// Package auth implements password hashing, Basic login, Bearer session // middleware and the authentication routes. package auth import ( "encoding/base64" "errors" "log/slog" "strings" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/model" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/session" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" "github.com/gofiber/fiber/v3" ) const ( basicChallenge = `Basic realm="messenger", charset="UTF-8"` bearerChallenge = `Bearer realm="messenger"` ) type Handler struct { store *store.Store sessions *session.Store } func NewHandler(st *store.Store, sessions *session.Store) *Handler { return &Handler{store: st, sessions: sessions} } func (h *Handler) CreateSession(c fiber.Ctx) error { username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization)) if !ok { return common.NewChallenge(basicChallenge, "invalid credentials") } user, err := h.store.GetUserByUsername(c.Context(), username) if err != nil { if common.IsCode(err, common.ErrorCodeNotFound) { // An unknown username returns before Argon2 runs, while a known // username with a wrong password runs VerifyPassword. The branches // therefore take different time, so username enumeration through // response timing is theoretically possible. The contract only // requires the same 401 body and challenge. return common.NewChallenge(basicChallenge, "invalid credentials") } return err } valid, err := VerifyPassword(user.PasswordHash, password) if err != nil || !valid { return common.NewChallenge(basicChallenge, "invalid credentials") } token, expiresAt, err := h.sessions.Create(c.Context(), user.ID) if err != nil { slog.Error("create session", "err", err) return common.Unavailable("session store unavailable") } return c.Status(fiber.StatusCreated).JSON(model.Session{ Token: token, TokenType: "Bearer", ExpiresAt: common.RFCFormTime(expiresAt), User: user, }) } func (h *Handler) RevokeSession(c fiber.Ctx) error { token, ok := common.SessionToken(c) if !ok { return common.NewChallenge(bearerChallenge, "authentication required") } if err := h.sessions.Revoke(c.Context(), token); err != nil { slog.Error("revoke session", "err", err) return common.Unavailable("session store unavailable") } return c.SendStatus(fiber.StatusNoContent) } func BearerAuth(sessions *session.Store) fiber.Handler { return func(c fiber.Ctx) error { header := strings.TrimSpace(c.Get(fiber.HeaderAuthorization)) scheme, token, found := strings.Cut(header, " ") token = strings.TrimSpace(token) if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t") { return common.NewChallenge(bearerChallenge, "authentication required") } userID, err := sessions.Lookup(c.Context(), token) if err != nil { if errors.Is(err, session.ErrNotFound) { return common.NewChallenge(bearerChallenge, "session expired or revoked") } slog.Error("session lookup", "err", err) return common.Unavailable("session store unavailable") } c.Locals(common.KeyUserID, userID) c.Locals(common.KeySessionToken, token) return c.Next() } } func parseBasic(header string) (string, string, bool) { scheme, encoded, found := strings.Cut(strings.TrimSpace(header), " ") if !found || !strings.EqualFold(scheme, "Basic") || encoded == "" { return "", "", false } decoded, err := base64.StdEncoding.DecodeString(encoded) if err != nil { if decoded, err = base64.RawStdEncoding.DecodeString(encoded); err != nil { return "", "", false } } // RFC 7617: split at the first colon; a colon is legal inside the password. username, password, found := strings.Cut(string(decoded), ":") if !found || username == "" || password == "" { return "", "", false } return username, password, true }