Files
uptimesebi/internal/api/auth.go
T
Sebastian UnterschützandClaude Opus 5.5 db44fedc72 feat(api): add signup, login with totp and account security pages
Signup is limited to the first user by default (UPTIME_SIGNUP). TOTP
secrets are sealed with UPTIME_SECRET_KEYS and bound to the user id.

Closes #3
Closes #5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-21 23:55:23 +01:00

300 lines
7.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const (
mfaCookie = "__Host-mfa"
mfaTTL = 5 * time.Minute
)
type signupRequest struct {
Email string `json:"email" binding:"required,email,max=320"`
Password string `json:"password" binding:"required,max=1024"`
DisplayName string `json:"display_name" binding:"max=200"`
OrgName string `json:"org_name" binding:"required,max=200"`
OrgSlug string `json:"org_slug" binding:"required,max=63"`
}
func (s *Server) signup(c *gin.Context) {
var req signupRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
if !s.limit(c, "signup:"+c.ClientIP(), 10, time.Hour) {
return
}
if allowed, err := s.signupAllowed(ctx); err != nil {
internalError(c, err)
return
} else if !allowed {
fail(c, http.StatusForbidden, "signup_closed", "Registrierung ist deaktiviert.")
return
}
hash, err := auth.HashPassword(req.Password)
if errors.Is(err, auth.ErrPasswordTooShort) {
fail(c, http.StatusUnprocessableEntity, "password_too_short", err.Error())
return
} else if err != nil {
internalError(c, err)
return
}
orgID := uuid.New()
var user store.User
err = s.db.Tx(ctx, tenant.Org(orgID, uuid.Nil), func(q *store.Queries) error {
var err error
user, err = q.CreateUser(ctx, store.CreateUserParams{
Email: normalizeEmail(req.Email),
DisplayName: strings.TrimSpace(req.DisplayName),
PasswordHash: &hash,
})
if err != nil {
return err
}
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
return err
}
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true})
})
switch {
case isUniqueViolation(err, "users_email_key"):
fail(c, http.StatusConflict, "email_taken", "Diese E-Mail-Adresse ist bereits registriert.")
return
case isUniqueViolation(err, "orgs_slug_key"):
fail(c, http.StatusConflict, "slug_taken", "Dieser Kurzname ist bereits vergeben.")
return
case isCheckViolation(err):
fail(c, http.StatusUnprocessableEntity, "invalid_input", "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.")
return
case err != nil:
internalError(c, err)
return
}
s.startSession(c, user.ID, orgID)
}
func (s *Server) signupAllowed(ctx context.Context) (bool, error) {
switch s.cfg.Signup {
case config.SignupOpen:
return true, nil
case config.SignupFirstUser:
var exists bool
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
exists, err = q.AnyUserExists(ctx)
return err
})
return !exists, err
}
return false, nil
}
type loginRequest struct {
Email string `json:"email" binding:"required,max=320"`
Password string `json:"password" binding:"required,max=1024"`
}
func (s *Server) login(c *gin.Context) {
var req loginRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
email := normalizeEmail(req.Email)
if !s.limit(c, "login:ip:"+c.ClientIP(), 30, 15*time.Minute) || !s.limit(c, "login:email:"+email, 10, 15*time.Minute) {
return
}
var user store.User
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
user, err = q.GetUserByEmail(ctx, email)
return err
})
if errors.Is(err, pgx.ErrNoRows) || (err == nil && user.PasswordHash == nil) {
auth.BurnPasswordCheck(req.Password)
invalidCredentials(c)
return
}
if err != nil {
internalError(c, err)
return
}
ok, rehash, err := auth.VerifyPassword(*user.PasswordHash, req.Password)
if err != nil {
internalError(c, err)
return
}
if !ok || user.DisabledAt != nil {
invalidCredentials(c)
return
}
if rehash {
s.rehashPassword(ctx, user.ID, req.Password)
}
if user.TotpSecret != nil {
token := randomToken()
if err := s.rdb.Set(ctx, mfaKey(token), user.ID.String(), mfaTTL).Err(); err != nil {
internalError(c, err)
return
}
setCookie(c, mfaCookie, token, int(mfaTTL.Seconds()))
c.JSON(http.StatusOK, gin.H{"status": "totp_required"})
return
}
s.finishLogin(c, user.ID)
}
type totpRequest struct {
Code string `json:"code" binding:"required,len=6,numeric"`
}
func (s *Server) loginTOTP(c *gin.Context) {
var req totpRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
token, _ := c.Cookie(mfaCookie)
if token == "" {
fail(c, http.StatusUnauthorized, "mfa_expired", "Anmeldung abgelaufen, bitte erneut anmelden.")
return
}
if !s.limit(c, "mfa:"+mfaKey(token), 5, mfaTTL) {
return
}
raw, err := s.rdb.Get(ctx, mfaKey(token)).Result()
if err != nil {
fail(c, http.StatusUnauthorized, "mfa_expired", "Anmeldung abgelaufen, bitte erneut anmelden.")
return
}
userID, err := uuid.Parse(raw)
if err != nil {
internalError(c, err)
return
}
ok, err := s.verifyUserTOTP(ctx, userID, req.Code)
if err != nil {
internalError(c, err)
return
}
if !ok {
fail(c, http.StatusUnauthorized, "invalid_code", "Code ungültig.")
return
}
_ = s.rdb.Del(ctx, mfaKey(token)).Err()
setCookie(c, mfaCookie, "", -1)
s.finishLogin(c, userID)
}
func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) {
ctx := c.Request.Context()
var orgs []store.ListUserOrgsRow
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
var err error
orgs, err = q.ListUserOrgs(ctx, userID)
return err
})
if err != nil {
internalError(c, err)
return
}
var org uuid.UUID
if len(orgs) > 0 {
org = orgs[0].ID
}
s.startSession(c, userID, org)
}
func (s *Server) startSession(c *gin.Context, userID, orgID uuid.UUID) {
if old := auth.Current(c); old != nil {
_ = s.sessions.Delete(c.Request.Context(), old)
}
sess, err := s.sessions.Create(c.Request.Context(), userID, orgID)
if err != nil {
internalError(c, err)
return
}
auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds()))
c.JSON(http.StatusOK, gin.H{"status": "ok", "csrf_token": sess.CSRF})
}
func (s *Server) logout(c *gin.Context) {
if sess := auth.Current(c); sess != nil {
if err := s.sessions.Delete(c.Request.Context(), sess); err != nil {
internalError(c, err)
return
}
}
auth.ClearCookie(c)
c.Status(http.StatusNoContent)
}
func (s *Server) rehashPassword(ctx context.Context, user uuid.UUID, pw string) {
hash, err := auth.HashPassword(pw)
if err != nil {
return
}
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
return q.SetPasswordHash(ctx, store.SetPasswordHashParams{ID: user, PasswordHash: &hash})
})
if err != nil {
s.log.WarnContext(ctx, "password rehash failed", "error", err)
}
}
func (s *Server) limit(c *gin.Context, key string, n int, window time.Duration) bool {
ok, err := s.limiter.Allow(c.Request.Context(), key, n, window)
if err != nil {
internalError(c, err)
return false
}
if !ok {
c.Header("Retry-After", "60")
fail(c, http.StatusTooManyRequests, "rate_limited", "Zu viele Versuche, bitte später erneut.")
return false
}
return true
}
func mfaKey(token string) string {
sum := sha256.Sum256([]byte(token))
return "login_mfa:" + hex.EncodeToString(sum[:])
}
func normalizeEmail(e string) string { return strings.ToLower(strings.TrimSpace(e)) }
func invalidCredentials(c *gin.Context) {
fail(c, http.StatusUnauthorized, "invalid_credentials", "E-Mail oder Passwort falsch.")
}
func isUniqueViolation(err error, constraint string) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == constraint
}
func isCheckViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23514"
}