Feat v0.6.9 cookie fix roadmap (#44)
Co-authored-by: Jeffrey Smith <jasafpro@gmail.com> Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
This commit was merged in pull request #44.
This commit is contained in:
@@ -142,9 +142,30 @@ func parseAndValidateJWT(tokenString string, jwtSecret string) (*Claims, bool) {
|
||||
return claims, true
|
||||
}
|
||||
|
||||
// parseJWTIgnoringExpiry parses a JWT and validates the signature but
|
||||
// tolerates an expired token. Used by page-auth middleware so the Go
|
||||
// template can render the page shell even when the access token has
|
||||
// lapsed — the Preact SDK will refresh the token client-side.
|
||||
// Returns (claims, signatureValid). A tampered or unsigned token
|
||||
// returns (nil, false).
|
||||
func parseJWTIgnoringExpiry(tokenString string, jwtSecret string) (*Claims, bool) {
|
||||
claims := &Claims{}
|
||||
_, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return []byte(jwtSecret), nil
|
||||
}, jwt.WithoutClaimsValidation())
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return claims, true
|
||||
}
|
||||
|
||||
// UserIDFromCookie extracts the user ID from the arm_token cookie without
|
||||
// requiring authentication. Returns "" if no valid token is found.
|
||||
// Used by unauthenticated routes that want optional user context.
|
||||
// Tolerates expired tokens (signature must be valid) so that user preferences
|
||||
// still apply even when the access token has lapsed.
|
||||
func UserIDFromCookie(c *gin.Context, jwtSecret string) string {
|
||||
cookie, err := c.Cookie("arm_token")
|
||||
if err != nil || cookie == "" {
|
||||
@@ -152,7 +173,11 @@ func UserIDFromCookie(c *gin.Context, jwtSecret string) string {
|
||||
}
|
||||
claims, ok := parseAndValidateJWT(cookie, jwtSecret)
|
||||
if !ok {
|
||||
return ""
|
||||
// Accept expired-but-signed token for optional user context
|
||||
claims, ok = parseJWTIgnoringExpiry(cookie, jwtSecret)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return claims.UserID
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user