aboutsummaryrefslogtreecommitdiff
path: root/utils/auth/auth.go
blob: f92e9554e0ce51904930ed6bea6bf9a9a914f512 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package auth

import (
	"imageboard/config"
	"imageboard/models"
	"net/url"

	"github.com/gofiber/fiber/v2"
)

func GetCurrentUser(ctx *fiber.Ctx) *models.User {
	if user, ok := ctx.Locals("User").(*models.User); ok {
		return user
	}
	return nil
}

func IsAuthenticated(ctx *fiber.Ctx) bool {
	return GetCurrentUser(ctx) != nil
}

func GetRedirectURL(ctx *fiber.Ctx) string {
	next := ctx.Query("next")
	if next == "" {
		next = ctx.FormValue("next")
	}
	if next != "" && isValidRedirectURL(next) {
		return next
	}
	return config.URL_HOME
}

func isValidRedirectURL(redirectURL string) bool {
	if redirectURL == "" {
		return false
	}

	if redirectURL == config.URL_LOGIN || redirectURL == config.URL_REGISTER || redirectURL == config.URL_LOGOUT {
		return false
	}

	if redirectURL[0] == '/' {
		return true
	}

	return false
}

func GetLoginURLWithRedirect(ctx *fiber.Ctx) string {
	currentPath := ctx.Path()
	if queryString := string(ctx.Request().URI().QueryString()); queryString != "" {
		currentPath += "?" + queryString
	}
	return config.URL_LOGIN + "?next=" + url.QueryEscape(currentPath)
}

func GetLogoutURLWithRedirect(ctx *fiber.Ctx) string {
	currentPath := ctx.Path()
	if queryString := string(ctx.Request().URI().QueryString()); queryString != "" {
		currentPath += "?" + queryString
	}
	return config.URL_LOGOUT + "?next=" + url.QueryEscape(currentPath)
}