Files
Sebastian UnterschützandClaude Opus 5.5 db3ff19983
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 9m19s
ci / test (pull_request) Successful in 9m25s
ci / build (pull_request) Successful in 15m40s
ci / image (pull_request) Successful in 4m26s
feat: several owners per organization, and handing ownership over
An organization may now have several owners; the unique index allowing
only one is gone. Owners make members owners or take it back, their own
included, through PUT /api/v1/org/members/:user/owner; handing an
organization over is making someone else owner and stepping down. The
last owner cannot step down, and changes serialize on a per-organization
lock so two owners stepping down at once cannot leave none. A former
owner without roles keeps working as Admin. Owners still cannot be
removed while they are owners.

Deleting an account now takes along only the organizations it is the
last owner of, counted under the same lock; it just leaves those with
further owners. The members page offers "Make owner", "Remove as owner"
and "Step down as owner" to owners.

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

360 lines
9.9 KiB
Go

package api
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"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"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Every account accepts the platform's privacy policy and terms in their
// current version: on sign-up, and otherwise right after signing in, again
// whenever a document asks for it. Until then, and while an account is
// suspended, it can only read the documents, export its data, delete
// itself and sign out.
// requiredConsent returns the current version of each document accounts
// accept; empty when the platform has none.
func (s *Server) requiredConsent(ctx context.Context) (map[string]int64, error) {
return s.consent.get(ctx, s.rdb, func(ctx context.Context) (map[string]int64, error) {
out := map[string]int64{}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
rows, err := q.RequiredLegalVersions(ctx)
for _, r := range rows {
out[r.Kind] = r.Version
}
return err
})
return out, err
})
}
// consentVersions encodes versions for a form, e.g. "privacy:12,terms:14".
func consentVersions(v map[string]int64) string {
var parts []string
for _, kind := range web.ConsentKinds {
if n, ok := v[kind]; ok {
parts = append(parts, kind+":"+strconv.FormatInt(n, 10))
}
}
return strings.Join(parts, ",")
}
func parseConsentVersions(s string) map[string]int64 {
out := map[string]int64{}
for part := range strings.SplitSeq(s, ",") {
kind, n, ok := strings.Cut(strings.TrimSpace(part), ":")
if v, err := strconv.ParseInt(n, 10, 64); ok && err == nil {
out[kind] = v
}
}
return out
}
// errConsentOutdated reports an acceptance of versions that are no longer
// current: a document changed while the form was open.
var errConsentOutdated = errors.New("api: consent for outdated documents")
// checkConsent verifies that accepted covers exactly the documents
// required right now.
func checkConsent(required, accepted map[string]int64) error {
for kind, v := range required {
if accepted[kind] != v {
return errConsentOutdated
}
}
return nil
}
func recordConsent(ctx context.Context, q *store.Queries, user uuid.UUID, versions map[string]int64) error {
for kind, v := range versions {
if err := q.AcceptLegal(ctx, store.AcceptLegalParams{UserID: user, Kind: kind, Version: v}); err != nil {
return err
}
}
return nil
}
// access is what an account may do in the console.
type access struct {
suspended bool
reason string
// missing are the documents still to accept, with their versions.
missing map[string]int64
}
func (a access) restricted() bool { return a.suspended || len(a.missing) > 0 }
func (s *Server) accessOf(ctx context.Context, user uuid.UUID) (access, error) {
required, err := s.requiredConsent(ctx)
if err != nil {
return access{}, err
}
var a access
err = s.db.Tx(ctx, tenant.User(user), func(q *store.Queries) error {
u, err := q.GetUser(ctx, user)
if err != nil {
return err
}
if u.DisabledAt != nil {
a.suspended, a.reason = true, u.DisabledReason
}
if len(required) == 0 {
return nil
}
accepted, err := q.AcceptedLegalVersions(ctx, user)
if err != nil {
return err
}
for kind, v := range required {
if !slices.ContainsFunc(accepted, func(r store.AcceptedLegalVersionsRow) bool { return r.Kind == kind && r.Version == v }) {
if a.missing == nil {
a.missing = map[string]int64{}
}
a.missing[kind] = v
}
}
return nil
})
return a, err
}
// restrictedPaths stay open to accounts that are suspended or have yet to
// accept the documents. Admins keep editing the documents, which they may
// be publishing one after the other; the handlers still check they are.
var restrictedPaths = []string{
"/consent", "/account/suspended", "/legal/",
"/api/v1/auth/", "/api/v1/consent", "/api/v1/me/export", "/api/v1/me/delete", "/api/v1/locale",
"/admin/legal", "/api/v1/admin/legal/",
}
func allowedRestricted(path string) bool {
return slices.ContainsFunc(restrictedPaths, func(p string) bool {
return path == p || (strings.HasSuffix(p, "/") && strings.HasPrefix(path, p))
})
}
// accountGate keeps restricted accounts on the consent or suspension page.
func (s *Server) accountGate() gin.HandlerFunc {
return func(c *gin.Context) {
sess := auth.Current(c)
path := c.Request.URL.Path
if sess == nil || allowedRestricted(path) {
c.Next()
return
}
a, err := s.accessOf(c.Request.Context(), sess.UserID)
switch {
case err != nil:
internalError(c, err)
c.Abort()
return
case !a.restricted():
c.Next()
return
}
if strings.HasPrefix(path, "/api/") {
code := "consent_required"
if a.suspended {
code = "account_suspended"
}
fail(c, http.StatusForbidden, code)
c.Abort()
return
}
target := "/account/suspended"
if !a.suspended {
target = "/consent?next=" + url.QueryEscape(c.Request.URL.RequestURI())
}
c.Redirect(http.StatusSeeOther, target)
c.Abort()
}
}
// localNext keeps a redirect target on this site.
func localNext(next string) string {
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") {
return "/"
}
return next
}
type consentRequest struct {
// Versions are the documents accepted, as shown: "privacy:12,terms:14".
Versions string `json:"versions" binding:"max=200"`
Next string `json:"next" binding:"max=2000"`
}
// acceptConsent records that the signed-in account accepts the current
// documents.
func (s *Server) acceptConsent(c *gin.Context) {
var req consentRequest
if !bind(c, &req) {
return
}
sess := auth.Current(c)
if sess == nil {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
ctx := c.Request.Context()
required, err := s.requiredConsent(ctx)
if err != nil {
internalError(c, err)
return
}
accepted := parseConsentVersions(req.Versions)
if err := checkConsent(required, accepted); err != nil {
fail(c, http.StatusConflict, "consent_outdated")
return
}
auditDetail(c, "versions", consentVersions(required))
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return recordConsent(ctx, q, sess.UserID, required)
}); err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"redirect": localNext(req.Next)})
}
// consentDocs lists the documents of versions with their links.
func (s *Server) consentDocs(ctx context.Context, versions map[string]int64) []web.LegalLink {
var docs []web.LegalLink
for _, l := range web.LegalLinks(s.platformLegalDocs(ctx), "/legal/") {
if _, ok := versions[l.Kind]; ok {
docs = append(docs, l)
}
}
return docs
}
// restrictedMe is the account data the consent and suspension pages show,
// with the organizations its deletion would take along.
func (s *Server) restrictedMe(c *gin.Context, sess *auth.Session) (web.Me, error) {
m, err := s.loadMe(c.Request.Context(), sess)
if err != nil {
return web.Me{}, err
}
me := toWebMe(m)
me.DeletesOrgs, err = s.lastOwnedOrgs(c.Request.Context(), sess.UserID)
return me, err
}
func (s *Server) consentPage(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
next := localNext(c.Query("next"))
a, err := s.accessOf(c.Request.Context(), sess.UserID)
if err != nil {
internalError(c, err)
return
}
if a.suspended {
c.Redirect(http.StatusSeeOther, "/account/suspended")
return
}
if len(a.missing) == 0 {
c.Redirect(http.StatusSeeOther, next)
return
}
me, err := s.restrictedMe(c, sess)
if err != nil {
internalError(c, err)
return
}
required, err := s.requiredConsent(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.ConsentPage(s.pageFor(c, "consent.title"), me,
s.consentDocs(c.Request.Context(), a.missing), consentVersions(required), next))
}
func (s *Server) suspendedPage(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
a, err := s.accessOf(c.Request.Context(), sess.UserID)
if err != nil {
internalError(c, err)
return
}
if !a.suspended {
c.Redirect(http.StatusSeeOther, "/")
return
}
me, err := s.restrictedMe(c, sess)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.SuspendedPage(s.pageFor(c, "suspended.title"), me, a.reason))
}
// signupConsent checks the consent given on a sign-up form and returns the
// versions to record.
func (s *Server) signupConsent(c *gin.Context, given bool, versions string) (map[string]int64, bool) {
required, err := s.requiredConsent(c.Request.Context())
if err != nil {
internalError(c, err)
return nil, false
}
if len(required) == 0 {
return nil, true
}
if !given {
fail(c, http.StatusUnprocessableEntity, "consent_required")
return nil, false
}
if err := checkConsent(required, parseConsentVersions(versions)); err != nil {
fail(c, http.StatusConflict, "consent_outdated")
return nil, false
}
return required, true
}
// signupConsentView is what sign-up forms show: the documents to accept
// and their versions.
func (s *Server) signupConsentView(ctx context.Context) (web.SignupConsent, error) {
required, err := s.requiredConsent(ctx)
if err != nil || len(required) == 0 {
return web.SignupConsent{}, err
}
return web.SignupConsent{Docs: s.consentDocs(ctx, required), Versions: consentVersions(required)}, nil
}
// lastOwnedOrgs names the organizations user is the last owner of, which
// deleting the account deletes too.
func (s *Server) lastOwnedOrgs(ctx context.Context, user uuid.UUID) ([]string, error) {
var out []string
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, user)
for _, o := range owned {
if o.Owners == 1 {
out = append(out, fmt.Sprintf("%s (%s)", o.Name, o.Slug))
}
}
return err
})
return out, err
}