forked from mtusi2026/mtusi2026lab6
77 lines
2.1 KiB
Go
77 lines
2.1 KiB
Go
package fiber
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
|
)
|
|
|
|
const identityKey = "authenticated-user"
|
|
|
|
// HandleLogin structurally decodes Basic credentials and delegates authentication.
|
|
func (ctrl *Controller) HandleLogin(ctx *fiber.Ctx) error {
|
|
scheme, encoded, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ")
|
|
if !ok || !strings.EqualFold(scheme, "Basic") {
|
|
return service.ErrUnauthorized
|
|
}
|
|
decoded, err := base64.StdEncoding.DecodeString(encoded)
|
|
if err != nil {
|
|
return service.ErrUnauthorized
|
|
}
|
|
username, password, ok := strings.Cut(string(decoded), ":")
|
|
if !ok {
|
|
return service.ErrUnauthorized
|
|
}
|
|
if len(ctx.Body()) != 0 {
|
|
return service.ErrInvalid
|
|
}
|
|
session, err := ctrl.auth.Login(ctx.UserContext(), username, password)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return ctx.Status(http.StatusCreated).JSON(fiber.Map{
|
|
"token": session.Token,
|
|
"token_type": "Bearer",
|
|
"expires_at": session.ExpiresAt,
|
|
"user": userResponse(session.User),
|
|
})
|
|
}
|
|
|
|
// HandleLogout revokes the current authenticated token before returning no content.
|
|
func (ctrl *Controller) HandleLogout(ctx *fiber.Ctx) error {
|
|
if err := ctrl.auth.Logout(ctx.UserContext(), bearer(ctx)); err != nil {
|
|
return err
|
|
}
|
|
return ctx.SendStatus(http.StatusNoContent)
|
|
}
|
|
|
|
// bearer extracts a Bearer token without interpreting its identity or validity.
|
|
func bearer(ctx *fiber.Ctx) string {
|
|
scheme, token, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ")
|
|
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
|
return ""
|
|
}
|
|
return token
|
|
}
|
|
|
|
// identity reads only the identity produced by successful session authentication.
|
|
func identity(ctx *fiber.Ctx) string {
|
|
value, _ := ctx.Locals(identityKey).(string)
|
|
return value
|
|
}
|
|
|
|
// requestGroup selects a bounded policy group from the HTTP operation.
|
|
func requestGroup(ctx *fiber.Ctx) string {
|
|
if ctx.Path() == "/api/v1/users" || strings.HasPrefix(ctx.Path(), "/api/v1/auth/") {
|
|
return "auth"
|
|
}
|
|
if ctx.Method() == http.MethodGet {
|
|
return "read"
|
|
}
|
|
return "write"
|
|
}
|