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
262 lines
6.6 KiB
Go
262 lines
6.6 KiB
Go
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
|
|
}
|