106 lines
2.5 KiB
Go
106 lines
2.5 KiB
Go
package auth
|
|
|
|
import (
|
|
sushi "git.sharkk.net/Sharkk/Sushi"
|
|
"git.sharkk.net/Sharkk/Sushi/session"
|
|
"github.com/valyala/fasthttp"
|
|
)
|
|
|
|
const UserCtxKey = "user"
|
|
|
|
// Middleware adds authentication handling
|
|
func Middleware(userLookup func(int) any) sushi.Middleware {
|
|
return func(next sushi.Handler) sushi.Handler {
|
|
return func(ctx sushi.Ctx, params []string) {
|
|
sess := session.GetCurrentSession(ctx)
|
|
if sess != nil && sess.UserID > 0 && userLookup != nil {
|
|
user := userLookup(sess.UserID)
|
|
if user != nil {
|
|
ctx.SetUserValue(UserCtxKey, user)
|
|
} else {
|
|
sess.SetUserID(0)
|
|
session.StoreSession(sess)
|
|
}
|
|
}
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
}
|
|
|
|
// RequireAuth middleware that redirects unauthenticated users
|
|
func RequireAuth(redirectPath ...string) sushi.Middleware {
|
|
redirect := "/login"
|
|
if len(redirectPath) > 0 && redirectPath[0] != "" {
|
|
redirect = redirectPath[0]
|
|
}
|
|
|
|
return func(next sushi.Handler) sushi.Handler {
|
|
return func(ctx sushi.Ctx, params []string) {
|
|
if !IsAuthenticated(ctx) {
|
|
ctx.Redirect(redirect, fasthttp.StatusFound)
|
|
return
|
|
}
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
}
|
|
|
|
// RequireGuest middleware that redirects authenticated users
|
|
func RequireGuest(redirectPath ...string) sushi.Middleware {
|
|
redirect := "/"
|
|
if len(redirectPath) > 0 && redirectPath[0] != "" {
|
|
redirect = redirectPath[0]
|
|
}
|
|
|
|
return func(next sushi.Handler) sushi.Handler {
|
|
return func(ctx sushi.Ctx, params []string) {
|
|
if IsAuthenticated(ctx) {
|
|
ctx.Redirect(redirect, fasthttp.StatusFound)
|
|
return
|
|
}
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
}
|
|
|
|
// IsAuthenticated checks if the current request is from an authenticated user
|
|
func IsAuthenticated(ctx sushi.Ctx) bool {
|
|
user := ctx.UserValue(UserCtxKey)
|
|
return user != nil
|
|
}
|
|
|
|
// GetCurrentUser returns the current authenticated user
|
|
func GetCurrentUser(ctx sushi.Ctx) any {
|
|
return ctx.UserValue(UserCtxKey)
|
|
}
|
|
|
|
// Login authenticates a user session
|
|
func Login(ctx sushi.Ctx, userID int, user any) {
|
|
sess := session.GetCurrentSession(ctx)
|
|
if sess != nil {
|
|
sess.SetUserID(userID)
|
|
sess.RegenerateID()
|
|
session.StoreSession(sess)
|
|
|
|
ctx.SetUserValue(session.SessionCtxKey, sess)
|
|
ctx.SetUserValue(UserCtxKey, user)
|
|
|
|
session.SetSessionCookie(ctx, sess.ID)
|
|
}
|
|
}
|
|
|
|
// Logout clears the user session
|
|
func Logout(ctx sushi.Ctx) {
|
|
sess := session.GetCurrentSession(ctx)
|
|
if sess != nil {
|
|
sess.SetUserID(0)
|
|
sess.RegenerateID()
|
|
session.StoreSession(sess)
|
|
|
|
ctx.SetUserValue(session.SessionCtxKey, sess)
|
|
session.SetSessionCookie(ctx, sess.ID)
|
|
}
|
|
|
|
ctx.SetUserValue(UserCtxKey, nil)
|
|
}
|