Enabling TOTP returns ten codes that are shown once. Disabling TOTP and regenerating codes require the password plus a current code. Closes #40 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
313 lines
7.9 KiB
Go
313 lines
7.9 KiB
Go
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/i18n"
|
|
"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")
|
|
return
|
|
}
|
|
hash, err := auth.HashPassword(req.Password)
|
|
if errors.Is(err, auth.ErrPasswordTooShort) {
|
|
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
|
|
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,
|
|
Locale: ptr(i18n.Lang(ctx)),
|
|
})
|
|
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")
|
|
return
|
|
case isUniqueViolation(err, "orgs_slug_key"):
|
|
fail(c, http.StatusConflict, "slug_taken")
|
|
return
|
|
case isCheckViolation(err):
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_slug")
|
|
return
|
|
case err != nil:
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
s.startSession(c, user.ID, orgID, i18n.Lang(ctx))
|
|
}
|
|
|
|
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 := auth.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)
|
|
}
|
|
|
|
// secondFactorRequest carries a TOTP code or a recovery code.
|
|
type secondFactorRequest struct {
|
|
Code string `json:"code" binding:"required,max=32"`
|
|
}
|
|
|
|
type totpRequest struct {
|
|
Code string `json:"code" binding:"required,len=6,numeric"`
|
|
}
|
|
|
|
func (s *Server) loginTOTP(c *gin.Context) {
|
|
var req secondFactorRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
token, _ := c.Cookie(mfaCookie)
|
|
if token == "" {
|
|
fail(c, http.StatusUnauthorized, "mfa_expired")
|
|
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")
|
|
return
|
|
}
|
|
userID, err := uuid.Parse(raw)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
ok, err := s.verifySecondFactor(ctx, userID, req.Code)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if !ok {
|
|
fail(c, http.StatusUnauthorized, "invalid_code")
|
|
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 (
|
|
user store.User
|
|
orgs []store.ListUserOrgsRow
|
|
)
|
|
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
|
|
var err error
|
|
if user, err = q.GetUser(ctx, userID); err != nil {
|
|
return err
|
|
}
|
|
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, deref(user.Locale))
|
|
}
|
|
|
|
func (s *Server) startSession(c *gin.Context, userID, orgID uuid.UUID, locale string) {
|
|
if old := auth.Current(c); old != nil {
|
|
_ = s.sessions.Delete(c.Request.Context(), old)
|
|
}
|
|
sess, err := s.sessions.Create(c.Request.Context(), userID, orgID, locale)
|
|
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")
|
|
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")
|
|
}
|
|
|
|
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"
|
|
}
|