60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"dk/internal/models/users"
|
|
"dk/internal/router"
|
|
"strings"
|
|
|
|
"github.com/valyala/fasthttp"
|
|
)
|
|
|
|
// RequireFighting ensures the user is in a fight when accessing fight routes
|
|
func RequireFighting() router.Middleware {
|
|
return func(next router.Handler) router.Handler {
|
|
return func(ctx router.Ctx, params []string) {
|
|
user, ok := ctx.UserValue("user").(*users.User)
|
|
if !ok || user == nil {
|
|
ctx.SetStatusCode(fasthttp.StatusUnauthorized)
|
|
ctx.SetBodyString("Not authenticated")
|
|
return
|
|
}
|
|
|
|
if !user.IsFighting() {
|
|
ctx.Redirect("/", 303)
|
|
return
|
|
}
|
|
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
}
|
|
|
|
// HandleFightRedirect redirects users to appropriate locations based on fight status
|
|
func HandleFightRedirect() router.Middleware {
|
|
return func(next router.Handler) router.Handler {
|
|
return func(ctx router.Ctx, params []string) {
|
|
user, ok := ctx.UserValue("user").(*users.User)
|
|
if !ok || user == nil {
|
|
next(ctx, params)
|
|
return
|
|
}
|
|
|
|
currentPath := string(ctx.URI().Path())
|
|
|
|
// If user is fighting and not on fight page, redirect to fight
|
|
if user.IsFighting() && !strings.HasPrefix(currentPath, "/fight") {
|
|
ctx.Redirect("/fight", 303)
|
|
return
|
|
}
|
|
|
|
// If user is not fighting and on fight page, redirect to home
|
|
if !user.IsFighting() && strings.HasPrefix(currentPath, "/fight") {
|
|
ctx.Redirect("/", 303)
|
|
return
|
|
}
|
|
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
}
|