forked from mtusi2026/mtusi2026lab3
chore(app) transferred codebase from Lab2
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// KeyUserID is the request-scoped key set by the Bearer middleware.
|
||||
KeyUserID = "userID"
|
||||
// KeySessionToken is the raw token of the current request.
|
||||
KeySessionToken = "sessionToken"
|
||||
)
|
||||
|
||||
// UserID returns the authenticated user ID and whether the middleware set it.
|
||||
func UserID(c fiber.Ctx) (uuid.UUID, bool) {
|
||||
userID, ok := c.Locals(KeyUserID).(uuid.UUID)
|
||||
return userID, ok
|
||||
}
|
||||
|
||||
// MustUserID is for handlers mounted behind BearerAuth, where the middleware
|
||||
// guarantees the local. A missing value is a programming error, not a client
|
||||
// error, so it becomes a recovered 500 instead of an anonymous request.
|
||||
func MustUserID(c fiber.Ctx) uuid.UUID {
|
||||
userID, ok := UserID(c)
|
||||
if !ok {
|
||||
panic("common: authenticated user ID is missing from the request context")
|
||||
}
|
||||
return userID
|
||||
}
|
||||
|
||||
// SessionToken returns the raw bearer token of the current request.
|
||||
func SessionToken(c fiber.Ctx) (string, bool) {
|
||||
token, ok := c.Locals(KeySessionToken).(string)
|
||||
return token, ok && token != ""
|
||||
}
|
||||
Reference in New Issue
Block a user