Set token cookies on user login

This commit is contained in:
2025-02-10 22:47:20 +11:00
parent e73805a02d
commit 750de24fd1
3 changed files with 42 additions and 13 deletions

View File

@@ -2,13 +2,17 @@ package cookies
import (
"net/http"
"projectreshoot/config"
"time"
"projectreshoot/config"
"projectreshoot/db"
"projectreshoot/jwt"
"github.com/pkg/errors"
)
// Get the value of the access and refresh tokens
func GetTokens(
w http.ResponseWriter,
func GetTokenStrings(
r *http.Request,
) (acc string, ref string) {
accCookie, accErr := r.Cookie("access")
@@ -27,22 +31,46 @@ func GetTokens(
}
// Set a token with the provided details
func SetToken(
func setToken(
w http.ResponseWriter,
r *http.Request,
config *config.Config,
token string,
scope string,
exp int64,
rememberme bool,
) {
tokenCookie := &http.Cookie{
Name: scope,
Value: token,
Path: "/",
Expires: time.Unix(exp, 0),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: config.SSL,
}
if rememberme {
tokenCookie.Expires = time.Unix(exp, 0)
}
http.SetCookie(w, tokenCookie)
}
// Generate new tokens for the user and set them as cookies
func SetTokenCookies(
w http.ResponseWriter,
r *http.Request,
config *config.Config,
user *db.User,
rememberMe bool,
) error {
at, atexp, err := jwt.GenerateAccessToken(config, user, true, rememberMe)
if err != nil {
return errors.Wrap(err, "jwt.GenerateAccessToken")
}
rt, rtexp, err := jwt.GenerateRefreshToken(config, user, rememberMe)
if err != nil {
return errors.Wrap(err, "jwt.GenerateRefreshToken")
}
// Don't set the cookies until we know no errors occured
setToken(w, config, at, "access", atexp, rememberMe)
setToken(w, config, rt, "refresh", rtexp, rememberMe)
return nil
}