Fixed session duration
Use HttpOnly and SameSite
Added cookie refresh on all pages
This commit is contained in:
0xCA 2023-12-28 11:47:19 +05:00
parent 45849a2aee
commit 6292424591
3 changed files with 63 additions and 11 deletions

View file

@ -93,18 +93,24 @@ func Login(db store.IStore) echo.HandlerFunc {
}
if userCorrect && passwordCorrect {
// TODO: refresh the token
ageMax := 0
expiration := time.Now().Add(24 * time.Hour)
if rememberMe {
ageMax = 86400
expiration.Add(144 * time.Hour)
ageMax = 86400 * 7
expiration = time.Now().Add(time.Duration(ageMax) * time.Second)
}
cookiePath := util.BasePath
if cookiePath == "" {
cookiePath = "/"
}
sess, _ := session.Get("session", c)
sess.Options = &sessions.Options{
Path: util.BasePath,
Path: cookiePath,
MaxAge: ageMax,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
// set session_token
@ -117,8 +123,11 @@ func Login(db store.IStore) echo.HandlerFunc {
// set session_token in cookie
cookie := new(http.Cookie)
cookie.Name = "session_token"
cookie.Path = cookiePath
cookie.Value = tokenUID
cookie.Expires = expiration
cookie.HttpOnly = true
cookie.SameSite = http.SameSiteLaxMode
c.SetCookie(cookie)
return c.JSON(http.StatusOK, jsonHTTPResponse{true, "Logged in successfully"})

View file

@ -3,7 +3,9 @@ package handler
import (
"fmt"
"net/http"
"time"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/ngoduykhanh/wireguard-ui/util"
@ -23,6 +25,13 @@ func ValidSession(next echo.HandlerFunc) echo.HandlerFunc {
}
}
func RefreshSession(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
doRefreshSession(c)
return next(c)
}
}
func NeedsAdmin(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !isAdmin(c) {
@ -44,6 +53,40 @@ func isValidSession(c echo.Context) bool {
return true
}
func doRefreshSession(c echo.Context) {
if util.DisableLogin {
return
}
sess, _ := session.Get("session", c)
oldCookie, err := c.Cookie("session_token")
if err != nil || sess.Values["session_token"] != oldCookie.Value {
return
}
cookiePath := util.BasePath
if cookiePath == "" {
cookiePath = "/"
}
sess.Options = &sessions.Options{
Path: cookiePath,
MaxAge: sess.Options.MaxAge,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
sess.Save(c.Request(), c.Response())
cookie := new(http.Cookie)
cookie.Name = "session_token"
cookie.Path = cookiePath
cookie.Value = oldCookie.Value
cookie.Expires = time.Now().Add(time.Duration(sess.Options.MaxAge) * time.Second)
cookie.HttpOnly = true
cookie.SameSite = http.SameSiteLaxMode
c.SetCookie(cookie)
}
// currentUser to get username of logged in user
func currentUser(c echo.Context) string {
if util.DisableLogin {