58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
package auth
|
|
|
|
import (
|
|
sushi "git.sharkk.net/Sharkk/Sushi"
|
|
"github.com/valyala/fasthttp"
|
|
)
|
|
|
|
const UserCtxKey = "user"
|
|
|
|
// Middleware adds authentication handling
|
|
func Middleware(userLookup func(int) any) sushi.Middleware {
|
|
return func(ctx sushi.Ctx, next func()) {
|
|
sess := sushi.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)
|
|
sushi.StoreSession(sess)
|
|
}
|
|
}
|
|
next()
|
|
}
|
|
}
|
|
|
|
// 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(ctx sushi.Ctx, next func()) {
|
|
if !ctx.IsAuthenticated() {
|
|
ctx.Redirect(redirect, fasthttp.StatusFound)
|
|
return
|
|
}
|
|
next()
|
|
}
|
|
}
|
|
|
|
// RequireGuest middleware that redirects authenticated users
|
|
func RequireGuest(redirectPath ...string) sushi.Middleware {
|
|
redirect := "/"
|
|
if len(redirectPath) > 0 && redirectPath[0] != "" {
|
|
redirect = redirectPath[0]
|
|
}
|
|
|
|
return func(ctx sushi.Ctx, next func()) {
|
|
if ctx.IsAuthenticated() {
|
|
ctx.Redirect(redirect, fasthttp.StatusFound)
|
|
return
|
|
}
|
|
next()
|
|
}
|
|
}
|