ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 9m21s
ci / test (pull_request) Successful in 13m53s
ci / build (pull_request) Successful in 11m22s
ci / image (pull_request) Successful in 4m36s
Terms of service join the legal notice and privacy policy, for the platform only. Every account accepts the platform's privacy policy and terms: on sign-up (also through an invitation) by ticking a box for the versions shown, and after a sign-in through a provider right away. When an admin saves a material change with "everyone has to accept again", the document gets a new version and each account is asked at its next request; corrections ask nobody. Acceptances are kept per version with their time, as proof, and are part of the data export. Until an account accepted, and while it is suspended, it can read the documents, export its data, delete itself and sign out, nothing else: pages lead to /consent or /account/suspended, other API calls answer 403 consent_required or account_suspended. Suspended accounts therefore sign in again, by password or provider; their API tokens stay blocked. Deleting an account deletes the organizations it owns, monitors and all, also when they have other members (each organization has one owner); it no longer refuses. The account settings name those organizations first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
361 lines
9.5 KiB
Go
361 lines
9.5 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/mail"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
|
"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"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
|
)
|
|
|
|
const invitationTTL = 7 * 24 * time.Hour
|
|
|
|
type inviteRequest struct {
|
|
Email string `json:"email" binding:"required,max=320"`
|
|
RoleID uuid.UUID `json:"role_id" binding:"required"`
|
|
}
|
|
|
|
func (s *Server) createInvitation(c *gin.Context) {
|
|
var req inviteRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
email := normalizeEmail(req.Email)
|
|
if addr, err := mail.ParseAddress(email); err != nil || addr.Address != email {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_email")
|
|
return
|
|
}
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
tok := auth.RandomToken()
|
|
var code string
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
role, err := q.GetRole(ctx, req.RoleID)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
code = "role_not_found"
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !p.Grants.CanGrant(authz.NewSet(role.Permissions...), nil) {
|
|
code = "permission_escalation"
|
|
return nil
|
|
}
|
|
members, err := q.ListOrgMembers(ctx, p.Org.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, m := range members {
|
|
if m.Email == email {
|
|
code = "already_member"
|
|
return nil
|
|
}
|
|
}
|
|
_, err = q.CreateInvitation(ctx, store.CreateInvitationParams{
|
|
OrgID: p.Org.ID, Email: email, RoleID: role.ID, TokenHash: HashToken(tok),
|
|
InvitedBy: &p.UserID, ExpiresAt: time.Now().Add(invitationTTL),
|
|
})
|
|
return err
|
|
})
|
|
switch {
|
|
case err != nil:
|
|
internalError(c, err)
|
|
case code == "role_not_found":
|
|
fail(c, http.StatusNotFound, code)
|
|
case code == "permission_escalation":
|
|
fail(c, http.StatusForbidden, code)
|
|
case code != "":
|
|
fail(c, http.StatusConflict, code)
|
|
default:
|
|
// There is no mailer yet; the inviter passes the link on.
|
|
c.JSON(http.StatusCreated, gin.H{"url": s.cfg.PublicURL + "/invite/" + tok})
|
|
}
|
|
}
|
|
|
|
// invitationView is a pending invitation.
|
|
type invitationView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Email string `json:"email"`
|
|
RoleName string `json:"role_name"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
}
|
|
|
|
func (s *Server) listInvitations(c *gin.Context) {
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var rows []store.ListPendingInvitationsRow
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
rows, err = q.ListPendingInvitations(ctx)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
out := make([]invitationView, len(rows))
|
|
for i, r := range rows {
|
|
out[i] = invitationView{ID: r.ID, Email: r.Email, RoleName: r.RoleName, ExpiresAt: r.ExpiresAt}
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"invitations": out})
|
|
}
|
|
|
|
func (s *Server) deleteInvitation(c *gin.Context) {
|
|
id, err := uuid.Parse(c.Param("id"))
|
|
if err != nil {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var n int64
|
|
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
n, err = q.DeleteInvitation(ctx, id)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if n == 0 {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
// findInvitation returns the invitation for tok, or ok=false if it does not
|
|
// exist, was used or has expired.
|
|
func (s *Server) findInvitation(ctx context.Context, tok string) (inv store.GetInvitationByHashRow, ok bool, err error) {
|
|
hash := HashToken(tok)
|
|
var org uuid.UUID
|
|
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
org, err = q.InvitationOrg(ctx, hash)
|
|
return err
|
|
})
|
|
if err != nil || org == uuid.Nil {
|
|
return inv, false, err
|
|
}
|
|
err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
|
|
inv, err = q.GetInvitationByHash(ctx, hash)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
return inv, false, err
|
|
}
|
|
return inv, inv.AcceptedAt == nil && inv.ExpiresAt.After(time.Now()), nil
|
|
}
|
|
|
|
// join makes userID a member with the invited role. The inviter must still
|
|
// be allowed to grant that role; rights lost since inviting are not passed
|
|
// on through a pending invitation.
|
|
func (s *Server) join(ctx context.Context, inv store.GetInvitationByHashRow, userID uuid.UUID) (string, error) {
|
|
var code string
|
|
err := s.db.Tx(ctx, tenant.Org(inv.OrgID, userID), func(q *store.Queries) error {
|
|
if inv.InvitedBy == nil {
|
|
code = "invitation_invalid"
|
|
return nil
|
|
}
|
|
g, member, err := loadGrants(ctx, q, inv.OrgID, *inv.InvitedBy)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
role, err := q.GetRole(ctx, inv.RoleID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !member || !g.CanGrant(authz.NewSet(role.Permissions...), nil) {
|
|
code = "invitation_invalid"
|
|
return nil
|
|
}
|
|
n, err := q.MarkInvitationAccepted(ctx, inv.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n == 0 {
|
|
code = "invitation_invalid"
|
|
return nil
|
|
}
|
|
if already, err := q.IsMember(ctx, store.IsMemberParams{OrgID: inv.OrgID, UserID: userID}); err != nil {
|
|
return err
|
|
} else if !already {
|
|
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: inv.OrgID, UserID: userID}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
_, err = q.CreateAssignment(ctx, store.CreateAssignmentParams{OrgID: inv.OrgID, UserID: userID, RoleID: inv.RoleID})
|
|
if isUniqueViolation(err, "role_assignments_org_id_user_id_role_id_resource_type_resou_key") {
|
|
return nil
|
|
}
|
|
return err
|
|
})
|
|
return code, err
|
|
}
|
|
|
|
func (s *Server) acceptInvitation(c *gin.Context) {
|
|
ctx := c.Request.Context()
|
|
sess := auth.Current(c)
|
|
inv, ok, err := s.findInvitation(ctx, c.Param("token"))
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if !ok {
|
|
fail(c, http.StatusGone, "invitation_invalid")
|
|
return
|
|
}
|
|
me, err := s.loadMe(ctx, sess)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if me.Email != inv.Email {
|
|
fail(c, http.StatusForbidden, "invitation_email_mismatch")
|
|
return
|
|
}
|
|
code, err := s.join(ctx, inv, sess.UserID)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if code != "" {
|
|
fail(c, http.StatusGone, code)
|
|
return
|
|
}
|
|
auditOrg(c, inv.OrgID)
|
|
if err := s.sessions.SwitchOrg(ctx, sess, inv.OrgID); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
type inviteSignupRequest struct {
|
|
DisplayName string `json:"display_name" binding:"max=200"`
|
|
Password string `json:"password" binding:"required,max=1024"`
|
|
Consent bool `json:"consent"`
|
|
ConsentVersions string `json:"consent_versions" binding:"max=200"`
|
|
}
|
|
|
|
// inviteSignup creates an account for an invited address. It bypasses
|
|
// UPTIME_SIGNUP because the organization vouched for the invitee.
|
|
func (s *Server) inviteSignup(c *gin.Context) {
|
|
var req inviteSignupRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
if !s.limit(c, "signup:"+c.ClientIP(), 10, time.Hour) {
|
|
return
|
|
}
|
|
inv, ok, err := s.findInvitation(ctx, c.Param("token"))
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if !ok {
|
|
fail(c, http.StatusGone, "invitation_invalid")
|
|
return
|
|
}
|
|
consent, ok := s.signupConsent(c, req.Consent, req.ConsentVersions)
|
|
if !ok {
|
|
return
|
|
}
|
|
hash, err := auth.HashPassword(req.Password)
|
|
if errors.Is(err, auth.ErrPasswordTooShort) {
|
|
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
var user store.User
|
|
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
// The organization invited this address, which stands in for
|
|
// confirming it.
|
|
user, err = q.CreateUser(ctx, store.CreateUserParams{
|
|
Email: inv.Email, DisplayName: strings.TrimSpace(req.DisplayName),
|
|
PasswordHash: &hash, Locale: ptr(i18n.Lang(ctx)),
|
|
EmailKey: ptr(emailKey(inv.Email)), EmailVerifiedAt: ptr(time.Now()),
|
|
})
|
|
return err
|
|
})
|
|
if err == nil {
|
|
err = s.db.Tx(ctx, tenant.User(user.ID), func(q *store.Queries) error {
|
|
return recordConsent(ctx, q, user.ID, consent)
|
|
})
|
|
}
|
|
if isUniqueViolation(err, "users_email_key") || isUniqueViolation(err, "users_email_key_idx") {
|
|
fail(c, http.StatusConflict, "email_taken")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
code, err := s.join(ctx, inv, user.ID)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if code != "" {
|
|
fail(c, http.StatusGone, code)
|
|
return
|
|
}
|
|
s.startSession(c, auth.NewSession{UserID: user.ID, OrgID: inv.OrgID, Locale: i18n.Lang(ctx), Method: auth.MethodPassword})
|
|
}
|
|
|
|
func (s *Server) invitePage(c *gin.Context) {
|
|
ctx := c.Request.Context()
|
|
tok := c.Param("token")
|
|
inv, ok, err := s.findInvitation(ctx, tok)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
view := web.Invitation{Token: tok, Valid: ok}
|
|
if ok {
|
|
view.OrgName, view.RoleName, view.Email = inv.OrgName, inv.RoleName, inv.Email
|
|
if sess := auth.Current(c); sess != nil {
|
|
me, err := s.loadMe(ctx, sess)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
view.SignedInAs = me.Email
|
|
} else {
|
|
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
_, err := q.GetUserByEmail(ctx, inv.Email)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil
|
|
}
|
|
view.AccountExists = err == nil
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
if view.Consent, err = s.signupConsentView(ctx); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
web.Render(c, http.StatusOK, web.InvitationPage(s.pageFor(c, "invite.title"), view))
|
|
}
|