package middleware import ( "dk/internal/auth" "dk/internal/router" "dk/internal/users" "github.com/valyala/fasthttp" ) // Auth creates an authentication middleware func Auth(authManager *auth.AuthManager) router.Middleware { return func(next router.Handler) router.Handler { return func(ctx router.Ctx, params []string) { sessionID := auth.GetSessionCookie(ctx) if sessionID != "" { if session, exists := authManager.GetSession(sessionID); exists { // Update session activity authManager.UpdateSession(sessionID) // Get the full user object user, err := users.Find(session.UserID) if err == nil && user != nil { // Store session and user info in context ctx.SetUserValue("session", session) ctx.SetUserValue("user", user) // Refresh the cookie auth.SetSessionCookie(ctx, sessionID) } } } next(ctx, params) } } } // RequireAuth enforces authentication - redirect defaults to "/login" func RequireAuth(paths ...string) router.Middleware { redirect := "/login" if len(paths) > 0 && paths[0] != "" { redirect = paths[0] } return func(next router.Handler) router.Handler { return func(ctx router.Ctx, params []string) { if !IsAuthenticated(ctx) { ctx.Redirect(redirect, fasthttp.StatusFound) return } next(ctx, params) } } } // RequireGuest enforces no authentication - redirect defaults to "/" func RequireGuest(paths ...string) router.Middleware { redirect := "/" if len(paths) > 0 && paths[0] != "" { redirect = paths[0] } return func(next router.Handler) router.Handler { return func(ctx router.Ctx, params []string) { if IsAuthenticated(ctx) { ctx.Redirect(redirect, fasthttp.StatusFound) return } next(ctx, params) } } } // IsAuthenticated checks if the current request has a valid session func IsAuthenticated(ctx router.Ctx) bool { _, exists := ctx.UserValue("user").(*users.User) return exists } // GetCurrentUser returns the current authenticated user, or nil if not authenticated func GetCurrentUser(ctx router.Ctx) *users.User { if user, ok := ctx.UserValue("user").(*users.User); ok { return user } return nil } // GetCurrentSession returns the current session, or nil if not authenticated func GetCurrentSession(ctx router.Ctx) *auth.Session { if session, ok := ctx.UserValue("session").(*auth.Session); ok { return session } return nil } // Login creates a session and sets the cookie func Login(ctx router.Ctx, authManager *auth.AuthManager, user *users.User) { session := authManager.CreateSession(user) auth.SetSessionCookie(ctx, session.ID) // Set in context for immediate use ctx.SetUserValue("session", session) ctx.SetUserValue("user", user) } // Logout destroys the session and clears the cookie func Logout(ctx router.Ctx, authManager *auth.AuthManager) { sessionID := auth.GetSessionCookie(ctx) if sessionID != "" { authManager.DeleteSession(sessionID) } auth.DeleteSessionCookie(ctx) // Clear from context ctx.SetUserValue("session", nil) ctx.SetUserValue("user", nil) }