cup/hooks/auth-check.go
Zeni Kim 10ded026df - Refactory cookie and API session handle. Insolated y routes and controllers (api-auth.go, app-auth.go).
- Cookie lifetime with sliding expiration
- Fix bug single global expiresAt in JWT, now each token has unique ExpiresAt
2026-09-12 21:26:01 -05:00

87 lines
2.4 KiB
Go

package hooks
import (
"errors"
"net/http"
"strings"
"git.smarteching.com/goffee/core"
"git.smarteching.com/goffee/cup/models"
"gorm.io/gorm"
)
var CheckSessionCookie core.Hook = func(c *core.Context) {
pass := false
// Validate the cookie based session through the core session. This also
// transparently performs sliding expiration renewal when applicable.
session := c.GetSession()
if session.Init(c) {
// ensure the authenticated user still exists in the database
var user models.User
res := c.GetGorm().Where("id = ?", session.GetUserID()).First(&user)
if res.Error == nil || errors.Is(res.Error, gorm.ErrRecordNotFound) {
pass = true
}
}
if pass {
c.Next()
} else {
c.Response.Redirect("/applogin").ForceSendResponse()
return
}
}
var APIAuthCheck core.Hook = func(c *core.Context) {
// --- API/bearer flow ---
tokenRaw := c.GetHeader("Authorization")
token := strings.TrimSpace(strings.Replace(tokenRaw, "Bearer", "", 1))
if token == "" {
c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
"message": "unauthorized",
})).ForceSendResponse()
return
}
payload, err := c.GetJWT().DecodeToken(token)
if err != nil {
c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
"message": "unauthorized",
})).ForceSendResponse()
return
}
userAgent := c.GetUserAgent()
hashedCacheKey := core.CreateAuthTokenHashedCacheKey(uint(c.CastToInt(payload["userID"])), userAgent)
cachedToken, err := c.GetCache().Get(hashedCacheKey)
if err != nil {
// user signed out
c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
"message": "unauthorized",
})).ForceSendResponse()
return
}
if cachedToken != token {
// using old token replaced with new one after recent signin
c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
"message": "unauthorized",
})).ForceSendResponse()
return
}
var user models.User
res := c.GetGorm().Where("id = ?", payload["userID"]).First(&user)
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
// error with the database
c.GetLogger().Error(res.Error.Error())
c.Response.SetStatusCode(http.StatusInternalServerError).Json(c.MapToJson(map[string]interface{}{
"message": "internal error",
})).ForceSendResponse()
return
}
c.Next()
}