forked from mtusi2026/mtusi2026lab5
40 lines
894 B
Go
40 lines
894 B
Go
package common
|
|
|
|
import (
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const (
|
|
KeyUserID = "userID"
|
|
KeySessionToken = "sessionToken"
|
|
)
|
|
|
|
func UserID(c fiber.Ctx) (uuid.UUID, bool) {
|
|
userID, ok := c.Locals(KeyUserID).(uuid.UUID)
|
|
return userID, ok
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
func SessionToken(c fiber.Ctx) (string, bool) {
|
|
token, ok := c.Locals(KeySessionToken).(string)
|
|
return token, ok && token != ""
|
|
}
|
|
|
|
// PathUUID parses a UUID path parameter. A malformed value is a contract
|
|
// invalid_request, not a lookup failure.
|
|
func PathUUID(c fiber.Ctx, name string) (uuid.UUID, error) {
|
|
id, err := uuid.Parse(c.Params(name))
|
|
if err != nil {
|
|
return uuid.Nil, BadRequest("invalid " + name + " format")
|
|
}
|
|
return id, nil
|
|
}
|