- Refactory cookie and API session handle. Insolated y routes and controllers (api-auth.go, app-auth.go).
- Cookie lifetime with sliding expiration - Fix bug single global expiresAt in JWT, now each token has unique ExpiresAt
This commit is contained in:
parent
ab7c00575c
commit
0e20a17ce9
5 changed files with 241 additions and 86 deletions
27
cookies.go
27
cookies.go
|
|
@ -86,7 +86,24 @@ func GetCookie(r *http.Request) (UserCookie, error) {
|
|||
|
||||
// SetCookie sets an encrypted cookie with a user's email and token, using gob encoding for data serialization.
|
||||
// The Secure flag is controlled by the COOKIE_SECURE environment variable (defaults to true, set to false for local HTTP development).
|
||||
// The cookie lifetime is derived from JWT_LIFESPAN_MINUTES.
|
||||
func SetCookie(w http.ResponseWriter, email string, token string) error {
|
||||
// Derive cookie MaxAge from JWT_LIFESPAN_MINUTES (default: 1440 min = 1 day)
|
||||
maxAge := 1440 * 60 // default 1 day in seconds
|
||||
lifetimeStr := os.Getenv("JWT_LIFESPAN_MINUTES")
|
||||
if lifetimeStr != "" {
|
||||
lifetime, parseErr := strconv.Atoi(lifetimeStr)
|
||||
if parseErr == nil {
|
||||
maxAge = lifetime * 60 // convert minutes to seconds
|
||||
}
|
||||
}
|
||||
return SetCookieWithMaxAge(w, email, token, maxAge)
|
||||
}
|
||||
|
||||
// SetCookieWithMaxAge sets the encrypted "goffee" cookie with an explicit lifetime in seconds.
|
||||
// It is used for sliding session renewal, where the cookie expiration must be refreshed
|
||||
// to a full lifetime from the moment of renewal.
|
||||
func SetCookieWithMaxAge(w http.ResponseWriter, email string, token string, maxAge int) error {
|
||||
var err error
|
||||
|
||||
// check if template engine is enable
|
||||
|
|
@ -124,16 +141,6 @@ func SetCookie(w http.ResponseWriter, email string, token string) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// Derive cookie MaxAge from JWT_LIFESPAN_MINUTES (default: 1440 min = 1 day)
|
||||
maxAge := 1440 * 60 // default 1 day in seconds
|
||||
lifetimeStr := os.Getenv("JWT_LIFESPAN_MINUTES")
|
||||
if lifetimeStr != "" {
|
||||
lifetime, parseErr := strconv.Atoi(lifetimeStr)
|
||||
if parseErr == nil {
|
||||
maxAge = lifetime * 60 // convert minutes to seconds
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if the cookie should have the Secure flag.
|
||||
// Set COOKIE_SECURE=false (or "0", "f") in your .env for local development over HTTP.
|
||||
// Defaults to true for production safety.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue