forked from ngoduykhanh/wireguard-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
55 lines (48 loc) · 1.31 KB
/
session.go
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
package handler
import (
"fmt"
"net/http"
"github.com/aokimio/wireguard-ui/util"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
func ValidSession(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !isValidSession(c) {
nextURL := c.Request().URL
if nextURL != nil && c.Request().Method == http.MethodGet {
return c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf(util.BasePath+"/login?next=%s", c.Request().URL))
} else {
return c.Redirect(http.StatusTemporaryRedirect, util.BasePath+"/login")
}
}
return next(c)
}
}
func isValidSession(c echo.Context) bool {
if util.DisableLogin {
return true
}
sess, _ := session.Get("session", c)
cookie, err := c.Cookie("session_token")
if err != nil || sess.Values["session_token"] != cookie.Value {
return false
}
return true
}
// currentUser to get username of logged in user
func currentUser(c echo.Context) string {
if util.DisableLogin {
return ""
}
sess, _ := session.Get("session", c)
username := fmt.Sprintf("%s", sess.Values["username"])
return username
}
// clearSession to remove current session
func clearSession(c echo.Context) {
sess, _ := session.Get("session", c)
sess.Values["username"] = ""
sess.Values["session_token"] = ""
sess.Save(c.Request(), c.Response())
}