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
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-21 23:55:23 +01:00
1 parent 99e9b1e57d
commit db44fedc72
18 files changed
+1792 -91

No files matched your search

+299
View File
@@ -0,0 +1,299 @@
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"
}
+261
View File
@@ -0,0 +1,261 @@
package api
import (
"bytes"
"context"
"encoding/base64"
"errors"
"image/png"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/pquerna/otp"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const totpSetupTTL = 10 * time.Minute
type orgView struct {
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
IsOwner bool `json:"is_owner"`
RequireTOTP bool `json:"require_totp"`
}
type meView struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
TOTP bool `json:"totp_enabled"`
ActiveOrg uuid.UUID `json:"active_org"`
Orgs []orgView `json:"orgs"`
// Set when an org the user belongs to enforces TOTP and the user has none.
TOTPEnrollmentRequired bool `json:"totp_enrollment_required"`
}
func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error) {
var me meView
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
u, err := q.GetUser(ctx, sess.UserID)
if err != nil {
return err
}
orgs, err := q.ListUserOrgs(ctx, sess.UserID)
if err != nil {
return err
}
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}}
for _, o := range orgs {
me.Orgs = append(me.Orgs, orgView{ID: o.ID, Slug: o.Slug, Name: o.Name, IsOwner: o.IsOwner, RequireTOTP: o.RequireTotp})
if o.RequireTotp && !me.TOTP {
me.TOTPEnrollmentRequired = true
}
}
return nil
})
return me, err
}
func (s *Server) me(c *gin.Context) {
me, err := s.loadMe(c.Request.Context(), auth.Current(c))
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, me)
}
type switchOrgRequest struct {
OrgID uuid.UUID `json:"org_id" binding:"required"`
}
func (s *Server) switchOrg(c *gin.Context) {
var req switchOrgRequest
if !bind(c, &req) {
return
}
sess := auth.Current(c)
me, err := s.loadMe(c.Request.Context(), sess)
if err != nil {
internalError(c, err)
return
}
for _, o := range me.Orgs {
if o.ID == req.OrgID {
if err := s.sessions.SwitchOrg(c.Request.Context(), sess, o.ID); err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
return
}
}
fail(c, http.StatusNotFound, "org_not_found", "Organisation nicht gefunden.")
}
func totpSetupKey(user uuid.UUID) string { return "totp_setup:" + user.String() }
func (s *Server) totpSetup(c *gin.Context) {
ctx := c.Request.Context()
me, err := s.loadMe(ctx, auth.Current(c))
if err != nil {
internalError(c, err)
return
}
if me.TOTP {
fail(c, http.StatusConflict, "totp_already_enabled", "TOTP ist bereits aktiv.")
return
}
key, err := auth.NewTOTPKey(me.Email)
if err != nil {
internalError(c, err)
return
}
if err := s.rdb.Set(ctx, totpSetupKey(me.ID), key.Secret(), totpSetupTTL).Err(); err != nil {
internalError(c, err)
return
}
qr, err := qrDataURI(key)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"secret": key.Secret(), "otpauth_url": key.URL(), "qr": qr})
}
func (s *Server) totpEnable(c *gin.Context) {
var req totpRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
sess := auth.Current(c)
secret, err := s.rdb.Get(ctx, totpSetupKey(sess.UserID)).Result()
if err != nil {
fail(c, http.StatusConflict, "totp_setup_expired", "Einrichtung abgelaufen, bitte neu starten.")
return
}
if !s.limit(c, "totp_enable:"+sess.UserID.String(), 10, totpSetupTTL) {
return
}
ok, err := s.totp.Verify(ctx, sess.UserID, secret, req.Code)
if err != nil {
internalError(c, err)
return
}
if !ok {
fail(c, http.StatusUnprocessableEntity, "invalid_code", "Code ungültig.")
return
}
sealedSecret := s.keys.Seal([]byte(secret), sess.UserID[:])
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return q.EnableTOTP(ctx, store.EnableTOTPParams{ID: sess.UserID, TotpSecret: sealedSecret})
})
if err != nil {
internalError(c, err)
return
}
_ = s.rdb.Del(ctx, totpSetupKey(sess.UserID)).Err()
c.Status(http.StatusNoContent)
}
type totpDisableRequest struct {
Password string `json:"password" binding:"required,max=1024"`
Code string `json:"code" binding:"required,len=6,numeric"`
}
func (s *Server) totpDisable(c *gin.Context) {
var req totpDisableRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
sess := auth.Current(c)
if !s.limit(c, "totp_disable:"+sess.UserID.String(), 5, 15*time.Minute) {
return
}
me, err := s.loadMe(ctx, sess)
if err != nil {
internalError(c, err)
return
}
for _, o := range me.Orgs {
if o.RequireTOTP {
fail(c, http.StatusConflict, "totp_required_by_org", "Eine deiner Organisationen verlangt TOTP.")
return
}
}
var user store.User
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
user, err = q.GetUser(ctx, sess.UserID)
return err
})
if err != nil {
internalError(c, err)
return
}
if user.PasswordHash == nil {
fail(c, http.StatusConflict, "no_password", "Konto ohne Passwort.")
return
}
if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok {
invalidCredentials(c)
return
}
if ok, err := s.verifyUserTOTP(ctx, sess.UserID, req.Code); err != nil {
internalError(c, err)
return
} else if !ok {
fail(c, http.StatusUnauthorized, "invalid_code", "Code ungültig.")
return
}
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return q.DisableTOTP(ctx, sess.UserID)
})
if err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
var errNoTOTP = errors.New("api: user has no totp")
func (s *Server) verifyUserTOTP(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
var user store.User
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
var err error
user, err = q.GetUser(ctx, userID)
return err
})
if err != nil {
return false, err
}
if user.TotpSecret == nil {
return false, errNoTOTP
}
secret, err := s.keys.Open(user.TotpSecret, userID[:])
if err != nil {
return false, err
}
return s.totp.Verify(ctx, userID, string(secret), code)
}
func qrDataURI(key *otp.Key) (string, error) {
img, err := key.Image(240, 240)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
return "", err
}
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}
+82
View File
@@ -0,0 +1,82 @@
package api
import (
"net/http"
"github.com/a-h/templ"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
func (s *Server) RegisterPages(r gin.IRouter) {
r.GET("/login", s.loginPage)
r.GET("/signup", s.signupPage)
r.GET("/", s.page("Übersicht", web.Dashboard))
r.GET("/settings/security", s.page("Sicherheit", web.Security))
}
func pageFor(c *gin.Context, title string) web.Page {
p := web.Page{Title: title}
if sess := auth.Current(c); sess != nil {
p.CSRF = sess.CSRF
}
return p
}
func (s *Server) loginPage(c *gin.Context) {
if auth.Current(c) != nil {
c.Redirect(http.StatusSeeOther, "/")
return
}
allowed, err := s.signupAllowed(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.Login(pageFor(c, "Anmelden"), allowed))
}
func (s *Server) signupPage(c *gin.Context) {
allowed, err := s.signupAllowed(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
if !allowed {
c.Redirect(http.StatusSeeOther, "/login")
return
}
web.Render(c, http.StatusOK, web.Signup(pageFor(c, "Konto anlegen")))
}
func (s *Server) page(title string, view func(web.Page, web.Me) templ.Component) gin.HandlerFunc {
return func(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
me, err := s.loadMe(c.Request.Context(), sess)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, view(pageFor(c, title), toWebMe(me)))
}
}
func toWebMe(m meView) web.Me {
out := web.Me{
Email: m.Email,
DisplayName: m.DisplayName,
TOTP: m.TOTP,
ActiveOrg: m.ActiveOrg.String(),
TOTPMissing: m.TOTPEnrollmentRequired,
}
for _, o := range m.Orgs {
out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner})
}
return out
}
+101
View File
@@ -0,0 +1,101 @@
package api
import (
"errors"
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/redis/go-redis/v9"
"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/sealed"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
type Server struct {
cfg config.API
log *slog.Logger
db *tenant.DB
rdb redis.UniversalClient
keys *sealed.Keyring
sessions *auth.Sessions
limiter *auth.Limiter
totp *auth.TOTPVerifier
}
func New(cfg config.API, log *slog.Logger, db *tenant.DB, rdb redis.UniversalClient, keys *sealed.Keyring) *Server {
return &Server{
cfg: cfg,
log: log,
db: db,
rdb: rdb,
keys: keys,
sessions: auth.NewSessions(rdb, cfg.SessionIdle, cfg.SessionAbsolute),
limiter: auth.NewLimiter(rdb),
totp: auth.NewTOTPVerifier(rdb),
}
}
func (s *Server) Sessions() *auth.Sessions { return s.sessions }
// Register mounts the JSON API. The caller must already have installed
// Sessions().Load() and auth.CSRF() on the engine.
func (s *Server) Register(r gin.IRouter) {
v1 := r.Group("/api/v1")
a := v1.Group("/auth")
a.POST("/signup", s.signup)
a.POST("/login", s.login)
a.POST("/login/totp", s.loginTOTP)
a.POST("/logout", s.logout)
me := v1.Group("/me", auth.Require())
me.GET("", s.me)
me.POST("/org", s.switchOrg)
me.POST("/totp/setup", s.totpSetup)
me.POST("/totp/enable", s.totpEnable)
me.POST("/totp/disable", s.totpDisable)
}
type apiError struct {
Error string `json:"error"`
Message string `json:"message"`
Fields map[string]string `json:"fields,omitempty"`
}
func fail(c *gin.Context, status int, code, msg string) {
c.AbortWithStatusJSON(status, apiError{Error: code, Message: msg})
}
func internalError(c *gin.Context, err error) {
_ = c.Error(err)
c.AbortWithStatusJSON(http.StatusInternalServerError, apiError{Error: "internal", Message: "Interner Fehler."})
}
func bind(c *gin.Context, dst any) bool {
if err := c.ShouldBindJSON(dst); err != nil {
e := apiError{Error: "invalid_input", Message: "Eingaben prüfen."}
var ve validator.ValidationErrors
if errors.As(err, &ve) {
e.Fields = map[string]string{}
for _, f := range ve {
e.Fields[f.Field()] = f.Tag()
}
}
c.AbortWithStatusJSON(http.StatusBadRequest, e)
return false
}
return true
}
func setCookie(c *gin.Context, name, value string, maxAge int) {
http.SetCookie(c.Writer, &http.Cookie{
Name: name, Value: value, Path: "/", MaxAge: maxAge,
Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode,
})
}
func randomToken() string { return auth.RandomToken() }