package api import ( "context" "crypto/sha256" "encoding/hex" "errors" "net" "net/http" "net/url" "strings" "time" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/redis/go-redis/v9" "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/notify" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) // New accounts confirm their email address before signing in, through a // link mailed to them. One mailbox holds one account, aliases included, // and a client address may create only a few accounts a day. const ( verifyTTL = 24 * time.Hour // unverifiedKeep is how long an account waits for confirmation. unverifiedKeep = 7 * 24 * time.Hour ) // emailKey identifies the mailbox behind an address: +suffixes are dropped // everywhere, and Gmail ignores dots and treats googlemail.com as gmail.com. // The migration adding users.email_key computes the same. func emailKey(email string) string { local, domain, ok := strings.Cut(strings.ToLower(strings.TrimSpace(email)), "@") if !ok { return strings.ToLower(email) } local, _, _ = strings.Cut(local, "+") if domain == "gmail.com" || domain == "googlemail.com" { local, domain = strings.ReplaceAll(local, ".", ""), "gmail.com" } return local + "@" + domain } // clientKey groups client addresses for sign-up limits: IPv6 clients // usually hold a whole /64. func clientKey(ip string) string { a := net.ParseIP(ip) if a == nil || a.To4() != nil { return ip } return a.Mask(net.CIDRMask(64, 128)).String() + "/64" } // verificationRequired reports whether new accounts confirm their email. func (s *Server) verificationRequired() bool { switch s.cfg.SignupVerify { case "required": return true case "off": return false } return s.cloud() || s.smtp != nil } // signupsLeft reports whether the client may create another account. func (s *Server) signupsLeft(c *gin.Context) (bool, error) { if s.cfg.SignupsPerIP == 0 { return true, nil } n, err := s.rdb.Get(c.Request.Context(), "signups:"+clientKey(c.ClientIP())).Int() if errors.Is(err, redis.Nil) { return true, nil } return n < s.cfg.SignupsPerIP, err } // countSignup counts a created account against the client's daily limit. func (s *Server) countSignup(c *gin.Context) { if s.cfg.SignupsPerIP == 0 { return } ctx := c.Request.Context() key := "signups:" + clientKey(c.ClientIP()) pipe := s.rdb.TxPipeline() pipe.Incr(ctx, key) pipe.ExpireNX(ctx, key, 24*time.Hour) if _, err := pipe.Exec(ctx); err != nil { s.log.WarnContext(ctx, "counting sign-up failed", "error", err) } } func verifyKey(token string) string { sum := sha256.Sum256([]byte(token)) return "verify:" + hex.EncodeToString(sum[:]) } // sendVerification mails u a link that confirms their address. func (s *Server) sendVerification(ctx context.Context, u store.User) error { if s.smtp == nil { return errors.New("api: no mail server to send verification") } token := auth.RandomToken() if err := s.rdb.Set(ctx, verifyKey(token), u.ID.String(), verifyTTL).Err(); err != nil { return err } l := s.catalog.Match(deref(u.Locale)) link := strings.TrimSuffix(s.cfg.PublicURL, "/") + "/verify?token=" + url.QueryEscape(token) data := map[string]any{"Link": link, "Hours": int(verifyTTL.Hours())} return s.smtp.Send(ctx, notify.Mail{ To: []string{u.Email}, Subject: l.T("email.verify.subject", data), Body: l.T("email.verify.body", data), }) } type verifyRequest struct { Token string `json:"token" binding:"required,max=200"` } // verifyEmail confirms the address the token was mailed to and signs the // account in: whoever holds the link controls the mailbox. func (s *Server) verifyEmail(c *gin.Context) { var req verifyRequest if !bind(c, &req) { return } ctx := c.Request.Context() if !s.limit(c, "verify:ip:"+c.ClientIP(), 30, 15*time.Minute) { return } raw, err := s.rdb.GetDel(ctx, verifyKey(req.Token)).Result() id, perr := uuid.Parse(raw) if errors.Is(err, redis.Nil) || perr != nil { fail(c, http.StatusGone, "verification_expired") return } if err != nil { internalError(c, err) return } var u store.User err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { var err error u, err = q.MarkEmailVerified(ctx, id) return err }) if errors.Is(err, pgx.ErrNoRows) { fail(c, http.StatusGone, "verification_expired") return } if err != nil { internalError(c, err) return } auditActor(c, u.ID) if u.DisabledAt != nil { fail(c, http.StatusForbidden, "account_suspended") return } s.finishLogin(c, u.ID, auth.MethodPassword) } type resendRequest struct { Email string `json:"email" binding:"required,email,max=320"` } // resendVerification mails a new link to an unconfirmed account. It // answers the same whether or not such an account exists. func (s *Server) resendVerification(c *gin.Context) { var req resendRequest if !bind(c, &req) { return } ctx := c.Request.Context() email := normalizeEmail(req.Email) if !s.limit(c, "resend:ip:"+c.ClientIP(), 10, time.Hour) || !s.limit(c, "resend:email:"+email, 3, time.Hour) { return } var u store.User err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { var err error u, err = q.GetUserByEmail(ctx, email) return err }) switch { case errors.Is(err, pgx.ErrNoRows): case err != nil: internalError(c, err) return case u.EmailVerifiedAt == nil && u.DisabledAt == nil: if err := s.sendVerification(ctx, u); err != nil { s.log.ErrorContext(ctx, "sending verification failed", "error", err) } } c.Status(http.StatusNoContent) } type createOrgRequest struct { Name string `json:"name" binding:"required,max=200"` Slug string `json:"slug" binding:"required,max=63"` } // createOrg creates an organization owned by the signed-in account and // makes it the active one. func (s *Server) createOrg(c *gin.Context) { var req createOrgRequest if !bind(c, &req) { return } sess := auth.Current(c) ctx := c.Request.Context() u, err := s.loadUser(ctx, sess.UserID) if err != nil { internalError(c, err) return } max := s.platformLimits(ctx).OrgsPerAccount if u.LimitOrgs != nil { max = int(*u.LimitOrgs) } orgID := uuid.New() err = s.db.Tx(ctx, tenant.Org(orgID, sess.UserID), func(q *store.Queries) error { if max > 0 { // Serialize the account's creations to count them reliably. if err := q.LockOrgUsage(ctx, u.ID); err != nil { return err } n, err := q.CountOwnedOrgs(ctx, u.ID) if err != nil { return err } if n >= int64(max) { return limitError{"org_limit", max} } } if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(strings.TrimSpace(req.Slug)), Name: strings.TrimSpace(req.Name)}); err != nil { return err } return q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: u.ID, IsOwner: true}) }) switch { case failLimit(c, err): 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 } auditOrg(c, orgID) if err := s.sessions.SwitchOrg(ctx, sess, orgID); err != nil { internalError(c, err) return } c.JSON(http.StatusCreated, gin.H{"id": orgID, "slug": strings.ToLower(strings.TrimSpace(req.Slug)), "redirect": "/"}) } // signupClosedWithoutMail tells whether sign-up must wait for a mail // server: accounts need confirming but no link could be sent. func (s *Server) signupClosedWithoutMail() bool { return s.verificationRequired() && s.smtp == nil }