Feat v0.6.6 final hardening (#41)
All checks were successful
All checks were successful
Co-authored-by: Jeffrey Smith <jasafpro@gmail.com> Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
This commit was merged in pull request #41.
This commit is contained in:
@@ -97,6 +97,64 @@ func RequireAdminPage(stores store.Stores) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// OptionalAuth authenticates the user if a valid token is present (cookie,
|
||||
// header, or query param) but allows anonymous pass-through otherwise.
|
||||
// Use for page routes that should be accessible by both authenticated users
|
||||
// and anonymous visitors (e.g. public workflow entry pages).
|
||||
func OptionalAuth(cfg *config.Config, users store.UserStore, cache *UserStatusCache) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !database.IsConnected() {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := ""
|
||||
if cookie, err := c.Cookie("sb_token"); err == nil && cookie != "" {
|
||||
tokenString = cookie
|
||||
}
|
||||
if tokenString == "" {
|
||||
header := c.GetHeader("Authorization")
|
||||
if strings.HasPrefix(header, "Bearer ") {
|
||||
tokenString = strings.TrimPrefix(header, "Bearer ")
|
||||
}
|
||||
}
|
||||
if tokenString == "" {
|
||||
tokenString = c.Query("token")
|
||||
}
|
||||
|
||||
// No token → anonymous pass-through
|
||||
if tokenString == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := parseAndValidateJWT(tokenString, cfg.JWTSecret)
|
||||
if !ok {
|
||||
// Invalid token → treat as anonymous
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
if claims.UserID != "" {
|
||||
if entry, hit := cache.get(claims.UserID); hit {
|
||||
if entry.isActive {
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("email", claims.Email)
|
||||
}
|
||||
} else {
|
||||
user, err := users.GetByID(c.Request.Context(), claims.UserID)
|
||||
if err == nil && user.IsActive {
|
||||
cache.set(claims.UserID, true)
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("email", claims.Email)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func redirectToLogin(c *gin.Context, loginPath string) {
|
||||
// Save intended destination for post-login redirect
|
||||
intended := c.Request.URL.Path
|
||||
|
||||
Reference in New Issue
Block a user