forked from mtusi2026/mtusi2026lab2
37 lines
1.1 KiB
Go
37 lines
1.1 KiB
Go
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 != ""
|
|
}
|