package auth import ( "encoding/base64" "errors" "strings" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/log" ) const basicChallenge = `Basic realm="messenger", charset="UTF-8"` const 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} } // AGENT: CreateSession is the only endpoint that accepts Basic auth. It reads // no JSON body and returns the same 401 for an unknown user and a wrong // password, so the response does not reveal which usernames exist. func (h *Handler) CreateSession(c fiber.Ctx) error { username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization)) if !ok { return common.SendChallenge(c, basicChallenge, "invalid credentials") } user, err := h.store.GetUserByUsername(c.Context(), username) if err != nil { if common.IsCode(err, common.ErrorCodeNotFound) { return common.SendChallenge(c, basicChallenge, "invalid credentials") } return common.SendAppError(c, err) } valid, err := VerifyPassword(user.PasswordHash, password) if err != nil || !valid { return common.SendChallenge(c, basicChallenge, "invalid credentials") } token, expiresAt, err := h.sessions.Create(c.Context(), user.ID) if err != nil { log.Errorf("create session: %v", err) return common.SendError(c, fiber.StatusServiceUnavailable, common.ErrorCodeUnavailable, "session store unavailable") } return c.Status(fiber.StatusCreated).JSON(model.Session{ Token: token, TokenType: "Bearer", ExpiresAt: common.RFCFormTime(expiresAt), User: user, }) } // RevokeSession deletes the current token. The middleware has already proven // that the token exists, so a repeated DELETE is a 401, not a 204. func (h *Handler) RevokeSession(c fiber.Ctx) error { token, ok := common.SessionToken(c) if !ok { return common.SendChallenge(c, bearerChallenge, "authentication required") } if err := h.sessions.Revoke(c.Context(), token); err != nil { log.Errorf("revoke session: %v", err) return common.SendError(c, fiber.StatusServiceUnavailable, common.ErrorCodeUnavailable, "session store unavailable") } return c.SendStatus(fiber.StatusNoContent) } // BearerAuth accepts only an opaque Bearer token. X-User-Id is deliberately // never read: with lab 2 it can neither create nor override an identity. 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.SendChallenge(c, bearerChallenge, "authentication required") } userID, err := sessions.Lookup(c.Context(), token) if err != nil { if errors.Is(err, session.ErrNotFound) { return common.SendChallenge(c, bearerChallenge, "session expired or revoked") } // AGENT: A dead Redis must not degrade to "anonymous allowed". // Protected calls get a bounded 503 instead of a 401 or a bypass. log.Errorf("session lookup: %v", err) return common.SendError(c, fiber.StatusServiceUnavailable, common.ErrorCodeUnavailable, "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 }