diff --git a/internal/api/access.go b/internal/api/access.go new file mode 100644 index 0000000..076c4e7 --- /dev/null +++ b/internal/api/access.go @@ -0,0 +1,153 @@ +package api + +import ( + "context" + "errors" + "net/http" + + "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/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +const ctxPrincipal = "api.principal" + +// principal is whoever acts on an organization in this request: a browser +// session or an API token, together with what it may do there. +type principal struct { + UserID uuid.UUID + Org store.Org + Grants *authz.Grants + // Session is nil for API token requests. + Session *auth.Session + // TokenID is set for API token requests. + TokenID uuid.UUID +} + +func (p *principal) scope() tenant.Scope { return tenant.Org(p.Org.ID, p.UserID) } + +func current(c *gin.Context) *principal { return c.MustGet(ctxPrincipal).(*principal) } + +// loadGrants returns the member's permissions, or ok=false if userID is not +// a member of org. +func loadGrants(ctx context.Context, q *store.Queries, org, userID uuid.UUID) (g *authz.Grants, ok bool, err error) { + m, err := q.GetMembership(ctx, store.GetMembershipParams{OrgID: org, UserID: userID}) + if errors.Is(err, pgx.ErrNoRows) { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + rows, err := q.MemberGrants(ctx, store.MemberGrantsParams{OrgID: org, UserID: userID}) + if err != nil { + return nil, false, err + } + g = &authz.Grants{Owner: m.IsOwner, Org: authz.Set{}, Scoped: map[authz.Resource]authz.Set{}} + for _, r := range rows { + perms := authz.NewSet(r.Permissions...) + if r.ResourceType == nil || r.ResourceID == nil { + g.Org = g.Org.Union(perms) + continue + } + res := authz.Resource{Type: authz.ResourceType(*r.ResourceType), ID: *r.ResourceID} + g.Scoped[res] = g.Scoped[res].Union(perms) + } + return g, true, nil +} + +// policyViolation returns the error code if sess may not act on org because +// of the org's sign-in policy, or "" if it may. +// +// SSO sessions satisfy the TOTP requirement: multi-factor authentication is +// then the identity provider's job. The owner may always sign in with a +// password so a broken IdP cannot lock the organization out. +func policyViolation(org store.Org, isOwner bool, sess *auth.Session) string { + viaOrgSSO := sess.Method == auth.MethodSSO && sess.SSOOrg == org.ID + if org.RequireSso && !viaOrgSSO && !isOwner { + return "sso_required_by_org" + } + if org.RequireTotp && !viaOrgSSO && sess.Method != auth.MethodPasswordTOTP { + return "totp_required_by_org" + } + return "" +} + +// orgAccess authenticates the request against the session's active +// organization, enforces its sign-in policy and attaches a principal. +func (s *Server) orgAccess() gin.HandlerFunc { + return func(c *gin.Context) { + p, status, code, err := s.resolvePrincipal(c) + if err != nil { + internalError(c, err) + return + } + if code != "" { + fail(c, status, code) + return + } + c.Set(ctxPrincipal, p) + c.Next() + } +} + +func (s *Server) resolvePrincipal(c *gin.Context) (*principal, int, string, error) { + if tok := bearerToken(c); tok != "" { + return s.tokenPrincipal(c.Request.Context(), tok) + } + sess := auth.Current(c) + if sess == nil { + return nil, http.StatusUnauthorized, "unauthenticated", nil + } + if sess.OrgID == uuid.Nil { + return nil, http.StatusForbidden, "forbidden", nil + } + ctx := c.Request.Context() + p := &principal{UserID: sess.UserID, Session: sess} + var member bool + err := s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error { + var err error + if p.Org, err = q.GetOrg(ctx, sess.OrgID); err != nil { + return err + } + p.Grants, member, err = loadGrants(ctx, q, sess.OrgID, sess.UserID) + return err + }) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && !member) { + return nil, http.StatusForbidden, "forbidden", nil + } + if err != nil { + return nil, 0, "", err + } + if code := policyViolation(p.Org, p.Grants.Owner, sess); code != "" { + return nil, http.StatusForbidden, code, nil + } + return p, 0, "", nil +} + +// can aborts unless the principal holds perm organization-wide. +func can(perm authz.Permission) gin.HandlerFunc { + return func(c *gin.Context) { + if !current(c).Grants.Can(perm) { + fail(c, http.StatusForbidden, "forbidden") + return + } + c.Next() + } +} + +// sessionOnly rejects API tokens on routes that manage credentials, so a +// leaked token cannot mint further tokens or change who has access. +func sessionOnly() gin.HandlerFunc { + return func(c *gin.Context) { + if current(c).Session == nil { + fail(c, http.StatusForbidden, "session_required") + return + } + c.Next() + } +} diff --git a/internal/api/auth.go b/internal/api/auth.go index 8f9e229..6f84eba 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -91,7 +91,7 @@ func (s *Server) signup(c *gin.Context) { internalError(c, err) return } - s.startSession(c, user.ID, orgID, i18n.Lang(ctx)) + s.startSession(c, auth.NewSession{UserID: user.ID, OrgID: orgID, Locale: i18n.Lang(ctx), Method: auth.MethodPassword}) } func (s *Server) signupAllowed(ctx context.Context) (bool, error) { @@ -164,7 +164,7 @@ func (s *Server) login(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "totp_required"}) return } - s.finishLogin(c, user.ID) + s.finishLogin(c, user.ID, auth.MethodPassword) } // secondFactorRequest carries a TOTP code or a recovery code. @@ -211,10 +211,10 @@ func (s *Server) loginTOTP(c *gin.Context) { } _ = s.rdb.Del(ctx, mfaKey(token)).Err() setCookie(c, mfaCookie, "", -1) - s.finishLogin(c, userID) + s.finishLogin(c, userID, auth.MethodPasswordTOTP) } -func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) { +func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID, method auth.Method) { ctx := c.Request.Context() var ( user store.User @@ -236,14 +236,14 @@ func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) { if len(orgs) > 0 { org = orgs[0].ID } - s.startSession(c, userID, org, deref(user.Locale)) + s.startSession(c, auth.NewSession{UserID: userID, OrgID: org, Locale: deref(user.Locale), Method: method}) } -func (s *Server) startSession(c *gin.Context, userID, orgID uuid.UUID, locale string) { +func (s *Server) startSession(c *gin.Context, n auth.NewSession) { 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) + sess, err := s.sessions.Create(c.Request.Context(), n) if err != nil { internalError(c, err) return diff --git a/internal/api/invitations.go b/internal/api/invitations.go new file mode 100644 index 0000000..1ff42c9 --- /dev/null +++ b/internal/api/invitations.go @@ -0,0 +1,339 @@ +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}) + } +} + +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 + } + type view struct { + ID uuid.UUID `json:"id"` + Email string `json:"email"` + RoleName string `json:"role_name"` + ExpiresAt time.Time `json:"expires_at"` + } + out := make([]view, len(rows)) + for i, r := range rows { + out[i] = view{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 + } + 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"` +} + +// 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 + } + 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 { + user, err = q.CreateUser(ctx, store.CreateUserParams{ + Email: inv.Email, DisplayName: strings.TrimSpace(req.DisplayName), + PasswordHash: &hash, Locale: ptr(i18n.Lang(ctx)), + }) + return err + }) + if isUniqueViolation(err, "users_email_key") { + 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 + } + } + } + web.Render(c, http.StatusOK, web.InvitationPage(s.pageFor(c, "invite.title"), view)) +} diff --git a/internal/api/me.go b/internal/api/me.go index 4d26dbd..8b0709a 100644 --- a/internal/api/me.go +++ b/internal/api/me.go @@ -171,6 +171,12 @@ func (s *Server) totpEnable(c *gin.Context) { return } _ = s.rdb.Del(ctx, totpSetupKey(sess.UserID)).Err() + if sess.Method == auth.MethodPassword || sess.Method == "" { + if err := s.sessions.SetMethod(ctx, sess, auth.MethodPasswordTOTP); err != nil { + internalError(c, err) + return + } + } c.JSON(http.StatusOK, gin.H{"recovery_codes": codes}) } diff --git a/internal/api/members.go b/internal/api/members.go new file mode 100644 index 0000000..acb6985 --- /dev/null +++ b/internal/api/members.go @@ -0,0 +1,488 @@ +package api + +import ( + "errors" + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" +) + +type assignmentView struct { + ID uuid.UUID `json:"id"` + RoleID uuid.UUID `json:"role_id"` + RoleName string `json:"role_name"` + RoleKey *string `json:"role_key,omitempty"` + ResourceType *string `json:"resource_type,omitempty"` + ResourceID *uuid.UUID `json:"resource_id,omitempty"` +} + +type memberView struct { + UserID uuid.UUID `json:"user_id"` + Email string `json:"email"` + DisplayName string `json:"display_name"` + IsOwner bool `json:"is_owner"` + JoinedAt time.Time `json:"joined_at"` + Assignments []assignmentView `json:"assignments"` +} + +func (s *Server) loadMembers(c *gin.Context) ([]memberView, error) { + p := current(c) + ctx := c.Request.Context() + var out []memberView + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + members, err := q.ListOrgMembers(ctx, p.Org.ID) + if err != nil { + return err + } + assigns, err := q.ListAssignments(ctx, p.Org.ID) + if err != nil { + return err + } + byUser := map[uuid.UUID][]assignmentView{} + for _, a := range assigns { + byUser[a.UserID] = append(byUser[a.UserID], assignmentView{ + ID: a.ID, RoleID: a.RoleID, RoleName: a.RoleName, RoleKey: a.RoleKey, + ResourceType: a.ResourceType, ResourceID: a.ResourceID, + }) + } + out = make([]memberView, len(members)) + for i, m := range members { + out[i] = memberView{ + UserID: m.ID, Email: m.Email, DisplayName: m.DisplayName, IsOwner: m.IsOwner, + JoinedAt: m.JoinedAt, Assignments: byUser[m.ID], + } + if out[i].Assignments == nil { + out[i].Assignments = []assignmentView{} + } + } + return nil + }) + return out, err +} + +func (s *Server) listMembers(c *gin.Context) { + members, err := s.loadMembers(c) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"members": members}) +} + +// removeMember requires the actor to hold every permission the member holds +// organization-wide, so a delegated admin cannot remove a stronger one. +func (s *Server) removeMember(c *gin.Context) { + target, err := uuid.Parse(c.Param("user")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + p := current(c) + ctx := c.Request.Context() + var code string + err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + g, member, err := loadGrants(ctx, q, p.Org.ID, target) + switch { + case err != nil: + return err + case !member: + code = "not_found" + case g.Owner: + code = "owner_cannot_be_removed" + case !p.Grants.CanGrant(g.Org, nil): + code = "permission_escalation" + default: + _, err = q.RemoveMembership(ctx, store.RemoveMembershipParams{OrgID: p.Org.ID, UserID: target}) + } + return err + }) + if err != nil { + internalError(c, err) + return + } + switch code { + case "": + _ = s.sessions.DeleteAllForUser(ctx, target) + c.Status(http.StatusNoContent) + case "not_found": + fail(c, http.StatusNotFound, code) + default: + fail(c, http.StatusForbidden, code) + } +} + +type assignRequest struct { + RoleID uuid.UUID `json:"role_id" binding:"required"` + ResourceType string `json:"resource_type" binding:"omitempty,oneof=monitor_group status_page"` + ResourceID *uuid.UUID `json:"resource_id"` +} + +func (r assignRequest) scope() (*authz.Resource, bool) { + if r.ResourceType == "" && r.ResourceID == nil { + return nil, true + } + if r.ResourceID == nil { + return nil, false + } + res := authz.Resource{Type: authz.ResourceType(r.ResourceType), ID: *r.ResourceID} + return &res, res.Valid() +} + +func (s *Server) assignRole(c *gin.Context) { + target, err := uuid.Parse(c.Param("user")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + var req assignRequest + if !bind(c, &req) { + return + } + scope, ok := req.scope() + if !ok { + fail(c, http.StatusUnprocessableEntity, "invalid_input") + return + } + p := current(c) + ctx := c.Request.Context() + var ( + code string + row store.RoleAssignment + ) + 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 + } + m, err := q.GetMembership(ctx, store.GetMembershipParams{OrgID: p.Org.ID, UserID: target}) + switch { + case errors.Is(err, pgx.ErrNoRows): + code = "not_found" + return nil + case err != nil: + return err + case m.IsOwner: + code = "owner_has_all_permissions" + return nil + case !p.Grants.CanGrant(authz.NewSet(role.Permissions...), scope): + code = "permission_escalation" + return nil + } + params := store.CreateAssignmentParams{OrgID: p.Org.ID, UserID: target, RoleID: role.ID} + if scope != nil { + rt := string(scope.Type) + params.ResourceType, params.ResourceID = &rt, &scope.ID + } + row, err = q.CreateAssignment(ctx, params) + if isUniqueViolation(err, "role_assignments_org_id_user_id_role_id_resource_type_resou_key") { + code = "already_assigned" + return nil + } + return err + }) + if err != nil { + internalError(c, err) + return + } + switch code { + case "": + c.JSON(http.StatusCreated, gin.H{"id": row.ID}) + case "not_found", "role_not_found": + fail(c, http.StatusNotFound, code) + case "already_assigned", "owner_has_all_permissions": + fail(c, http.StatusConflict, code) + default: + fail(c, http.StatusForbidden, code) + } +} + +func (s *Server) unassignRole(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 code string + err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + a, err := q.GetAssignment(ctx, id) + if errors.Is(err, pgx.ErrNoRows) { + code = "not_found" + return nil + } + if err != nil { + return err + } + role, err := q.GetRole(ctx, a.RoleID) + if err != nil { + return err + } + var scope *authz.Resource + if a.ResourceType != nil && a.ResourceID != nil { + scope = &authz.Resource{Type: authz.ResourceType(*a.ResourceType), ID: *a.ResourceID} + } + if !p.Grants.CanGrant(authz.NewSet(role.Permissions...), scope) { + code = "permission_escalation" + return nil + } + _, err = q.DeleteAssignment(ctx, id) + return err + }) + if err != nil { + internalError(c, err) + return + } + switch code { + case "": + c.Status(http.StatusNoContent) + case "not_found": + fail(c, http.StatusNotFound, code) + default: + fail(c, http.StatusForbidden, code) + } +} + +type roleView struct { + ID uuid.UUID `json:"id"` + Key *string `json:"key,omitempty"` + Name string `json:"name"` + BuiltIn bool `json:"built_in"` + Permissions []string `json:"permissions"` +} + +func viewRole(r store.Role) roleView { + return roleView{ID: r.ID, Key: r.Key, Name: r.Name, BuiltIn: r.OrgID == nil, Permissions: authz.NewSet(r.Permissions...).Strings()} +} + +func (s *Server) listRoles(c *gin.Context) { + p := current(c) + ctx := c.Request.Context() + var rows []store.Role + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + rows, err = q.ListRoles(ctx) + return err + }) + if err != nil { + internalError(c, err) + return + } + out := make([]roleView, len(rows)) + for i, r := range rows { + out[i] = viewRole(r) + } + c.JSON(http.StatusOK, gin.H{"roles": out, "permissions": authz.NewSet(authz.All...).Strings()}) +} + +type roleRequest struct { + Name string `json:"name" binding:"required,max=100"` + Permissions []string `json:"permissions" binding:"required,min=1,max=50,dive,max=50"` +} + +func (s *Server) createRole(c *gin.Context) { + var req roleRequest + if !bind(c, &req) { + return + } + perms := authz.NewSet(req.Permissions...) + p := current(c) + if len(perms) == 0 || strings.TrimSpace(req.Name) == "" { + fail(c, http.StatusUnprocessableEntity, "invalid_permissions") + return + } + if !p.Grants.CanGrant(perms, nil) { + fail(c, http.StatusForbidden, "permission_escalation") + return + } + ctx := c.Request.Context() + var row store.Role + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + row, err = q.CreateRole(ctx, store.CreateRoleParams{OrgID: &p.Org.ID, Name: strings.TrimSpace(req.Name), Permissions: perms.Strings()}) + return err + }) + if isUniqueViolation(err, "roles_org_id_name_key") { + fail(c, http.StatusConflict, "role_name_taken") + return + } + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusCreated, viewRole(row)) +} + +// updateRole requires the actor to hold both the old and the new +// permissions: otherwise they could strip rights they cannot grant back, or +// widen a role they are assigned to. +func (s *Server) updateRole(c *gin.Context) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + var req roleRequest + if !bind(c, &req) { + return + } + perms := authz.NewSet(req.Permissions...) + if len(perms) == 0 || strings.TrimSpace(req.Name) == "" { + fail(c, http.StatusUnprocessableEntity, "invalid_permissions") + return + } + p := current(c) + ctx := c.Request.Context() + var ( + code string + row store.Role + ) + err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + old, err := q.GetRole(ctx, id) + switch { + case errors.Is(err, pgx.ErrNoRows): + code = "not_found" + return nil + case err != nil: + return err + case old.OrgID == nil: + code = "role_built_in" + return nil + case !p.Grants.CanGrant(perms.Union(authz.NewSet(old.Permissions...)), nil): + code = "permission_escalation" + return nil + } + row, err = q.UpdateRole(ctx, store.UpdateRoleParams{ID: id, Name: strings.TrimSpace(req.Name), Permissions: perms.Strings()}) + if isUniqueViolation(err, "roles_org_id_name_key") { + code = "role_name_taken" + return nil + } + return err + }) + s.roleResult(c, err, code, func() { c.JSON(http.StatusOK, viewRole(row)) }) +} + +func (s *Server) deleteRole(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 code string + err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + old, err := q.GetRole(ctx, id) + switch { + case errors.Is(err, pgx.ErrNoRows): + code = "not_found" + return nil + case err != nil: + return err + case old.OrgID == nil: + code = "role_built_in" + return nil + case !p.Grants.CanGrant(authz.NewSet(old.Permissions...), nil): + code = "permission_escalation" + return nil + } + n, err := q.CountRoleAssignments(ctx, id) + if err != nil { + return err + } + if n > 0 { + code = "role_in_use" + return nil + } + _, err = q.DeleteRole(ctx, id) + return err + }) + s.roleResult(c, err, code, func() { c.Status(http.StatusNoContent) }) +} + +func (s *Server) roleResult(c *gin.Context, err error, code string, ok func()) { + switch { + case err != nil: + internalError(c, err) + case code == "": + ok() + case code == "not_found": + fail(c, http.StatusNotFound, code) + case code == "permission_escalation": + fail(c, http.StatusForbidden, code) + default: + fail(c, http.StatusConflict, code) + } +} + +type policyRequest struct { + RequireTOTP bool `json:"require_totp"` + RequireSSO bool `json:"require_sso"` + // APITokenMaxDays limits how long API tokens stay valid; 0 or null + // means no limit. + APITokenMaxDays *int `json:"api_token_max_days" binding:"omitempty,min=0,max=3650"` +} + +func (s *Server) updatePolicy(c *gin.Context) { + var req policyRequest + if !bind(c, &req) { + return + } + p := current(c) + // The actor must already meet a policy before switching it on, or the + // change would lock them out on their next request. + probe := p.Org + probe.RequireTotp, probe.RequireSso = req.RequireTOTP, req.RequireSSO + if code := policyViolation(probe, p.Grants.Owner, p.Session); code != "" { + fail(c, http.StatusConflict, "policy_would_lock_you_out") + return + } + ctx := c.Request.Context() + var org store.Org + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + if req.RequireSSO { + providers, err := q.ListEnabledSSOProviders(ctx) + if err != nil { + return err + } + if len(providers) == 0 { + return errNoSSOProvider + } + } + var maxDays *int32 + if req.APITokenMaxDays != nil && *req.APITokenMaxDays > 0 { + maxDays = ptr(int32(*req.APITokenMaxDays)) + } + var err error + org, err = q.UpdateOrgPolicy(ctx, store.UpdateOrgPolicyParams{ + ID: p.Org.ID, RequireTotp: req.RequireTOTP, RequireSso: req.RequireSSO, ApiTokenMaxDays: maxDays, + }) + if err != nil || maxDays == nil { + return err + } + _, err = q.ClampAPITokenExpiry(ctx, store.ClampAPITokenExpiryParams{OrgID: p.Org.ID, MaxDays: *maxDays}) + return err + }) + if errors.Is(err, errNoSSOProvider) { + fail(c, http.StatusConflict, "sso_no_provider") + return + } + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"require_totp": org.RequireTotp, "require_sso": org.RequireSso, "api_token_max_days": org.ApiTokenMaxDays}) +} + +var errNoSSOProvider = errors.New("api: no enabled sso provider") diff --git a/internal/api/pages.go b/internal/api/pages.go index 33c8b26..a317e69 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -2,13 +2,17 @@ package api import ( "net/http" + "slices" "strings" + "time" "github.com/a-h/templ" "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/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" @@ -17,9 +21,14 @@ import ( func (s *Server) registerPages(r gin.IRouter) { r.GET("/login", s.loginPage) r.GET("/signup", s.signupPage) + r.GET("/invite/:token", s.invitePage) r.GET("/", s.page("console.monitors.title", web.Dashboard)) r.GET("/settings/security", s.securityPage) - r.GET("/settings/sso", s.ssoSettingsPage) + r.GET("/settings/sso", s.orgPage("sso.settings.title", authz.OrgManage, s.ssoSettingsView)) + r.GET("/settings/org", s.orgPage("org.title", authz.OrgManage, s.orgSettingsView)) + r.GET("/settings/members", s.orgPage("members.title", authz.MembersRead, s.membersView)) + r.GET("/settings/roles", s.orgPage("roles.title", authz.MembersRead, s.rolesView)) + r.GET("/settings/tokens", s.orgPage("tokens.title", "", s.tokensView)) } // flashErrors lists the codes a redirect may ask a page to display. Anything @@ -28,6 +37,7 @@ var flashErrors = map[ssoError]bool{ "sso_unavailable": true, "sso_provider_error": true, "sso_expired": true, "sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true, "sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true, + "totp_required_by_org": true, "sso_required_by_org": true, } func (s *Server) pageFor(c *gin.Context, titleID string) web.Page { @@ -44,9 +54,19 @@ func (s *Server) pageFor(c *gin.Context, titleID string) web.Page { return p } +// localPath returns next if it is a path on this site, so login redirects +// cannot send users to another origin. +func localPath(next string) string { + if strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") && !strings.Contains(next, `\`) { + return next + } + return "/" +} + func (s *Server) loginPage(c *gin.Context) { + next := localPath(c.Query("next")) if auth.Current(c) != nil { - c.Redirect(http.StatusSeeOther, "/") + c.Redirect(http.StatusSeeOther, next) return } allowed, err := s.signupAllowed(c.Request.Context()) @@ -54,7 +74,7 @@ func (s *Server) loginPage(c *gin.Context) { internalError(c, err) return } - web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed)) + web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed, next)) } func (s *Server) signupPage(c *gin.Context) { @@ -70,30 +90,100 @@ func (s *Server) signupPage(c *gin.Context) { web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"))) } +// consoleMe loads the signed-in user and, if an organization is active, +// their permissions and policy state there. The principal is nil when the +// user has no active organization or is no longer a member. +func (s *Server) consoleMe(c *gin.Context, sess *auth.Session) (web.Me, *principal, error) { + ctx := c.Request.Context() + m, err := s.loadMe(ctx, sess) + if err != nil { + return web.Me{}, nil, err + } + me := toWebMe(m) + me.Can = map[string]bool{} + if sess.OrgID == uuid.Nil { + return me, nil, nil + } + p := &principal{UserID: sess.UserID, Session: sess} + var member bool + err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error { + var err error + if p.Org, err = q.GetOrg(ctx, sess.OrgID); err != nil { + return err + } + p.Grants, member, err = loadGrants(ctx, q, sess.OrgID, sess.UserID) + return err + }) + if err != nil || !member { + return me, nil, err + } + for _, perm := range authz.All { + me.Can[string(perm)] = p.Grants.Can(perm) + } + me.Policy = policyViolation(p.Org, p.Grants.Owner, sess) + return me, p, nil +} + func (s *Server) page(titleID string, view func(web.Page, web.Me) templ.Component) gin.HandlerFunc { return func(c *gin.Context) { sess := auth.Current(c) if sess == nil { - c.Redirect(http.StatusSeeOther, "/login") + c.Redirect(http.StatusSeeOther, "/login?next="+c.Request.URL.Path) return } - me, err := s.loadMe(c.Request.Context(), sess) + me, _, err := s.consoleMe(c, sess) if err != nil { internalError(c, err) return } - web.Render(c, http.StatusOK, view(s.pageFor(c, titleID), toWebMe(me))) + web.Render(c, http.StatusOK, view(s.pageFor(c, titleID), me)) + } +} + +type orgPageView func(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) + +// orgPage renders an organization settings page. perm may be empty for +// pages every member can open. +func (s *Server) orgPage(titleID string, perm authz.Permission, view orgPageView) gin.HandlerFunc { + return func(c *gin.Context) { + sess := auth.Current(c) + if sess == nil { + c.Redirect(http.StatusSeeOther, "/login?next="+c.Request.URL.Path) + return + } + me, p, err := s.consoleMe(c, sess) + if err != nil { + internalError(c, err) + return + } + switch { + case p == nil: + c.Redirect(http.StatusSeeOther, "/") + return + case me.Policy != "": + c.Redirect(http.StatusSeeOther, "/settings/security?sso_error="+me.Policy) + return + case perm != "" && !p.Grants.Can(perm): + c.Redirect(http.StatusSeeOther, "/") + return + } + comp, err := view(c, p, s.pageFor(c, titleID), me) + if err != nil { + internalError(c, err) + return + } + web.Render(c, http.StatusOK, comp) } } func (s *Server) securityPage(c *gin.Context) { sess := auth.Current(c) if sess == nil { - c.Redirect(http.StatusSeeOther, "/login") + c.Redirect(http.StatusSeeOther, "/login?next=/settings/security") return } ctx := c.Request.Context() - me, err := s.loadMe(ctx, sess) + me, _, err := s.consoleMe(c, sess) if err != nil { internalError(c, err) return @@ -120,47 +210,192 @@ func (s *Server) securityPage(c *gin.Context) { return } } - web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), toWebMe(me), identities, canLink)) + web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink)) } -func (s *Server) ssoSettingsPage(c *gin.Context) { - sess := auth.Current(c) - if sess == nil { - c.Redirect(http.StatusSeeOther, "/login") - return +func toWebRoles(rows []store.Role) []web.Role { + out := make([]web.Role, len(rows)) + for i, r := range rows { + out[i] = web.Role{ID: r.ID.String(), Name: r.Name, BuiltIn: r.OrgID == nil, Permissions: authz.NewSet(r.Permissions...).Strings()} } + return out +} + +// grantable lists the permissions p may hand out organization-wide. +func grantable(p *principal) []string { + var out []string + for _, perm := range authz.All { + if p.Grants.CanGrant(authz.NewSet(perm), nil) { + out = append(out, string(perm)) + } + } + return out +} + +func (s *Server) ssoSettingsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { ctx := c.Request.Context() - me, err := s.loadMe(ctx, sess) - if err != nil { - internalError(c, err) - return - } - wm := toWebMe(me) - if !wm.IsOwner { - c.Redirect(http.StatusSeeOther, "/") - return - } - var rows []store.SsoProvider - err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error { - rows, err = q.ListSSOProviders(ctx) + var ( + rows []store.SsoProvider + roles []store.Role + ) + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + if rows, err = q.ListSSOProviders(ctx); err != nil { + return err + } + roles, err = q.ListRoles(ctx) return err }) if err != nil { - internalError(c, err) - return + return nil, err } view := web.SSOSettings{ RedirectURL: s.sso.RedirectURL(), - LoginURL: s.cfg.PublicURL + "/sso/" + wm.ActiveSlug, + LoginURL: s.cfg.PublicURL + "/sso/" + p.Org.Slug, + Roles: toWebRoles(roles), } for _, r := range rows { - view.Providers = append(view.Providers, web.SSOProvider{ + pr := web.SSOProvider{ ID: r.ID.String(), Name: r.Name, Issuer: r.Issuer, ClientID: r.ClientID, HasSecret: r.ClientSecret != nil, AllowedDomains: strings.Join(r.AllowedDomains, ", "), AutoProvision: r.AutoProvision, Enabled: r.Enabled, - }) + } + if r.DefaultRoleID != nil { + pr.DefaultRoleID = r.DefaultRoleID.String() + } + view.Providers = append(view.Providers, pr) } - web.Render(c, http.StatusOK, web.SSOSettingsPage(s.pageFor(c, "sso.settings.title"), wm, view)) + return web.SSOSettingsPage(page, me, view), nil +} + +func (s *Server) orgSettingsView(_ *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { + v := web.OrgSettings{RequireTOTP: p.Org.RequireTotp, RequireSSO: p.Org.RequireSso} + if p.Org.ApiTokenMaxDays != nil { + v.TokenMaxDays = int(*p.Org.ApiTokenMaxDays) + } + return web.OrgSettingsPage(page, me, v), nil +} + +func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { + c.Set(ctxPrincipal, p) + members, err := s.loadMembers(c) + if err != nil { + return nil, err + } + ctx := c.Request.Context() + var ( + roles []store.Role + pending []store.ListPendingInvitationsRow + ) + err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + if roles, err = q.ListRoles(ctx); err != nil { + return err + } + pending, err = q.ListPendingInvitations(ctx) + return err + }) + if err != nil { + return nil, err + } + v := web.MembersView{CanManage: p.Grants.Can(authz.MembersManage)} + for _, r := range toWebRoles(roles) { + if p.Grants.CanGrant(authz.NewSet(r.Permissions...), nil) { + v.Roles = append(v.Roles, r) + } + } + for _, m := range members { + wm := web.Member{UserID: m.UserID.String(), Email: m.Email, DisplayName: m.DisplayName, IsOwner: m.IsOwner} + for _, a := range m.Assignments { + wa := web.Assignment{ID: a.ID.String(), RoleName: a.RoleName} + if a.ResourceType != nil { + wa.Scope = i18n.T(ctx, "scope."+*a.ResourceType) + } + wm.Assignments = append(wm.Assignments, wa) + } + v.Members = append(v.Members, wm) + } + for _, inv := range pending { + v.Invitations = append(v.Invitations, web.PendingInvite{ID: inv.ID.String(), Email: inv.Email, RoleName: inv.RoleName}) + } + return web.MembersPage(page, me, v), nil +} + +func (s *Server) rolesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { + ctx := c.Request.Context() + var roles []store.Role + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + roles, err = q.ListRoles(ctx) + return err + }) + if err != nil { + return nil, err + } + return web.RolesPage(page, me, web.RolesView{ + Roles: toWebRoles(roles), + Permissions: authz.NewSet(authz.All...).Strings(), + Grantable: grantable(p), + CanManage: p.Grants.Can(authz.RolesManage), + }), nil +} + +func (s *Server) tokensView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { + ctx := c.Request.Context() + showAll := p.Grants.Can(authz.TokensManage) + var filter *uuid.UUID + if !showAll { + filter = &p.UserID + } + var rows []store.ListAPITokensRow + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + rows, err = q.ListAPITokens(ctx, store.ListAPITokensParams{OrgID: p.Org.ID, UserID: filter}) + return err + }) + if err != nil { + return nil, err + } + v := web.TokensView{Grantable: grantable(p), ShowOwner: showAll, ExpiryDays: expiryChoices(p.Org.ApiTokenMaxDays)} + if p.Org.ApiTokenMaxDays != nil { + v.MaxDays = int(*p.Org.ApiTokenMaxDays) + } + never := i18n.T(ctx, "tokens.never") + for _, r := range rows { + t := web.Token{ + ID: r.ID.String(), Name: r.Name, Prefix: r.Prefix, UserEmail: r.UserEmail, + Permissions: authz.NewSet(r.Permissions...).Strings(), CreatedAt: r.CreatedAt.Format(time.DateOnly), + ExpiresAt: never, LastUsedAt: "–", + } + if r.ExpiresAt != nil { + t.ExpiresAt = r.ExpiresAt.Format(time.DateOnly) + } + if r.LastUsedAt != nil { + t.LastUsedAt = r.LastUsedAt.Format(time.DateTime) + } + v.Tokens = append(v.Tokens, t) + } + return web.TokensPage(page, me, v), nil +} + +// expiryChoices returns the token lifetimes to offer, in days, honoring the +// org's limit. 0 stands for no expiry and is only offered without a limit. +func expiryChoices(limit *int32) []int { + defaults := []int{90, 30, 365, 0} + if limit == nil { + return defaults + } + max := int(*limit) + var out []int + for _, d := range defaults { + if d > 0 && d <= max { + out = append(out, d) + } + } + if !slices.Contains(out, max) { + out = append(out, max) + } + return out } func toWebMe(m meView) web.Me { @@ -169,7 +404,6 @@ func toWebMe(m meView) web.Me { DisplayName: m.DisplayName, TOTP: m.TOTP, ActiveOrg: m.ActiveOrg.String(), - TOTPMissing: m.TOTPEnrollmentRequired, RecoveryCodesLeft: m.RecoveryCodesLeft, } for _, o := range m.Orgs { diff --git a/internal/api/permissions_test.go b/internal/api/permissions_test.go new file mode 100644 index 0000000..8262ab1 --- /dev/null +++ b/internal/api/permissions_test.go @@ -0,0 +1,276 @@ +package api_test + +import ( + "net/http" + "strings" + "testing" + "time" + + "github.com/pquerna/otp/totp" +) + +const password = "correct horse battery" + +// invite creates an invitation from b and returns its token. +func (b *browser) invite(email, roleID string) string { + b.t.Helper() + st, body := b.do("POST", "/api/v1/org/invitations", map[string]any{"email": email, "role_id": roleID}) + if st != http.StatusCreated { + b.t.Fatalf("invite(%s) = %d %v, want 201", email, st, body) + } + u := body["url"].(string) + return u[strings.LastIndex(u, "/")+1:] +} + +// joinVia signs up a new account through an invitation. +func (e *env) joinVia(t *testing.T, tok string) *browser { + t.Helper() + b := e.browser(t) + st, body := b.do("POST", "/api/v1/invitations/"+tok+"/signup", map[string]any{"password": password}) + if st != http.StatusOK { + t.Fatalf("invite signup = %d %v, want 200", st, body) + } + return b +} + +func (b *browser) roleID(key string) string { + b.t.Helper() + _, body := b.do("GET", "/api/v1/org/roles", nil) + for _, r := range body["roles"].([]any) { + r := r.(map[string]any) + if r["key"] == key || r["name"] == key { + return r["id"].(string) + } + } + b.t.Fatalf("role %q not found in %v", key, body) + return "" +} + +func (b *browser) userID(email string) string { + b.t.Helper() + _, body := b.do("GET", "/api/v1/org/members", nil) + for _, m := range body["members"].([]any) { + m := m.(map[string]any) + if m["email"] == email { + return m["user_id"].(string) + } + } + b.t.Fatalf("member %q not found", email) + return "" +} + +func expect(t *testing.T, what string, st int, body map[string]any, wantStatus int, wantCode string) { + t.Helper() + if st != wantStatus || (wantCode != "" && body["error"] != wantCode) { + t.Errorf("%s = %d %v, want %d %s", what, st, body["error"], wantStatus, wantCode) + } +} + +func TestPermissions(t *testing.T) { + e := newEnv(t) + domain := uniq("p") + ".test" + owner := e.browser(t) + owner.signup("owner@"+domain, uniq("perm-")) + + editorTok := owner.invite("editor@"+domain, owner.roleID("editor")) + editor := e.joinVia(t, editorTok) + + t.Run("invitation works once", func(t *testing.T) { + st, body := e.browser(t).do("POST", "/api/v1/invitations/"+editorTok+"/signup", map[string]any{"password": password}) + expect(t, "second use", st, body, http.StatusGone, "invitation_invalid") + }) + + t.Run("editor permissions", func(t *testing.T) { + st, body := editor.do("GET", "/api/v1/org/members", nil) + expect(t, "editor GET members", st, body, http.StatusOK, "") + st, body = editor.do("GET", "/api/v1/org/sso", nil) + expect(t, "editor GET sso", st, body, http.StatusForbidden, "forbidden") + st, body = editor.do("POST", "/api/v1/org/invitations", map[string]any{"email": "x@" + domain, "role_id": owner.roleID("viewer")}) + expect(t, "editor invite", st, body, http.StatusForbidden, "forbidden") + }) + + // A delegated people manager may only hand out what they hold. + st, body := owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "People", "permissions": []string{"members.manage"}}) + expect(t, "create role", st, body, http.StatusCreated, "") + st, body = owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "Readers", "permissions": []string{"members.read"}}) + expect(t, "create role", st, body, http.StatusCreated, "") + manager := e.joinVia(t, owner.invite("manager@"+domain, owner.roleID("People"))) + + t.Run("no escalation through delegation", func(t *testing.T) { + editorID := owner.userID("editor@" + domain) + st, body := manager.do("POST", "/api/v1/org/members/"+editorID+"/roles", map[string]any{"role_id": owner.roleID("admin")}) + expect(t, "manager assigns admin", st, body, http.StatusForbidden, "permission_escalation") + st, body = manager.do("POST", "/api/v1/org/members/"+editorID+"/roles", map[string]any{"role_id": owner.roleID("Readers")}) + expect(t, "manager assigns readers", st, body, http.StatusCreated, "") + st, body = manager.do("DELETE", "/api/v1/org/members/"+editorID, nil) + expect(t, "manager removes stronger editor", st, body, http.StatusForbidden, "permission_escalation") + st, body = manager.do("DELETE", "/api/v1/org/members/"+owner.userID("owner@"+domain), nil) + expect(t, "manager removes owner", st, body, http.StatusForbidden, "owner_cannot_be_removed") + st, body = manager.do("POST", "/api/v1/org/invitations", map[string]any{"email": "y@" + domain, "role_id": owner.roleID("editor")}) + expect(t, "manager invites editor", st, body, http.StatusForbidden, "permission_escalation") + st, body = manager.do("POST", "/api/v1/org/roles", map[string]any{"name": "Sneaky", "permissions": []string{"org.manage"}}) + expect(t, "manager creates role", st, body, http.StatusForbidden, "forbidden") + }) + + t.Run("settings pages", func(t *testing.T) { + pages := []string{"/settings/members", "/settings/roles", "/settings/tokens", "/settings/org", "/settings/sso", "/settings/security", "/"} + for _, path := range pages { + if got := owner.visit(path); got.Path != path { + t.Errorf("owner GET %s ended at %s", path, got.Path) + } + } + for path, want := range map[string]string{"/settings/sso": "/", "/settings/org": "/", "/settings/members": "/settings/members", "/settings/tokens": "/settings/tokens"} { + if got := editor.visit(path); got.Path != want { + t.Errorf("editor GET %s ended at %s, want %s", path, got.Path, want) + } + } + }) + + t.Run("built-in roles are read-only", func(t *testing.T) { + st, body := owner.do("PUT", "/api/v1/org/roles/"+owner.roleID("viewer"), map[string]any{"name": "Viewer", "permissions": []string{"org.manage"}}) + expect(t, "update built-in", st, body, http.StatusConflict, "role_built_in") + st, body = owner.do("DELETE", "/api/v1/org/roles/"+owner.roleID("People"), nil) + expect(t, "delete role in use", st, body, http.StatusConflict, "role_in_use") + }) + + t.Run("api tokens follow their owner", func(t *testing.T) { + st, body := editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "too much", "permissions": []string{"org.manage"}}) + expect(t, "token beyond own rights", st, body, http.StatusForbidden, "permission_escalation") + st, body = editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"members.read", "monitors.write"}, "expires_in_days": 30}) + expect(t, "create token", st, body, http.StatusCreated, "") + api := &browser{t: t, base: editor.base, hc: e.srv.Client(), bearer: body["token"].(string)} + + st, body = api.do("GET", "/api/v1/org/members", nil) + expect(t, "token GET members", st, body, http.StatusOK, "") + st, body = api.do("GET", "/api/v1/org/sso", nil) + expect(t, "token GET sso", st, body, http.StatusForbidden, "forbidden") + st, body = api.do("POST", "/api/v1/org/tokens", map[string]any{"name": "child", "permissions": []string{"members.read"}}) + expect(t, "token mints token", st, body, http.StatusForbidden, "session_required") + + // Losing the role that granted members.read removes it from the token. + editorID := owner.userID("editor@" + domain) + _, members := owner.do("GET", "/api/v1/org/members", nil) + for _, m := range members["members"].([]any) { + m := m.(map[string]any) + if m["user_id"] != editorID { + continue + } + for _, a := range m["assignments"].([]any) { + owner.do("DELETE", "/api/v1/org/assignments/"+a.(map[string]any)["id"].(string), nil) + } + } + st, body = api.do("GET", "/api/v1/org/members", nil) + expect(t, "token after role removal", st, body, http.StatusForbidden, "forbidden") + + st, body = owner.do("DELETE", "/api/v1/org/members/"+editorID, nil) + expect(t, "owner removes editor", st, body, http.StatusNoContent, "") + st, body = api.do("GET", "/api/v1/org/members", nil) + expect(t, "token after removal", st, body, http.StatusUnauthorized, "unauthenticated") + st, _ = editor.do("GET", "/api/v1/me", nil) + if st != http.StatusUnauthorized { + t.Errorf("removed member's session GET /me = %d, want 401", st) + } + }) + + t.Run("org policies", func(t *testing.T) { + st, body := owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_sso": true}) + expect(t, "require sso without provider", st, body, http.StatusConflict, "sso_no_provider") + st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_totp": true}) + expect(t, "require totp without own totp", st, body, http.StatusConflict, "policy_would_lock_you_out") + + owner.enableTOTP() + st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_totp": true}) + expect(t, "require totp", st, body, http.StatusOK, "") + st, body = manager.do("GET", "/api/v1/org/members", nil) + expect(t, "password-only member", st, body, http.StatusForbidden, "totp_required_by_org") + + // The manager enables TOTP in the current session and is let in. + _, setup := manager.do("POST", "/api/v1/me/totp/setup", nil) + code, _ := totp.GenerateCode(setup["secret"].(string), time.Now()) + manager.do("POST", "/api/v1/me/totp/enable", map[string]any{"code": code}) + st, body = manager.do("GET", "/api/v1/org/members", nil) + expect(t, "member after enabling totp", st, body, http.StatusOK, "") + }) + + t.Run("invitation for another address", func(t *testing.T) { + tok := owner.invite("someone@"+domain, owner.roleID("viewer")) + st, body := manager.do("POST", "/api/v1/invitations/"+tok+"/accept", nil) + expect(t, "accept as other user", st, body, http.StatusForbidden, "invitation_email_mismatch") + }) + + t.Run("custom roles stay in their org", func(t *testing.T) { + other := e.browser(t) + other.signup("x@"+uniq("o")+".test", uniq("other-")) + _, body := other.do("GET", "/api/v1/org/roles", nil) + for _, r := range body["roles"].([]any) { + if name := r.(map[string]any)["name"]; name == "People" || name == "Readers" { + t.Errorf("other org sees custom role %v", name) + } + } + }) +} + +func TestTokenOversightAndLifetimePolicy(t *testing.T) { + e := newEnv(t) + domain := uniq("t") + ".test" + owner := e.browser(t) + owner.signup("owner@"+domain, uniq("tok-")) + editor := e.joinVia(t, owner.invite("editor@"+domain, owner.roleID("editor"))) + + st, body := editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "forever", "permissions": []string{"monitors.read"}}) + expect(t, "editor creates non-expiring token", st, body, http.StatusCreated, "") + editorTokenID := body["id"].(string) + api := &browser{t: t, base: editor.base, hc: e.srv.Client(), bearer: body["token"].(string)} + owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "own", "permissions": []string{"monitors.read"}}) + + tokenNames := func(b *browser) []string { + _, body := b.do("GET", "/api/v1/org/tokens", nil) + var names []string + for _, tk := range body["tokens"].([]any) { + names = append(names, tk.(map[string]any)["name"].(string)) + } + return names + } + if got := tokenNames(owner); len(got) != 2 { + t.Errorf("owner sees tokens %v, want both", got) + } + if got := tokenNames(editor); len(got) != 1 || got[0] != "forever" { + t.Errorf("editor sees tokens %v, want only own", got) + } + + st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"api_token_max_days": 30}) + expect(t, "set lifetime policy", st, body, http.StatusOK, "") + _, list := owner.do("GET", "/api/v1/org/tokens", nil) + for _, tk := range list["tokens"].([]any) { + tk := tk.(map[string]any) + exp, _ := time.Parse(time.RFC3339Nano, fmtString(tk["expires_at"])) + if exp.IsZero() || exp.After(time.Now().Add(31*24*time.Hour)) { + t.Errorf("token %v expires_at = %v, want within 30 days", tk["name"], tk["expires_at"]) + } + } + + for _, days := range []int{0, 31} { + st, body = editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "x", "permissions": []string{"monitors.read"}, "expires_in_days": days}) + expect(t, "token beyond policy", st, body, http.StatusUnprocessableEntity, "token_lifetime_exceeds_policy") + } + st, body = editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ok", "permissions": []string{"monitors.read"}, "expires_in_days": 30}) + expect(t, "token within policy", st, body, http.StatusCreated, "") + + st, body = owner.do("DELETE", "/api/v1/org/tokens/"+editorTokenID, nil) + expect(t, "owner revokes editor token", st, body, http.StatusNoContent, "") + st, body = api.do("GET", "/api/v1/org/tokens", nil) + expect(t, "revoked token", st, body, http.StatusUnauthorized, "unauthenticated") + + st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"api_token_max_days": 0}) + if st != http.StatusOK || body["api_token_max_days"] != nil { + t.Errorf("clear lifetime policy = %d %v, want 200 with null", st, body) + } + if got := owner.visit("/settings/tokens"); got.Path != "/settings/tokens" { + t.Errorf("tokens page ended at %s", got) + } +} + +func fmtString(v any) string { + s, _ := v.(string) + return s +} diff --git a/internal/api/server.go b/internal/api/server.go index 2687d31..47cbd75 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -12,6 +12,7 @@ import ( "github.com/redis/go-redis/v9" "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/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" @@ -85,11 +86,36 @@ func (s *Server) Mount(r gin.IRouter) { me.POST("/totp/disable", s.totpDisable) me.POST("/totp/recovery-codes", s.regenerateRecoveryCodes) - org := v1.Group("/org", auth.Require(), s.requireOwner()) - org.GET("/sso", s.listSSOProviders) - org.POST("/sso", s.createSSOProvider) - org.PUT("/sso/:id", s.updateSSOProvider) - org.DELETE("/sso/:id", s.deleteSSOProvider) + v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation) + v1.POST("/invitations/:token/signup", s.inviteSignup) + + org := v1.Group("/org", s.orgAccess()) + org.PUT("/policy", sessionOnly(), can(authz.OrgManage), s.updatePolicy) + + org.GET("/sso", can(authz.OrgManage), s.listSSOProviders) + org.POST("/sso", sessionOnly(), can(authz.OrgManage), s.createSSOProvider) + org.PUT("/sso/:id", sessionOnly(), can(authz.OrgManage), s.updateSSOProvider) + org.DELETE("/sso/:id", sessionOnly(), can(authz.OrgManage), s.deleteSSOProvider) + + org.GET("/members", can(authz.MembersRead), s.listMembers) + org.DELETE("/members/:user", sessionOnly(), can(authz.MembersManage), s.removeMember) + org.POST("/members/:user/roles", sessionOnly(), can(authz.MembersManage), s.assignRole) + org.DELETE("/assignments/:id", sessionOnly(), can(authz.MembersManage), s.unassignRole) + + org.GET("/invitations", can(authz.MembersRead), s.listInvitations) + org.POST("/invitations", sessionOnly(), can(authz.MembersManage), s.createInvitation) + org.DELETE("/invitations/:id", sessionOnly(), can(authz.MembersManage), s.deleteInvitation) + + org.GET("/roles", can(authz.MembersRead), s.listRoles) + org.POST("/roles", sessionOnly(), can(authz.RolesManage), s.createRole) + org.PUT("/roles/:id", sessionOnly(), can(authz.RolesManage), s.updateRole) + org.DELETE("/roles/:id", sessionOnly(), can(authz.RolesManage), s.deleteRole) + + // Every member may hold personal tokens; their rights are capped by the + // member's own. + org.GET("/tokens", s.listTokens) + org.POST("/tokens", sessionOnly(), s.createToken) + org.DELETE("/tokens/:id", s.deleteToken) g.GET("/sso", s.ssoLookup) g.GET("/sso/callback", s.ssoCallback) diff --git a/internal/api/sso.go b/internal/api/sso.go index 252e9b5..7dbb1ce 100644 --- a/internal/api/sso.go +++ b/internal/api/sso.go @@ -23,6 +23,9 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/web" ) +// viewerRoleID is the built-in Viewer role seeded by migration 00009. +var viewerRoleID = uuid.MustParse("00000000-0000-0000-0000-00000000a003") + const ( ssoCookie = "__Host-sso" ssoFlowTTL = 10 * time.Minute @@ -262,7 +265,9 @@ func (s *Server) ssoCallback(c *gin.Context) { if locale == "" { locale = i18n.Lang(ctx) } - sess, err := s.sessions.Create(ctx, userID, row.OrgID, locale) + sess, err := s.sessions.Create(ctx, auth.NewSession{ + UserID: userID, OrgID: row.OrgID, Locale: locale, Method: auth.MethodSSO, SSOOrg: row.OrgID, + }) if err != nil { internalError(c, err) return @@ -322,6 +327,13 @@ func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl s if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: row.OrgID, UserID: u.ID}); err != nil { return err } + role := viewerRoleID + if row.DefaultRoleID != nil { + role = *row.DefaultRoleID + } + if _, err := q.CreateAssignment(ctx, store.CreateAssignmentParams{OrgID: row.OrgID, UserID: u.ID, RoleID: role}); err != nil { + return err + } userID = u.ID return q.CreateIdentity(ctx, store.CreateIdentityParams{ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: u.ID, Email: nonEmpty(email)}) }) diff --git a/internal/api/sso_admin.go b/internal/api/sso_admin.go index 5d72986..98146a8 100644 --- a/internal/api/sso_admin.go +++ b/internal/api/sso_admin.go @@ -11,62 +11,29 @@ import ( "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/sso" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" - "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) -const ctxOrgKey = "api.org" - -// requireOwner admits only the owner of the session's active org. It is a -// stand-in until role-based permissions exist (#6). -func (s *Server) requireOwner() gin.HandlerFunc { - return func(c *gin.Context) { - sess := auth.Current(c) - if sess == nil || sess.OrgID == uuid.Nil { - fail(c, http.StatusForbidden, "forbidden") - return - } - ctx := c.Request.Context() - var m store.Membership - err := s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error { - var err error - m, err = q.GetMembership(ctx, store.GetMembershipParams{OrgID: sess.OrgID, UserID: sess.UserID}) - return err - }) - if errors.Is(err, pgx.ErrNoRows) || (err == nil && !m.IsOwner) { - fail(c, http.StatusForbidden, "forbidden") - return - } - if err != nil { - internalError(c, err) - return - } - c.Set(ctxOrgKey, sess.OrgID) - c.Next() - } -} - -func orgOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxOrgKey).(uuid.UUID) } - type ssoProviderView struct { - ID uuid.UUID `json:"id"` - Name string `json:"name"` - Issuer string `json:"issuer"` - ClientID string `json:"client_id"` - HasClientSecret bool `json:"has_client_secret"` - Scopes []string `json:"scopes"` - AllowedDomains []string `json:"allowed_domains"` - AutoProvision bool `json:"auto_provision"` - Enabled bool `json:"enabled"` + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Issuer string `json:"issuer"` + ClientID string `json:"client_id"` + HasClientSecret bool `json:"has_client_secret"` + Scopes []string `json:"scopes"` + AllowedDomains []string `json:"allowed_domains"` + AutoProvision bool `json:"auto_provision"` + DefaultRoleID *uuid.UUID `json:"default_role_id"` + Enabled bool `json:"enabled"` } func viewSSOProvider(p store.SsoProvider) ssoProviderView { return ssoProviderView{ ID: p.ID, Name: p.Name, Issuer: p.Issuer, ClientID: p.ClientID, HasClientSecret: p.ClientSecret != nil, Scopes: p.Scopes, - AllowedDomains: p.AllowedDomains, AutoProvision: p.AutoProvision, Enabled: p.Enabled, + AllowedDomains: p.AllowedDomains, AutoProvision: p.AutoProvision, DefaultRoleID: p.DefaultRoleID, Enabled: p.Enabled, } } @@ -79,7 +46,9 @@ type ssoProviderRequest struct { Scopes []string `json:"scopes" binding:"max=20,dive,max=100"` AllowedDomains []string `json:"allowed_domains" binding:"max=50,dive,max=253"` AutoProvision bool `json:"auto_provision"` - Enabled *bool `json:"enabled"` + // DefaultRoleID is assigned to auto-provisioned users; nil means Viewer. + DefaultRoleID *uuid.UUID `json:"default_role_id"` + Enabled *bool `json:"enabled"` } var domainRE = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`) @@ -122,7 +91,7 @@ func (r *ssoProviderRequest) normalize() string { func (s *Server) listSSOProviders(c *gin.Context) { ctx := c.Request.Context() var rows []store.SsoProvider - err := s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error { + err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { var err error rows, err = q.ListSSOProviders(ctx) return err @@ -143,6 +112,28 @@ func (s *Server) validateSSORequest(c *gin.Context, req *ssoProviderRequest) boo fail(c, http.StatusUnprocessableEntity, code) return false } + if req.DefaultRoleID != nil { + ctx := c.Request.Context() + var role store.Role + err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { + var err error + role, err = q.GetRole(ctx, *req.DefaultRoleID) + return err + }) + if errors.Is(err, pgx.ErrNoRows) { + fail(c, http.StatusUnprocessableEntity, "role_not_found") + return false + } + if err != nil { + internalError(c, err) + return false + } + // Auto-provisioning hands this role to anyone the IdP vouches for. + if !current(c).Grants.CanGrant(authz.NewSet(role.Permissions...), nil) { + fail(c, http.StatusForbidden, "permission_escalation") + return false + } + } if err := s.sso.ValidateIssuer(c.Request.Context(), req.Issuer); err != nil { code := "sso_discovery_failed" switch { @@ -169,12 +160,12 @@ func (s *Server) createSSOProvider(c *gin.Context) { secret = s.keys.Seal([]byte(req.ClientSecret), id[:]) } var row store.SsoProvider - err := s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error { + err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { var err error row, err = q.CreateSSOProvider(ctx, store.CreateSSOProviderParams{ - ID: id, OrgID: orgOf(c), Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, + ID: id, OrgID: current(c).Org.ID, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, ClientSecret: secret, Scopes: req.Scopes, AllowedDomains: req.AllowedDomains, - AutoProvision: req.AutoProvision, Enabled: req.Enabled == nil || *req.Enabled, + AutoProvision: req.AutoProvision, DefaultRoleID: req.DefaultRoleID, Enabled: req.Enabled == nil || *req.Enabled, }) return err }) @@ -201,12 +192,12 @@ func (s *Server) updateSSOProvider(c *gin.Context) { secret = s.keys.Seal([]byte(req.ClientSecret), id[:]) } var row store.SsoProvider - err = s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error { + err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { var err error row, err = q.UpdateSSOProvider(ctx, store.UpdateSSOProviderParams{ ID: id, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, ClientSecret: secret, Scopes: req.Scopes, AllowedDomains: req.AllowedDomains, AutoProvision: req.AutoProvision, - Enabled: req.Enabled == nil || *req.Enabled, + DefaultRoleID: req.DefaultRoleID, Enabled: req.Enabled == nil || *req.Enabled, }) return err }) @@ -229,7 +220,7 @@ func (s *Server) deleteSSOProvider(c *gin.Context) { } ctx := c.Request.Context() var n int64 - err = s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error { + err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { var err error n, err = q.DeleteSSOProvider(ctx, id) return err diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go index 0c3ace2..1803ad3 100644 --- a/internal/api/sso_test.go +++ b/internal/api/sso_test.go @@ -99,6 +99,8 @@ type browser struct { base string hc *http.Client csrf string + // bearer, if set, is sent as an API token instead of relying on cookies. + bearer string } func (e *env) browser(t *testing.T) *browser { @@ -121,6 +123,9 @@ func (b *browser) do(method, path string, body any) (int, map[string]any) { if b.csrf != "" { req.Header.Set("X-CSRF-Token", b.csrf) } + if b.bearer != "" { + req.Header.Set("Authorization", "Bearer "+b.bearer) + } resp, err := b.hc.Do(req) if err != nil { b.t.Fatalf("%s %s failed: %v", method, path, err) @@ -142,6 +147,9 @@ func (b *browser) visit(path string) *url.URL { b.t.Fatalf("GET %s failed: %v", path, err) } _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + b.t.Errorf("GET %s ended with status %d at %s", path, resp.StatusCode, resp.Request.URL) + } return resp.Request.URL } diff --git a/internal/api/tokens.go b/internal/api/tokens.go new file mode 100644 index 0000000..9b7efa0 --- /dev/null +++ b/internal/api/tokens.go @@ -0,0 +1,211 @@ +package api + +import ( + "context" + "crypto/sha256" + "errors" + "net/http" + "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/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +// tokenPrefix makes tokens recognizable to secret scanners and to humans. +const tokenPrefix = "ust_" + +func hashToken(tok string) []byte { + sum := sha256.Sum256([]byte(tok)) + return sum[:] +} + +func bearerToken(c *gin.Context) string { + h := c.GetHeader("Authorization") + if len(h) < 7 || !strings.EqualFold(h[:7], "bearer ") { + return "" + } + return strings.TrimSpace(h[7:]) +} + +func (s *Server) tokenPrincipal(ctx context.Context, tok string) (*principal, int, string, error) { + if !strings.HasPrefix(tok, tokenPrefix) { + return nil, http.StatusUnauthorized, "unauthenticated", nil + } + hash := hashToken(tok) + var org uuid.UUID + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + org, err = q.APITokenOrg(ctx, hash) + return err + }) + if err != nil { + return nil, 0, "", err + } + if org == uuid.Nil { + return nil, http.StatusUnauthorized, "unauthenticated", nil + } + p := &principal{} + var ( + row store.ApiToken + member bool + ) + err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error { + var err error + if row, err = q.GetAPITokenByHash(ctx, hash); err != nil { + return err + } + if row.ExpiresAt != nil && !row.ExpiresAt.After(time.Now()) { + return nil + } + if p.Org, err = q.GetOrg(ctx, org); err != nil { + return err + } + if p.Grants, member, err = loadGrants(ctx, q, org, row.UserID); err != nil || !member { + return err + } + return q.TouchAPIToken(ctx, row.ID) + }) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && !member) { + return nil, http.StatusUnauthorized, "unauthenticated", nil + } + if err != nil { + return nil, 0, "", err + } + p.UserID, p.TokenID = row.UserID, row.ID + p.Grants = p.Grants.Restrict(authz.NewSet(row.Permissions...)) + return p, 0, "", nil +} + +type tokenView struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Prefix string `json:"prefix"` + UserID uuid.UUID `json:"user_id"` + UserEmail string `json:"user_email"` + Permissions []string `json:"permissions"` + ExpiresAt *time.Time `json:"expires_at"` + LastUsedAt *time.Time `json:"last_used_at"` + CreatedAt time.Time `json:"created_at"` +} + +func (s *Server) listTokens(c *gin.Context) { + p := current(c) + ctx := c.Request.Context() + // Members see their own tokens; tokens.manage reveals everyone's so the + // owner can audit and revoke them. + var filter *uuid.UUID + if !p.Grants.Can(authz.TokensManage) { + filter = &p.UserID + } + var rows []store.ListAPITokensRow + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + rows, err = q.ListAPITokens(ctx, store.ListAPITokensParams{OrgID: p.Org.ID, UserID: filter}) + return err + }) + if err != nil { + internalError(c, err) + return + } + out := make([]tokenView, len(rows)) + for i, r := range rows { + out[i] = tokenView{ + ID: r.ID, Name: r.Name, Prefix: r.Prefix, UserID: r.UserID, UserEmail: r.UserEmail, + Permissions: r.Permissions, ExpiresAt: r.ExpiresAt, LastUsedAt: r.LastUsedAt, CreatedAt: r.CreatedAt, + } + } + c.JSON(http.StatusOK, gin.H{"tokens": out}) +} + +type createTokenRequest struct { + Name string `json:"name" binding:"required,max=100"` + Permissions []string `json:"permissions" binding:"required,min=1,max=50,dive,max=50"` + // ExpiresInDays of 0 creates a token that does not expire, unless the + // org limits token lifetime. + ExpiresInDays int `json:"expires_in_days" binding:"min=0,max=3650"` +} + +func (s *Server) createToken(c *gin.Context) { + var req createTokenRequest + if !bind(c, &req) { + return + } + p := current(c) + perms := authz.NewSet(req.Permissions...) + if len(perms) == 0 { + fail(c, http.StatusUnprocessableEntity, "invalid_permissions") + return + } + if !p.Grants.CanGrant(perms, nil) { + fail(c, http.StatusForbidden, "permission_escalation") + return + } + if limit := p.Org.ApiTokenMaxDays; limit != nil && (req.ExpiresInDays == 0 || req.ExpiresInDays > int(*limit)) { + fail(c, http.StatusUnprocessableEntity, "token_lifetime_exceeds_policy", "Count", int(*limit)) + return + } + var expires *time.Time + if req.ExpiresInDays > 0 { + t := time.Now().AddDate(0, 0, req.ExpiresInDays) + expires = &t + } + tok := tokenPrefix + auth.RandomToken() + ctx := c.Request.Context() + var row store.ApiToken + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + row, err = q.CreateAPIToken(ctx, store.CreateAPITokenParams{ + OrgID: p.Org.ID, UserID: p.UserID, Name: strings.TrimSpace(req.Name), + TokenHash: hashToken(tok), Prefix: tok[:len(tokenPrefix)+6], + Permissions: perms.Strings(), ExpiresAt: expires, + }) + return err + }) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusCreated, gin.H{"id": row.ID, "token": tok, "prefix": row.Prefix, "permissions": row.Permissions}) +} + +func (s *Server) deleteToken(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 found bool + err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + row, err := q.GetAPIToken(ctx, id) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return err + } + if row.UserID != p.UserID && !p.Grants.Can(authz.TokensManage) { + return nil + } + found = true + _, err = q.DeleteAPIToken(ctx, id) + return err + }) + if err != nil { + internalError(c, err) + return + } + if !found { + fail(c, http.StatusNotFound, "not_found") + return + } + c.Status(http.StatusNoContent) +} diff --git a/internal/auth/session.go b/internal/auth/session.go index 5e5a6a7..f283914 100644 --- a/internal/auth/session.go +++ b/internal/auth/session.go @@ -24,14 +24,40 @@ var ErrNoSession = errors.New("auth: no session") // Session is a signed-in browser. Token is the cookie value and never // stored server side. type Session struct { - Token string - UserID uuid.UUID - OrgID uuid.UUID - Locale string + Token string + UserID uuid.UUID + OrgID uuid.UUID + Locale string + Method Method + // SSOOrg is the organization whose identity provider authenticated the + // session, if Method is MethodSSO. + SSOOrg uuid.UUID CSRF string CreatedAt time.Time } +// Method records how a session was authenticated. Organization policies +// that require TOTP or SSO are checked against it. +type Method string + +// Authentication methods. Sessions from before methods were recorded have +// the empty Method and count as the weakest. +const ( + MethodPassword Method = "password" + MethodPasswordTOTP Method = "password+totp" + MethodSSO Method = "sso" +) + +// NewSession describes a session to create. OrgID, Locale and SSOOrg may be +// empty. +type NewSession struct { + UserID uuid.UUID + OrgID uuid.UUID + Locale string + Method Method + SSOOrg uuid.UUID +} + // CheckCSRF compares token with the session's CSRF token in constant time. func (s *Session) CheckCSRF(token string) bool { return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1 @@ -67,22 +93,27 @@ func RandomToken() string { return base64.RawURLEncoding.EncodeToString(b) } -// Create starts a session. org and locale may be empty. -func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale string) (*Session, error) { +// Create starts a session. +func (s *Sessions) Create(ctx context.Context, n NewSession) (*Session, error) { sess := &Session{ Token: RandomToken(), - UserID: user, - OrgID: org, - Locale: locale, + UserID: n.UserID, + OrgID: n.OrgID, + Locale: n.Locale, + Method: n.Method, + SSOOrg: n.SSOOrg, CSRF: RandomToken(), CreatedAt: s.now(), } + user := n.UserID k := key(sess.Token) _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { p.HSet(ctx, k, map[string]any{ "user": sess.UserID.String(), - "org": orgString(org), - "locale": locale, + "org": orgString(n.OrgID), + "locale": n.Locale, + "method": string(n.Method), + "sso_org": orgString(n.SSOOrg), "csrf": sess.CSRF, "created": sess.CreatedAt.Unix(), }) @@ -137,6 +168,16 @@ func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) return nil } +// SetMethod records a stronger authentication, e.g. after the user proved +// possession of a TOTP device in this session. +func (s *Sessions) SetMethod(ctx context.Context, sess *Session, m Method) error { + if err := s.rdb.HSet(ctx, key(sess.Token), "method", string(m)).Err(); err != nil { + return fmt.Errorf("auth: set method: %w", err) + } + sess.Method = m + return nil +} + // SetLocale changes the session language. func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) error { if err := s.rdb.HSet(ctx, key(sess.Token), "locale", locale).Err(); err != nil { @@ -190,7 +231,17 @@ func decode(token string, v map[string]string) (*Session, error) { if err != nil { return nil, err } - return &Session{Token: token, UserID: user, OrgID: org, Locale: v["locale"], CSRF: v["csrf"], CreatedAt: time.Unix(created, 0)}, nil + var ssoOrg uuid.UUID + if v["sso_org"] != "" { + if ssoOrg, err = uuid.Parse(v["sso_org"]); err != nil { + return nil, err + } + } + return &Session{ + Token: token, UserID: user, OrgID: org, Locale: v["locale"], + Method: Method(v["method"]), SSOOrg: ssoOrg, + CSRF: v["csrf"], CreatedAt: time.Unix(created, 0), + }, nil } func orgString(id uuid.UUID) string { diff --git a/internal/auth/session_test.go b/internal/auth/session_test.go index 148b36b..7e81d68 100644 --- a/internal/auth/session_test.go +++ b/internal/auth/session_test.go @@ -36,7 +36,7 @@ func newTestSessions(t *testing.T) (*Sessions, *time.Time) { func mustCreate(t *testing.T, s *Sessions, user uuid.UUID) *Session { t.Helper() - sess, err := s.Create(context.Background(), user, uuid.Nil, "") + sess, err := s.Create(context.Background(), NewSession{UserID: user}) if err != nil { t.Fatalf("Create() failed: %v", err) } @@ -48,7 +48,7 @@ func TestSessionRoundTrip(t *testing.T) { ctx := context.Background() user, org := uuid.New(), uuid.New() - created, err := s.Create(ctx, user, org, "de") + created, err := s.Create(ctx, NewSession{UserID: user, OrgID: org, Locale: "de", Method: MethodSSO, SSOOrg: org}) if err != nil { t.Fatalf("Create() failed: %v", err) } @@ -56,7 +56,7 @@ func TestSessionRoundTrip(t *testing.T) { if err != nil { t.Fatalf("Get() failed: %v", err) } - if got.UserID != user || got.OrgID != org || got.Locale != "de" || got.CSRF != created.CSRF { + if got.UserID != user || got.OrgID != org || got.Locale != "de" || got.Method != MethodSSO || got.SSOOrg != org || got.CSRF != created.CSRF { t.Errorf("Get() = %+v, want user %v org %v locale de csrf %q", got, user, org, created.CSRF) } for token, want := range map[string]bool{created.CSRF: true, "": false, "x": false} { diff --git a/internal/authz/authz.go b/internal/authz/authz.go new file mode 100644 index 0000000..4f79cb8 --- /dev/null +++ b/internal/authz/authz.go @@ -0,0 +1,198 @@ +// Package authz decides what a member of an organization may do. +// +// Permissions are granted through roles. A role assignment applies either to +// the whole organization or to a single resource such as one status page. +// The organization owner holds every permission implicitly. +package authz + +import ( + "slices" + + "github.com/google/uuid" +) + +// Permission names one capability. The string form is stored in the database +// and exposed through the API, so existing values must never change. +type Permission string + +// Permissions. A *.write or *.manage permission implies the matching read. +const ( + OrgManage Permission = "org.manage" + MembersRead Permission = "members.read" + MembersManage Permission = "members.manage" + RolesManage Permission = "roles.manage" + TokensManage Permission = "tokens.manage" + MonitorsRead Permission = "monitors.read" + MonitorsWrite Permission = "monitors.write" + StatusPagesRead Permission = "statuspages.read" + StatusPagesWrite Permission = "statuspages.write" + IncidentsRead Permission = "incidents.read" + IncidentsWrite Permission = "incidents.write" + NotificationsRead Permission = "notifications.read" + NotificationsWrite Permission = "notifications.write" +) + +// All lists every permission in display order. +var All = []Permission{ + OrgManage, + MembersRead, MembersManage, RolesManage, TokensManage, + MonitorsRead, MonitorsWrite, + StatusPagesRead, StatusPagesWrite, + IncidentsRead, IncidentsWrite, + NotificationsRead, NotificationsWrite, +} + +var implies = map[Permission]Permission{ + MembersManage: MembersRead, + RolesManage: MembersRead, + MonitorsWrite: MonitorsRead, + StatusPagesWrite: StatusPagesRead, + IncidentsWrite: IncidentsRead, + NotificationsWrite: NotificationsRead, +} + +// Set is an unordered set of permissions. +type Set map[Permission]struct{} + +// NewSet returns a set of ps including the permissions they imply. Unknown +// strings are dropped, so a permission removed in a later release simply +// stops granting anything. +func NewSet[T ~string](ps ...T) Set { + s := Set{} + for _, p := range ps { + perm := Permission(p) + if !slices.Contains(All, perm) { + continue + } + s[perm] = struct{}{} + if r, ok := implies[perm]; ok { + s[r] = struct{}{} + } + } + return s +} + +// Has reports whether p is in s. +func (s Set) Has(p Permission) bool { + _, ok := s[p] + return ok +} + +// Covers reports whether every permission in other is also in s. +func (s Set) Covers(other Set) bool { + for p := range other { + if !s.Has(p) { + return false + } + } + return true +} + +// Union returns the permissions in either set. +func (s Set) Union(other Set) Set { + out := make(Set, len(s)+len(other)) + for p := range s { + out[p] = struct{}{} + } + for p := range other { + out[p] = struct{}{} + } + return out +} + +// Intersect returns the permissions in both sets. +func (s Set) Intersect(other Set) Set { + out := Set{} + for p := range s { + if other.Has(p) { + out[p] = struct{}{} + } + } + return out +} + +// Strings returns the permissions in the order of All. +func (s Set) Strings() []string { + out := make([]string, 0, len(s)) + for _, p := range All { + if s.Has(p) { + out = append(out, string(p)) + } + } + return out +} + +// ResourceType names what a scoped assignment applies to. +type ResourceType string + +// Resource types that assignments can be scoped to. +const ( + MonitorGroup ResourceType = "monitor_group" + StatusPage ResourceType = "status_page" +) + +// Resource identifies one scoped object. +type Resource struct { + Type ResourceType + ID uuid.UUID +} + +// Valid reports whether r names a known resource type. +func (r Resource) Valid() bool { + return (r.Type == MonitorGroup || r.Type == StatusPage) && r.ID != uuid.Nil +} + +// Grants are the effective permissions of one user in one organization. +type Grants struct { + Owner bool + Org Set + Scoped map[Resource]Set +} + +// Can reports whether the user holds p organization-wide or on any of rs. +func (g *Grants) Can(p Permission, rs ...Resource) bool { + if g.Owner || g.Org.Has(p) { + return true + } + for _, r := range rs { + if g.Scoped[r].Has(p) { + return true + } + } + return false +} + +// CanGrant reports whether the user may hand out perms, organization-wide +// when scope is nil or on that resource otherwise. Nobody can grant a +// permission they do not hold themselves, which keeps delegated +// administrators from escalating their own rights through a helper account. +func (g *Grants) CanGrant(perms Set, scope *Resource) bool { + if g.Owner { + return true + } + held := g.Org + if scope != nil { + held = held.Union(g.Scoped[*scope]) + } + return held.Covers(perms) +} + +// Restrict returns the grants limited to perms, as used for API tokens whose +// permissions must never exceed their owner's current ones. +func (g *Grants) Restrict(perms Set) *Grants { + out := &Grants{Org: perms.Intersect(g.all()), Scoped: map[Resource]Set{}} + if g.Owner { + out.Org = perms + } + for r, s := range g.Scoped { + out.Scoped[r] = s.Intersect(perms) + } + return out +} + +func (g *Grants) all() Set { + if g.Org == nil { + return Set{} + } + return g.Org +} diff --git a/internal/authz/authz_test.go b/internal/authz/authz_test.go new file mode 100644 index 0000000..927f5c9 --- /dev/null +++ b/internal/authz/authz_test.go @@ -0,0 +1,83 @@ +package authz + +import ( + "slices" + "testing" + + "github.com/google/uuid" +) + +func TestNewSetAddsImpliedAndDropsUnknown(t *testing.T) { + got := NewSet("monitors.write", "no.such", "members.manage").Strings() + want := []string{"members.read", "members.manage", "monitors.read", "monitors.write"} + if !slices.Equal(got, want) { + t.Errorf("NewSet(...).Strings() = %v, want %v", got, want) + } +} + +func TestCan(t *testing.T) { + page := Resource{Type: StatusPage, ID: uuid.New()} + other := Resource{Type: StatusPage, ID: uuid.New()} + g := &Grants{ + Org: NewSet(MonitorsRead), + Scoped: map[Resource]Set{page: NewSet(StatusPagesWrite)}, + } + tests := []struct { + name string + p Permission + rs []Resource + want bool + }{ + {"org-wide permission", MonitorsRead, nil, true}, + {"missing permission", MonitorsWrite, nil, false}, + {"scoped permission on its resource", StatusPagesWrite, []Resource{page}, true}, + {"scoped permission implies read", StatusPagesRead, []Resource{page}, true}, + {"scoped permission on other resource", StatusPagesWrite, []Resource{other}, false}, + {"scoped permission without resource", StatusPagesWrite, nil, false}, + } + for _, tt := range tests { + if got := g.Can(tt.p, tt.rs...); got != tt.want { + t.Errorf("%s: Can(%s, %v) = %t, want %t", tt.name, tt.p, tt.rs, got, tt.want) + } + } + if !(&Grants{Owner: true}).Can(OrgManage) { + t.Error("owner Can(org.manage) = false, want true") + } +} + +func TestCanGrant(t *testing.T) { + page := Resource{Type: StatusPage, ID: uuid.New()} + admin := &Grants{ + Org: NewSet(MembersManage, MonitorsWrite), + Scoped: map[Resource]Set{page: NewSet(StatusPagesWrite)}, + } + tests := []struct { + name string + perms Set + scope *Resource + want bool + }{ + {"subset org-wide", NewSet(MonitorsRead), nil, true}, + {"equal org-wide", NewSet(MembersManage, MonitorsWrite), nil, true}, + {"escalation org-wide", NewSet(OrgManage), nil, false}, + {"scoped right org-wide", NewSet(StatusPagesWrite), nil, false}, + {"scoped right on its resource", NewSet(StatusPagesWrite), &page, true}, + } + for _, tt := range tests { + if got := admin.CanGrant(tt.perms, tt.scope); got != tt.want { + t.Errorf("%s: CanGrant(%v) = %t, want %t", tt.name, tt.perms.Strings(), got, tt.want) + } + } +} + +func TestRestrict(t *testing.T) { + user := &Grants{Org: NewSet(MonitorsWrite)} + tok := user.Restrict(NewSet(MonitorsWrite, OrgManage)) + if !tok.Can(MonitorsWrite) || tok.Can(OrgManage) { + t.Errorf("Restrict() org = %v, want monitors only", tok.Org.Strings()) + } + owner := (&Grants{Owner: true}).Restrict(NewSet(MonitorsRead)) + if owner.Owner || !owner.Can(MonitorsRead) || owner.Can(MonitorsWrite) { + t.Errorf("owner Restrict() = %+v, want only monitors.read", owner) + } +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index c59d879..16a932c 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -10,6 +10,8 @@ import ( "sort" "strings" "testing" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" ) func catalogKeys(t *testing.T) map[string]map[string]bool { @@ -57,13 +59,19 @@ func TestCatalogsHaveSameKeys(t *testing.T) { var usagePatterns = []struct { re *regexp.Regexp prefix string + // dir limits the pattern to files below this directory. + dir string }{ - {regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`), ""}, - {regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), "error."}, - {regexp.MustCompile(`\b(?:pageFor\(c|s\.page\()(?:, )?"([a-z0-9_.]+)"`), ""}, - {regexp.MustCompile(`[^(]"(sso_[a-z_]+)"`), "error."}, - {regexp.MustCompile(`return "(invalid_[a-z_]+)"`), "error."}, - {regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`), ""}, + {re: regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`)}, + {re: regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), prefix: "error."}, + {re: regexp.MustCompile(`\b(?:pageFor\(c|s\.page\(|s\.orgPage\()(?:, )?"([a-z0-9_.]+)"`)}, + {re: regexp.MustCompile(`[^(]"(sso_[a-z_]+)"`), prefix: "error.", dir: "api"}, + {re: regexp.MustCompile(`return "(invalid_[a-z_]+)"`), prefix: "error."}, + {re: regexp.MustCompile(`code = "([a-z_]+)"`), prefix: "error."}, + {re: regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`)}, + {re: regexp.MustCompile(`@(?:settingsHeading|sectionHeading)\("([a-z0-9_.]+)"`)}, + {re: regexp.MustCompile(`@settingsHeading\("[a-z0-9_.]+", "([a-z0-9_.]+)"`)}, + {re: regexp.MustCompile(`@policyBanner\("([a-z0-9_.]+)", "([a-z0-9_.]+)"`)}, } // TestUsedKeysExist scans the source tree for literal message IDs so a typo @@ -86,9 +94,14 @@ func TestUsedKeysExist(t *testing.T) { return err } for _, u := range usagePatterns { + if u.dir != "" && !strings.Contains(filepath.ToSlash(p), "/"+u.dir+"/") { + continue + } for _, m := range u.re.FindAllStringSubmatch(string(src), -1) { - if id := u.prefix + m[1]; !en[id] { - missing = append(missing, p+": "+id) + for _, id := range m[1:] { + if id := u.prefix + id; !en[id] { + missing = append(missing, p+": "+id) + } } } } @@ -103,6 +116,22 @@ func TestUsedKeysExist(t *testing.T) { } } +// Permission and scope labels are looked up as "perm." and +// "scope.". +func TestEveryPermissionHasALabel(t *testing.T) { + en := catalogKeys(t)["en"] + for _, p := range authz.All { + if !en["perm."+string(p)] { + t.Errorf("en.json is missing %q", "perm."+string(p)) + } + } + for _, rt := range []authz.ResourceType{authz.MonitorGroup, authz.StatusPage} { + if !en["scope."+string(rt)] { + t.Errorf("en.json is missing %q", "scope."+string(rt)) + } + } +} + // The language switcher builds "lang." dynamically. func TestEveryLanguageHasAName(t *testing.T) { c, err := Load() @@ -154,6 +183,9 @@ func TestT(t *testing.T) { t.Errorf("T(de, recovery.left, %d) = %q, want %q", n, got, want) } } + if got, want := T(ctx, "error.token_lifetime_exceeds_policy", "Count", 30), "Tokens in dieser Organisation müssen innerhalb von 30 Tagen ablaufen."; got != want { + t.Errorf("T(de, token_lifetime_exceeds_policy, 30) = %q, want %q", got, want) + } if got, want := T(ctx, "no.such.key"), "no.such.key"; got != want { t.Errorf("T(missing) = %q, want %q", got, want) } diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index e0648c5..f610030 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -24,24 +24,43 @@ "console.monitors.empty": "Noch keine Monitore angelegt.", "console.monitors.title": "Monitore", "console.nav.logout": "Abmelden", + "console.nav.members": "Mitglieder", + "console.nav.org": "Organisation", + "console.nav.roles": "Rollen", "console.nav.security": "Sicherheit", "console.nav.sso": "SSO", - "console.totp_missing": "Deine Organisation verlangt Zwei-Faktor-Anmeldung.", + "console.nav.tokens": "API-Tokens", + "console.sso_required_action": "Mit SSO anmelden", "console.totp_missing_action": "Jetzt einrichten", + "error.already_assigned": "Das Mitglied hat diese Rolle bereits.", + "error.already_member": "Diese Person ist bereits Mitglied.", "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", "error.forbidden": "Dafür fehlt dir die Berechtigung.", "error.internal": "Interner Fehler.", "error.invalid_code": "Code ungültig.", "error.invalid_credentials": "E-Mail oder Passwort falsch.", "error.invalid_domain": "Eine der Domains ist ungültig.", + "error.invalid_email": "Bitte eine gültige E-Mail-Adresse eingeben.", "error.invalid_input": "Eingaben prüfen.", + "error.invalid_permissions": "Mindestens eine Berechtigung auswählen.", "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", + "error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.", + "error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.", "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", "error.no_password": "Konto ohne Passwort.", "error.not_found": "Nicht gefunden.", "error.org_not_found": "Organisation nicht gefunden.", + "error.owner_cannot_be_removed": "Der Owner kann nicht entfernt werden.", + "error.owner_has_all_permissions": "Der Owner hat bereits alle Berechtigungen.", "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", + "error.permission_escalation": "Du kannst keine Berechtigungen vergeben, die du selbst nicht hast.", + "error.policy_would_lock_you_out": "Deine aktuelle Anmeldung erfüllt diese Richtlinie nicht. Erfülle sie zuerst und aktiviere sie dann.", "error.rate_limited": "Zu viele Versuche, bitte später erneut.", + "error.role_built_in": "Eingebaute Rollen können nicht geändert werden.", + "error.role_in_use": "Die Rolle ist noch Mitgliedern zugewiesen.", + "error.role_name_taken": "Eine Rolle mit diesem Namen gibt es bereits.", + "error.role_not_found": "Rolle nicht gefunden.", + "error.session_required": "Diese Aktion ist für API-Tokens nicht verfügbar.", "error.signup_closed": "Registrierung ist deaktiviert.", "error.slug_taken": "Dieser Kurzname ist bereits vergeben.", "error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.", @@ -51,16 +70,72 @@ "error.sso_identity_taken": "Diese SSO-Anmeldung ist bereits mit einem anderen Konto verknüpft.", "error.sso_invalid_issuer": "Der Issuer muss eine https-URL ohne Query und Zugangsdaten sein.", "error.sso_link_required": "Es gibt bereits ein Konto mit dieser E-Mail. Melde dich mit Passwort an und verknüpfe SSO unter Sicherheit.", + "error.sso_no_provider": "Lege zuerst einen SSO-Provider an und aktiviere ihn.", "error.sso_not_member": "Dein Konto ist kein Mitglied dieser Organisation.", "error.sso_not_provisioned": "Für diese Anmeldung gibt es kein Konto. Bitte lass dich von einem Admin einladen.", "error.sso_provider_error": "Der Identity Provider konnte die Anmeldung nicht abschließen.", + "error.sso_required_by_org": "Diese Organisation verlangt die Anmeldung über ihren SSO-Provider.", "error.sso_unavailable": "Für diese Organisation ist kein Single Sign-on verfügbar.", + "error.token_lifetime_exceeds_policy": { + "one": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tag ablaufen.", + "other": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tagen ablaufen." + }, "error.totp_already_enabled": "TOTP ist bereits aktiv.", "error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.", "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", + "error.unauthenticated": "Anmeldung erforderlich.", "error.unsupported_locale": "Sprache wird nicht unterstützt.", + "invite.accept": "Einladung annehmen", + "invite.create_account": "Konto anlegen und beitreten", + "invite.sign_in": "Zum Annehmen anmelden", + "invite.summary": "Du bist eingeladen, {{.Org}} als {{.Role}} beizutreten.", + "invite.title": "Einladung", "lang.de": "Deutsch", "lang.en": "English", + "members.assign": "Rolle hinzufügen", + "members.intro": "Rollen bestimmen, was ein Mitglied darf. Niemand kann Berechtigungen vergeben, die er selbst nicht hat.", + "members.invite": "Einladen", + "members.invite_link": "Schicke diesen Link an die eingeladene Person. Er gilt 7 Tage und funktioniert einmal.", + "members.invite_submit": "Einladung erstellen", + "members.owner": "Owner", + "members.pending": "Offene Einladungen", + "members.remove": "Aus der Organisation entfernen", + "members.remove_confirm": "Dieses Mitglied entfernen? Seine Sessions und API-Tokens enden sofort.", + "members.revoke": "Widerrufen", + "members.role": "Rolle", + "members.roles": "Rollen", + "members.title": "Mitglieder", + "members.unassign": "Rolle entfernen", + "org.policy": "Anmelderichtlinie", + "org.require_sso": "SSO verlangen", + "org.require_sso_hint": "Mitglieder müssen sich über den Identity Provider dieser Organisation anmelden. Der Owner kann weiterhin ein Passwort nutzen, damit ein defekter IdP euch nicht aussperrt.", + "org.require_totp": "Zwei-Faktor-Anmeldung verlangen", + "org.require_totp_hint": "Mitglieder, die sich mit Passwort anmelden, brauchen TOTP. Bei SSO-Anmeldungen ist die MFA des Identity Providers zuständig.", + "org.title": "Organisation", + "org.token_max_days": "Maximale Gültigkeit von API-Tokens (Tage)", + "org.token_max_days_hint": "Neue Tokens müssen innerhalb dieses Zeitraums ablaufen. Beim Speichern werden bestehende Tokens gekürzt, die länger gelten würden. Leer lassen für keine Begrenzung.", + "org.token_max_days_none": "unbegrenzt", + "perm.incidents.read": "Incidents sehen", + "perm.incidents.write": "Incidents verwalten", + "perm.members.manage": "Mitglieder einladen und verwalten", + "perm.members.read": "Mitglieder und Rollen sehen", + "perm.monitors.read": "Monitore sehen", + "perm.monitors.write": "Monitore bearbeiten", + "perm.notifications.read": "Benachrichtigungskanäle sehen", + "perm.notifications.write": "Benachrichtigungskanäle bearbeiten", + "perm.org.manage": "Organisation und SSO verwalten", + "perm.roles.manage": "Eigene Rollen verwalten", + "perm.statuspages.read": "Statuspages sehen", + "perm.statuspages.write": "Statuspages bearbeiten", + "perm.tokens.manage": "Alle API-Tokens sehen und widerrufen", + "roles.built_in": "eingebaut", + "roles.create": "Rolle anlegen", + "roles.delete": "Rolle löschen", + "roles.delete_confirm": "Diese Rolle löschen?", + "roles.intro": "Eingebaute Rollen decken die üblichen Fälle ab. Eigene Rollen kombinieren einzelne Berechtigungen.", + "roles.title": "Rollen", + "scope.monitor_group": "Monitor-Gruppe", + "scope.status_page": "Statuspage", "security.recovery.left": { "one": "{{.Count}} Wiederherstellungscode übrig", "other": "{{.Count}} Wiederherstellungscodes übrig" @@ -92,6 +167,8 @@ "sso.field.client_id": "Client-ID", "sso.field.client_secret": "Client-Secret", "sso.field.client_secret_keep": "unverändert", + "sso.field.default_role": "Rolle für neue Konten", + "sso.field.default_role_viewer": "Viewer (Standard)", "sso.field.enabled": "Aktiv", "sso.field.issuer": "Issuer-URL", "sso.field.name": "Name", @@ -99,5 +176,25 @@ "sso.settings.intro": "Mitglieder dieser Organisation können sich über euren eigenen OpenID-Connect-Identity-Provider anmelden. Tragt die Redirect-URL unten bei eurem Provider als erlaubten Callback ein.", "sso.settings.login_url": "Anmelde-URL", "sso.settings.redirect_url": "Redirect-URL", - "sso.settings.title": "Single Sign-on" + "sso.settings.title": "Single Sign-on", + "tokens.copy_now": "Kopiere den Token jetzt. Er wird nicht erneut angezeigt.", + "tokens.create": "Token erstellen", + "tokens.created": "Erstellt", + "tokens.days": { + "one": "{{.Count}} Tag", + "other": "{{.Count}} Tage" + }, + "tokens.expires": "Läuft ab", + "tokens.intro": "Tokens handeln in deinem Namen in dieser Organisation. Sie haben nie mehr Rechte als du selbst, auch wenn deine Rechte später schrumpfen.", + "tokens.intro_all": "Du siehst alle API-Tokens dieser Organisation und kannst jeden davon widerrufen. Tokens haben nie mehr Rechte als ihr Inhaber.", + "tokens.last_used": "Zuletzt genutzt", + "tokens.never": "nie", + "tokens.owner": "Inhaber", + "tokens.permissions": "Berechtigungen", + "tokens.policy": { + "one": "Diese Organisation begrenzt API-Tokens auf {{.Count}} Tag.", + "other": "Diese Organisation begrenzt API-Tokens auf {{.Count}} Tage." + }, + "tokens.revoke_confirm": "Diesen Token widerrufen? Anfragen damit schlagen sofort fehl.", + "tokens.title": "API-Tokens" } diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 9ca4d53..19b7654 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -24,24 +24,43 @@ "console.monitors.empty": "No monitors yet.", "console.monitors.title": "Monitors", "console.nav.logout": "Sign out", + "console.nav.members": "Members", + "console.nav.org": "Organization", + "console.nav.roles": "Roles", "console.nav.security": "Security", "console.nav.sso": "SSO", - "console.totp_missing": "Your organization requires two-factor sign-in.", + "console.nav.tokens": "API tokens", + "console.sso_required_action": "Sign in with SSO", "console.totp_missing_action": "Set up now", + "error.already_assigned": "The member already has this role.", + "error.already_member": "This person is already a member.", "error.email_taken": "This email address is already registered.", "error.forbidden": "You are not allowed to do this.", "error.internal": "Internal error.", "error.invalid_code": "Invalid code.", "error.invalid_credentials": "Wrong email or password.", "error.invalid_domain": "One of the domains is not valid.", + "error.invalid_email": "Please enter a valid email address.", "error.invalid_input": "Please check your input.", + "error.invalid_permissions": "Choose at least one permission.", "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", + "error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.", + "error.invitation_invalid": "This invitation is invalid, expired or was already used.", "error.mfa_expired": "Sign-in expired, please start again.", "error.no_password": "This account has no password.", "error.not_found": "Not found.", "error.org_not_found": "Organization not found.", + "error.owner_cannot_be_removed": "The owner cannot be removed.", + "error.owner_has_all_permissions": "The owner already has every permission.", "error.password_too_short": "The password needs at least {{.Min}} characters.", + "error.permission_escalation": "You cannot grant permissions you do not hold yourself.", + "error.policy_would_lock_you_out": "Your current sign-in does not meet this policy. Meet it first, then turn it on.", "error.rate_limited": "Too many attempts, please try again later.", + "error.role_built_in": "Built-in roles cannot be changed.", + "error.role_in_use": "The role is still assigned to members.", + "error.role_name_taken": "A role with this name already exists.", + "error.role_not_found": "Role not found.", + "error.session_required": "This action is not available to API tokens.", "error.signup_closed": "Sign-up is disabled.", "error.slug_taken": "This short name is already taken.", "error.sso_denied": "Sign-in was cancelled at the identity provider.", @@ -51,16 +70,72 @@ "error.sso_identity_taken": "This SSO sign-in is already linked to another account.", "error.sso_invalid_issuer": "The issuer must be an https URL without query or credentials.", "error.sso_link_required": "An account with this email already exists. Sign in with your password and link SSO under Security.", + "error.sso_no_provider": "Add and enable an SSO provider first.", "error.sso_not_member": "Your account is not a member of this organization.", "error.sso_not_provisioned": "No account exists for this sign-in. Ask an administrator to invite you.", "error.sso_provider_error": "The identity provider could not complete the sign-in.", + "error.sso_required_by_org": "This organization requires signing in through its SSO provider.", "error.sso_unavailable": "Single sign-on is not available for this organization.", + "error.token_lifetime_exceeds_policy": { + "one": "Tokens in this organization must expire within {{.Count}} day.", + "other": "Tokens in this organization must expire within {{.Count}} days." + }, "error.totp_already_enabled": "TOTP is already active.", "error.totp_required_by_org": "One of your organizations requires TOTP.", "error.totp_setup_expired": "Setup expired, please start again.", + "error.unauthenticated": "Authentication required.", "error.unsupported_locale": "Unsupported language.", + "invite.accept": "Accept invitation", + "invite.create_account": "Create account and join", + "invite.sign_in": "Sign in to accept", + "invite.summary": "You are invited to join {{.Org}} as {{.Role}}.", + "invite.title": "Invitation", "lang.de": "Deutsch", "lang.en": "English", + "members.assign": "Add role", + "members.intro": "Roles decide what each member may do. Nobody can grant permissions they do not hold themselves.", + "members.invite": "Invite", + "members.invite_link": "Send this link to the invitee. It is valid for 7 days and works once.", + "members.invite_submit": "Create invitation", + "members.owner": "Owner", + "members.pending": "Pending invitations", + "members.remove": "Remove from organization", + "members.remove_confirm": "Remove this member? Their sessions and API tokens end immediately.", + "members.revoke": "Revoke", + "members.role": "Role", + "members.roles": "Roles", + "members.title": "Members", + "members.unassign": "Remove role", + "org.policy": "Sign-in policy", + "org.require_sso": "Require SSO", + "org.require_sso_hint": "Members must sign in through this organization's identity provider. The owner can still use a password so a broken IdP cannot lock you out.", + "org.require_totp": "Require two-factor sign-in", + "org.require_totp_hint": "Members signing in with a password need TOTP. SSO sign-ins rely on the identity provider's MFA.", + "org.title": "Organization", + "org.token_max_days": "Maximum API token lifetime (days)", + "org.token_max_days_hint": "New tokens must expire within this period. Saving shortens existing tokens that would outlive it. Leave empty for no limit.", + "org.token_max_days_none": "unlimited", + "perm.incidents.read": "View incidents", + "perm.incidents.write": "Manage incidents", + "perm.members.manage": "Invite and manage members", + "perm.members.read": "View members and roles", + "perm.monitors.read": "View monitors", + "perm.monitors.write": "Edit monitors", + "perm.notifications.read": "View notification channels", + "perm.notifications.write": "Edit notification channels", + "perm.org.manage": "Manage organization and SSO", + "perm.roles.manage": "Manage custom roles", + "perm.statuspages.read": "View status pages", + "perm.statuspages.write": "Edit status pages", + "perm.tokens.manage": "View and revoke all API tokens", + "roles.built_in": "built-in", + "roles.create": "Create role", + "roles.delete": "Delete role", + "roles.delete_confirm": "Delete this role?", + "roles.intro": "Built-in roles cover common cases. Custom roles combine individual permissions.", + "roles.title": "Roles", + "scope.monitor_group": "monitor group", + "scope.status_page": "status page", "security.recovery.left": { "one": "{{.Count}} recovery code left", "other": "{{.Count}} recovery codes left" @@ -92,6 +167,8 @@ "sso.field.client_id": "Client ID", "sso.field.client_secret": "Client secret", "sso.field.client_secret_keep": "unchanged", + "sso.field.default_role": "Role for new accounts", + "sso.field.default_role_viewer": "Viewer (default)", "sso.field.enabled": "Enabled", "sso.field.issuer": "Issuer URL", "sso.field.name": "Name", @@ -99,5 +176,25 @@ "sso.settings.intro": "Members of this organization can sign in through your own OpenID Connect identity provider. Register the redirect URL below as an allowed callback at your provider.", "sso.settings.login_url": "Sign-in URL", "sso.settings.redirect_url": "Redirect URL", - "sso.settings.title": "Single sign-on" + "sso.settings.title": "Single sign-on", + "tokens.copy_now": "Copy the token now. It will not be shown again.", + "tokens.create": "Create token", + "tokens.created": "Created", + "tokens.days": { + "one": "{{.Count}} day", + "other": "{{.Count}} days" + }, + "tokens.expires": "Expires", + "tokens.intro": "Tokens act on your behalf in this organization. They never exceed your own permissions, even if those shrink later.", + "tokens.intro_all": "You see every API token in this organization and can revoke any of them. Tokens never exceed their owner's permissions.", + "tokens.last_used": "Last used", + "tokens.never": "never", + "tokens.owner": "Owner", + "tokens.permissions": "Permissions", + "tokens.policy": { + "one": "This organization limits API tokens to {{.Count}} day.", + "other": "This organization limits API tokens to {{.Count}} days." + }, + "tokens.revoke_confirm": "Revoke this token? Requests using it fail immediately.", + "tokens.title": "API tokens" } diff --git a/internal/migrations/sql/00009_roles.sql b/internal/migrations/sql/00009_roles.sql new file mode 100644 index 0000000..e29508b --- /dev/null +++ b/internal/migrations/sql/00009_roles.sql @@ -0,0 +1,66 @@ +-- +goose Up +-- Built-in roles have org_id NULL and fixed ids; they are visible to every +-- org but writable by none. Custom roles belong to one org. +CREATE TABLE roles ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid REFERENCES orgs (id) ON DELETE CASCADE, + key text UNIQUE, + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + permissions text[] NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + CHECK ((org_id IS NULL) = (key IS NOT NULL)), + UNIQUE NULLS NOT DISTINCT (org_id, name) +); + +INSERT INTO roles (id, key, name, permissions) VALUES + ('00000000-0000-0000-0000-00000000a001', 'admin', 'Admin', + '{org.manage,members.manage,roles.manage,monitors.write,statuspages.write,incidents.write,notifications.write}'), + ('00000000-0000-0000-0000-00000000a002', 'editor', 'Editor', + '{members.read,monitors.write,statuspages.write,incidents.write,notifications.write}'), + ('00000000-0000-0000-0000-00000000a003', 'viewer', 'Viewer', + '{members.read,monitors.read,statuspages.read,incidents.read,notifications.read}'); + +-- A deleted role must not silently strip people of access, so assignments +-- block deletion. Removing a membership removes its assignments. +CREATE TABLE role_assignments ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL, + user_id uuid NOT NULL, + role_id uuid NOT NULL REFERENCES roles (id) ON DELETE RESTRICT, + resource_type text CHECK (resource_type IN ('monitor_group', 'status_page')), + resource_id uuid, + created_at timestamptz NOT NULL DEFAULT now(), + FOREIGN KEY (org_id, user_id) REFERENCES memberships (org_id, user_id) ON DELETE CASCADE, + CHECK ((resource_type IS NULL) = (resource_id IS NULL)), + UNIQUE NULLS NOT DISTINCT (org_id, user_id, role_id, resource_type, resource_id) +); + +CREATE INDEX role_assignments_member_idx ON role_assignments (org_id, user_id); +CREATE INDEX role_assignments_role_idx ON role_assignments (role_id); + +INSERT INTO role_assignments (org_id, user_id, role_id) +SELECT org_id, user_id, '00000000-0000-0000-0000-00000000a003' FROM memberships WHERE NOT is_owner; + +ALTER TABLE orgs ADD COLUMN require_sso boolean NOT NULL DEFAULT false; +ALTER TABLE sso_providers ADD COLUMN default_role_id uuid REFERENCES roles (id) ON DELETE SET NULL; + +ALTER TABLE roles ENABLE ROW LEVEL SECURITY; +ALTER TABLE roles FORCE ROW LEVEL SECURITY; +CREATE POLICY roles_read ON roles FOR SELECT + USING (org_id IS NULL OR app_scope_system() OR org_id = app_org_id()); +CREATE POLICY roles_write ON roles FOR ALL + USING (org_id IS NOT NULL AND (app_scope_system() OR org_id = app_org_id())) + WITH CHECK (org_id IS NOT NULL AND (app_scope_system() OR org_id = app_org_id())); + +ALTER TABLE role_assignments ENABLE ROW LEVEL SECURITY; +ALTER TABLE role_assignments FORCE ROW LEVEL SECURITY; +CREATE POLICY role_assignments_tenant ON role_assignments FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- +goose Down +ALTER TABLE sso_providers DROP COLUMN default_role_id; +ALTER TABLE orgs DROP COLUMN require_sso; +DROP TABLE role_assignments; +DROP TABLE roles; diff --git a/internal/migrations/sql/00010_api_tokens.sql b/internal/migrations/sql/00010_api_tokens.sql new file mode 100644 index 0000000..bc6ff74 --- /dev/null +++ b/internal/migrations/sql/00010_api_tokens.sql @@ -0,0 +1,46 @@ +-- +goose Up +CREATE TABLE api_tokens ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL, + user_id uuid NOT NULL, + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + token_hash bytea NOT NULL UNIQUE, + -- First characters of the token, shown so users can tell tokens apart. + prefix text NOT NULL, + permissions text[] NOT NULL, + expires_at timestamptz, + last_used_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + -- Leaving the org revokes the member's tokens. + FOREIGN KEY (org_id, user_id) REFERENCES memberships (org_id, user_id) ON DELETE CASCADE +); + +CREATE INDEX api_tokens_member_idx ON api_tokens (org_id, user_id); + +ALTER TABLE api_tokens ENABLE ROW LEVEL SECURITY; +ALTER TABLE api_tokens FORCE ROW LEVEL SECURITY; +CREATE POLICY api_tokens_tenant ON api_tokens FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- Requests carry only the token, so its org is unknown until it is found. +-- Like org_id_by_slug, the system scope is raised for this single lookup by +-- hash, which cannot enumerate other tokens. +-- +goose StatementBegin +CREATE FUNCTION api_token_org(hash bytea) RETURNS uuid +LANGUAGE plpgsql VOLATILE AS $$ +DECLARE + prev text := coalesce(current_setting('app.scope', true), ''); + result uuid; +BEGIN + PERFORM set_config('app.scope', 'system', true); + SELECT org_id INTO result FROM api_tokens WHERE token_hash = hash; + PERFORM set_config('app.scope', prev, true); + RETURN result; +END +$$; +-- +goose StatementEnd + +-- +goose Down +DROP FUNCTION api_token_org(bytea); +DROP TABLE api_tokens; diff --git a/internal/migrations/sql/00011_invitations.sql b/internal/migrations/sql/00011_invitations.sql new file mode 100644 index 0000000..d554134 --- /dev/null +++ b/internal/migrations/sql/00011_invitations.sql @@ -0,0 +1,40 @@ +-- +goose Up +CREATE TABLE invitations ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + email citext NOT NULL, + role_id uuid NOT NULL REFERENCES roles (id) ON DELETE CASCADE, + token_hash bytea NOT NULL UNIQUE, + invited_by uuid REFERENCES users (id) ON DELETE SET NULL, + expires_at timestamptz NOT NULL, + accepted_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX invitations_org_idx ON invitations (org_id); + +ALTER TABLE invitations ENABLE ROW LEVEL SECURITY; +ALTER TABLE invitations FORCE ROW LEVEL SECURITY; +CREATE POLICY invitations_tenant ON invitations FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- Invitees are not members yet; see api_token_org for the pattern. +-- +goose StatementBegin +CREATE FUNCTION invitation_org(hash bytea) RETURNS uuid +LANGUAGE plpgsql VOLATILE AS $$ +DECLARE + prev text := coalesce(current_setting('app.scope', true), ''); + result uuid; +BEGIN + PERFORM set_config('app.scope', 'system', true); + SELECT org_id INTO result FROM invitations WHERE token_hash = hash; + PERFORM set_config('app.scope', prev, true); + RETURN result; +END +$$; +-- +goose StatementEnd + +-- +goose Down +DROP FUNCTION invitation_org(bytea); +DROP TABLE invitations; diff --git a/internal/migrations/sql/00012_token_policy.sql b/internal/migrations/sql/00012_token_policy.sql new file mode 100644 index 0000000..eeffb9e --- /dev/null +++ b/internal/migrations/sql/00012_token_policy.sql @@ -0,0 +1,9 @@ +-- +goose Up +ALTER TABLE orgs ADD COLUMN api_token_max_days integer CHECK (api_token_max_days BETWEEN 1 AND 3650); + +UPDATE roles SET permissions = array_append(permissions, 'tokens.manage') +WHERE key = 'admin' AND NOT 'tokens.manage' = ANY (permissions); + +-- +goose Down +UPDATE roles SET permissions = array_remove(permissions, 'tokens.manage') WHERE key = 'admin'; +ALTER TABLE orgs DROP COLUMN api_token_max_days; diff --git a/internal/store/api_tokens.sql.go b/internal/store/api_tokens.sql.go new file mode 100644 index 0000000..a5259c4 --- /dev/null +++ b/internal/store/api_tokens.sql.go @@ -0,0 +1,211 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: api_tokens.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const aPITokenOrg = `-- name: APITokenOrg :one +SELECT coalesce(api_token_org($1::bytea), '00000000-0000-0000-0000-000000000000')::uuid AS org_id +` + +func (q *Queries) APITokenOrg(ctx context.Context, hash []byte) (uuid.UUID, error) { + row := q.db.QueryRow(ctx, aPITokenOrg, hash) + var org_id uuid.UUID + err := row.Scan(&org_id) + return org_id, err +} + +const clampAPITokenExpiry = `-- name: ClampAPITokenExpiry :execrows +UPDATE api_tokens SET expires_at = now() + make_interval(days => $1::int) +WHERE org_id = $2 + AND (expires_at IS NULL OR expires_at > now() + make_interval(days => $1::int)) +` + +type ClampAPITokenExpiryParams struct { + MaxDays int32 + OrgID uuid.UUID +} + +// Shortens tokens that would outlive a newly set maximum lifetime. +func (q *Queries) ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error) { + result, err := q.db.Exec(ctx, clampAPITokenExpiry, arg.MaxDays, arg.OrgID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const createAPIToken = `-- name: CreateAPIToken :one +INSERT INTO api_tokens (org_id, user_id, name, token_hash, prefix, permissions, expires_at) +VALUES ($1, $2, $3, $4, $5, $6, $7) +RETURNING id, org_id, user_id, name, token_hash, prefix, permissions, expires_at, last_used_at, created_at +` + +type CreateAPITokenParams struct { + OrgID uuid.UUID + UserID uuid.UUID + Name string + TokenHash []byte + Prefix string + Permissions []string + ExpiresAt *time.Time +} + +func (q *Queries) CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error) { + row := q.db.QueryRow(ctx, createAPIToken, + arg.OrgID, + arg.UserID, + arg.Name, + arg.TokenHash, + arg.Prefix, + arg.Permissions, + arg.ExpiresAt, + ) + var i ApiToken + err := row.Scan( + &i.ID, + &i.OrgID, + &i.UserID, + &i.Name, + &i.TokenHash, + &i.Prefix, + &i.Permissions, + &i.ExpiresAt, + &i.LastUsedAt, + &i.CreatedAt, + ) + return i, err +} + +const deleteAPIToken = `-- name: DeleteAPIToken :execrows +DELETE FROM api_tokens WHERE id = $1 +` + +func (q *Queries) DeleteAPIToken(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteAPIToken, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getAPIToken = `-- name: GetAPIToken :one +SELECT id, org_id, user_id, name, token_hash, prefix, permissions, expires_at, last_used_at, created_at FROM api_tokens WHERE id = $1 +` + +func (q *Queries) GetAPIToken(ctx context.Context, id uuid.UUID) (ApiToken, error) { + row := q.db.QueryRow(ctx, getAPIToken, id) + var i ApiToken + err := row.Scan( + &i.ID, + &i.OrgID, + &i.UserID, + &i.Name, + &i.TokenHash, + &i.Prefix, + &i.Permissions, + &i.ExpiresAt, + &i.LastUsedAt, + &i.CreatedAt, + ) + return i, err +} + +const getAPITokenByHash = `-- name: GetAPITokenByHash :one +SELECT id, org_id, user_id, name, token_hash, prefix, permissions, expires_at, last_used_at, created_at FROM api_tokens WHERE token_hash = $1 +` + +func (q *Queries) GetAPITokenByHash(ctx context.Context, tokenHash []byte) (ApiToken, error) { + row := q.db.QueryRow(ctx, getAPITokenByHash, tokenHash) + var i ApiToken + err := row.Scan( + &i.ID, + &i.OrgID, + &i.UserID, + &i.Name, + &i.TokenHash, + &i.Prefix, + &i.Permissions, + &i.ExpiresAt, + &i.LastUsedAt, + &i.CreatedAt, + ) + return i, err +} + +const listAPITokens = `-- name: ListAPITokens :many +SELECT t.id, t.org_id, t.user_id, t.name, t.token_hash, t.prefix, t.permissions, t.expires_at, t.last_used_at, t.created_at, u.email AS user_email +FROM api_tokens t +JOIN users u ON u.id = t.user_id +WHERE t.org_id = $1 AND ($2::uuid IS NULL OR t.user_id = $2) +ORDER BY t.created_at DESC +` + +type ListAPITokensParams struct { + OrgID uuid.UUID + UserID *uuid.UUID +} + +type ListAPITokensRow struct { + ID uuid.UUID + OrgID uuid.UUID + UserID uuid.UUID + Name string + TokenHash []byte + Prefix string + Permissions []string + ExpiresAt *time.Time + LastUsedAt *time.Time + CreatedAt time.Time + UserEmail string +} + +func (q *Queries) ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error) { + rows, err := q.db.Query(ctx, listAPITokens, arg.OrgID, arg.UserID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListAPITokensRow{} + for rows.Next() { + var i ListAPITokensRow + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.UserID, + &i.Name, + &i.TokenHash, + &i.Prefix, + &i.Permissions, + &i.ExpiresAt, + &i.LastUsedAt, + &i.CreatedAt, + &i.UserEmail, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const touchAPIToken = `-- name: TouchAPIToken :exec +UPDATE api_tokens SET last_used_at = now() +WHERE id = $1 AND (last_used_at IS NULL OR last_used_at < now() - interval '1 minute') +` + +func (q *Queries) TouchAPIToken(ctx context.Context, id uuid.UUID) error { + _, err := q.db.Exec(ctx, touchAPIToken, id) + return err +} diff --git a/internal/store/invitations.sql.go b/internal/store/invitations.sql.go new file mode 100644 index 0000000..7eb6dc9 --- /dev/null +++ b/internal/store/invitations.sql.go @@ -0,0 +1,194 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: invitations.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createInvitation = `-- name: CreateInvitation :one +INSERT INTO invitations (org_id, email, role_id, token_hash, invited_by, expires_at) +VALUES ($1, $2, $3, $4, $5, $6) +RETURNING id, org_id, email, role_id, token_hash, invited_by, expires_at, accepted_at, created_at +` + +type CreateInvitationParams struct { + OrgID uuid.UUID + Email string + RoleID uuid.UUID + TokenHash []byte + InvitedBy *uuid.UUID + ExpiresAt time.Time +} + +func (q *Queries) CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error) { + row := q.db.QueryRow(ctx, createInvitation, + arg.OrgID, + arg.Email, + arg.RoleID, + arg.TokenHash, + arg.InvitedBy, + arg.ExpiresAt, + ) + var i Invitation + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Email, + &i.RoleID, + &i.TokenHash, + &i.InvitedBy, + &i.ExpiresAt, + &i.AcceptedAt, + &i.CreatedAt, + ) + return i, err +} + +const deleteInvitation = `-- name: DeleteInvitation :execrows +DELETE FROM invitations WHERE id = $1 +` + +func (q *Queries) DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteInvitation, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getInvitation = `-- name: GetInvitation :one +SELECT id, org_id, email, role_id, token_hash, invited_by, expires_at, accepted_at, created_at FROM invitations WHERE id = $1 +` + +func (q *Queries) GetInvitation(ctx context.Context, id uuid.UUID) (Invitation, error) { + row := q.db.QueryRow(ctx, getInvitation, id) + var i Invitation + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Email, + &i.RoleID, + &i.TokenHash, + &i.InvitedBy, + &i.ExpiresAt, + &i.AcceptedAt, + &i.CreatedAt, + ) + return i, err +} + +const getInvitationByHash = `-- name: GetInvitationByHash :one +SELECT i.id, i.org_id, i.email, i.role_id, i.token_hash, i.invited_by, i.expires_at, i.accepted_at, i.created_at, r.name AS role_name, o.name AS org_name, o.slug AS org_slug +FROM invitations i +JOIN roles r ON r.id = i.role_id +JOIN orgs o ON o.id = i.org_id +WHERE i.token_hash = $1 +` + +type GetInvitationByHashRow struct { + ID uuid.UUID + OrgID uuid.UUID + Email string + RoleID uuid.UUID + TokenHash []byte + InvitedBy *uuid.UUID + ExpiresAt time.Time + AcceptedAt *time.Time + CreatedAt time.Time + RoleName string + OrgName string + OrgSlug string +} + +func (q *Queries) GetInvitationByHash(ctx context.Context, tokenHash []byte) (GetInvitationByHashRow, error) { + row := q.db.QueryRow(ctx, getInvitationByHash, tokenHash) + var i GetInvitationByHashRow + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Email, + &i.RoleID, + &i.TokenHash, + &i.InvitedBy, + &i.ExpiresAt, + &i.AcceptedAt, + &i.CreatedAt, + &i.RoleName, + &i.OrgName, + &i.OrgSlug, + ) + return i, err +} + +const invitationOrg = `-- name: InvitationOrg :one +SELECT coalesce(invitation_org($1::bytea), '00000000-0000-0000-0000-000000000000')::uuid AS org_id +` + +func (q *Queries) InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error) { + row := q.db.QueryRow(ctx, invitationOrg, hash) + var org_id uuid.UUID + err := row.Scan(&org_id) + return org_id, err +} + +const listPendingInvitations = `-- name: ListPendingInvitations :many +SELECT i.id, i.email, i.expires_at, i.created_at, r.name AS role_name +FROM invitations i +JOIN roles r ON r.id = i.role_id +WHERE i.accepted_at IS NULL AND i.expires_at > now() +ORDER BY i.created_at DESC +` + +type ListPendingInvitationsRow struct { + ID uuid.UUID + Email string + ExpiresAt time.Time + CreatedAt time.Time + RoleName string +} + +func (q *Queries) ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error) { + rows, err := q.db.Query(ctx, listPendingInvitations) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListPendingInvitationsRow{} + for rows.Next() { + var i ListPendingInvitationsRow + if err := rows.Scan( + &i.ID, + &i.Email, + &i.ExpiresAt, + &i.CreatedAt, + &i.RoleName, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const markInvitationAccepted = `-- name: MarkInvitationAccepted :execrows +UPDATE invitations SET accepted_at = now() +WHERE id = $1 AND accepted_at IS NULL AND expires_at > now() +` + +func (q *Queries) MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, markInvitationAccepted, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/internal/store/models.go b/internal/store/models.go index c4adace..1afa83b 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -10,6 +10,31 @@ import ( "github.com/google/uuid" ) +type ApiToken struct { + ID uuid.UUID + OrgID uuid.UUID + UserID uuid.UUID + Name string + TokenHash []byte + Prefix string + Permissions []string + ExpiresAt *time.Time + LastUsedAt *time.Time + CreatedAt time.Time +} + +type Invitation struct { + ID uuid.UUID + OrgID uuid.UUID + Email string + RoleID uuid.UUID + TokenHash []byte + InvitedBy *uuid.UUID + ExpiresAt time.Time + AcceptedAt *time.Time + CreatedAt time.Time +} + type Membership struct { OrgID uuid.UUID UserID uuid.UUID @@ -18,12 +43,14 @@ type Membership struct { } type Org struct { - ID uuid.UUID - Slug string - Name string - CreatedAt time.Time - UpdatedAt time.Time - RequireTotp bool + ID uuid.UUID + Slug string + Name string + CreatedAt time.Time + UpdatedAt time.Time + RequireTotp bool + RequireSso bool + ApiTokenMaxDays *int32 } type RecoveryCode struct { @@ -33,6 +60,26 @@ type RecoveryCode struct { CreatedAt time.Time } +type Role struct { + ID uuid.UUID + OrgID *uuid.UUID + Key *string + Name string + Permissions []string + CreatedAt time.Time + UpdatedAt time.Time +} + +type RoleAssignment struct { + ID uuid.UUID + OrgID uuid.UUID + UserID uuid.UUID + RoleID uuid.UUID + ResourceType *string + ResourceID *uuid.UUID + CreatedAt time.Time +} + type SsoProvider struct { ID uuid.UUID OrgID uuid.UUID @@ -46,6 +93,7 @@ type SsoProvider struct { Enabled bool CreatedAt time.Time UpdatedAt time.Time + DefaultRoleID *uuid.UUID } type User struct { diff --git a/internal/store/orgs.sql.go b/internal/store/orgs.sql.go index 168fef1..795e915 100644 --- a/internal/store/orgs.sql.go +++ b/internal/store/orgs.sql.go @@ -13,7 +13,7 @@ import ( const createOrg = `-- name: CreateOrg :one INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3) -RETURNING id, slug, name, created_at, updated_at, require_totp +RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days ` type CreateOrgParams struct { @@ -32,6 +32,8 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro &i.CreatedAt, &i.UpdatedAt, &i.RequireTotp, + &i.RequireSso, + &i.ApiTokenMaxDays, ) return i, err } @@ -49,7 +51,7 @@ func (q *Queries) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) { } const getOrg = `-- name: GetOrg :one -SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs WHERE id = $1 +SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days FROM orgs WHERE id = $1 ` func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) { @@ -62,12 +64,14 @@ func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) { &i.CreatedAt, &i.UpdatedAt, &i.RequireTotp, + &i.RequireSso, + &i.ApiTokenMaxDays, ) return i, err } const getOrgBySlug = `-- name: GetOrgBySlug :one -SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs WHERE slug = $1 +SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days FROM orgs WHERE slug = $1 ` func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) { @@ -80,12 +84,14 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) { &i.CreatedAt, &i.UpdatedAt, &i.RequireTotp, + &i.RequireSso, + &i.ApiTokenMaxDays, ) return i, err } const listOrgs = `-- name: ListOrgs :many -SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs ORDER BY name +SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days FROM orgs ORDER BY name ` func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { @@ -104,6 +110,8 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { &i.CreatedAt, &i.UpdatedAt, &i.RequireTotp, + &i.RequireSso, + &i.ApiTokenMaxDays, ); err != nil { return nil, err } @@ -114,3 +122,37 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { } return items, nil } + +const updateOrgPolicy = `-- name: UpdateOrgPolicy :one +UPDATE orgs SET require_totp = $2, require_sso = $3, api_token_max_days = $4, updated_at = now() +WHERE id = $1 +RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days +` + +type UpdateOrgPolicyParams struct { + ID uuid.UUID + RequireTotp bool + RequireSso bool + ApiTokenMaxDays *int32 +} + +func (q *Queries) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error) { + row := q.db.QueryRow(ctx, updateOrgPolicy, + arg.ID, + arg.RequireTotp, + arg.RequireSso, + arg.ApiTokenMaxDays, + ) + var i Org + err := row.Scan( + &i.ID, + &i.Slug, + &i.Name, + &i.CreatedAt, + &i.UpdatedAt, + &i.RequireTotp, + &i.RequireSso, + &i.ApiTokenMaxDays, + ) + return i, err +} diff --git a/internal/store/querier.go b/internal/store/querier.go index 267932a..b88cd25 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -11,39 +11,68 @@ import ( ) type Querier interface { + APITokenOrg(ctx context.Context, hash []byte) (uuid.UUID, error) AddMembership(ctx context.Context, arg AddMembershipParams) error AnyUserExists(ctx context.Context) (bool, error) + // Shortens tokens that would outlive a newly set maximum lifetime. + ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error) + CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error) CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) + CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error) + CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (RoleAssignment, error) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error + CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) + CreateRole(ctx context.Context, arg CreateRoleParams) (Role, error) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) + DeleteAPIToken(ctx context.Context, id uuid.UUID) (int64, error) + DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error) + DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error + DeleteRole(ctx context.Context, id uuid.UUID) (int64, error) DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error) DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) DisableTOTP(ctx context.Context, id uuid.UUID) error EnableTOTP(ctx context.Context, arg EnableTOTPParams) error + GetAPIToken(ctx context.Context, id uuid.UUID) (ApiToken, error) + GetAPITokenByHash(ctx context.Context, tokenHash []byte) (ApiToken, error) + GetAssignment(ctx context.Context, id uuid.UUID) (RoleAssignment, error) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) + GetInvitation(ctx context.Context, id uuid.UUID) (Invitation, error) + GetInvitationByHash(ctx context.Context, tokenHash []byte) (GetInvitationByHashRow, error) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) + GetRole(ctx context.Context, id uuid.UUID) (Role, error) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) GetUser(ctx context.Context, id uuid.UUID) (User, error) GetUserByEmail(ctx context.Context, email string) (User, error) InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error) + InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error) IsMember(ctx context.Context, arg IsMemberParams) (bool, error) + ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error) + ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) ListOrgs(ctx context.Context) ([]Org, error) + ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error) + ListRoles(ctx context.Context) ([]Role, error) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) + MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error) + // Every role a member holds, with the scope it applies to. + MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error + TouchAPIToken(ctx context.Context, id uuid.UUID) error TouchIdentity(ctx context.Context, arg TouchIdentityParams) error + UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error) + UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error) } diff --git a/internal/store/queries/api_tokens.sql b/internal/store/queries/api_tokens.sql new file mode 100644 index 0000000..6ecbf8c --- /dev/null +++ b/internal/store/queries/api_tokens.sql @@ -0,0 +1,33 @@ +-- name: APITokenOrg :one +SELECT coalesce(api_token_org(sqlc.arg(hash)::bytea), '00000000-0000-0000-0000-000000000000')::uuid AS org_id; + +-- name: GetAPITokenByHash :one +SELECT * FROM api_tokens WHERE token_hash = $1; + +-- name: TouchAPIToken :exec +UPDATE api_tokens SET last_used_at = now() +WHERE id = $1 AND (last_used_at IS NULL OR last_used_at < now() - interval '1 minute'); + +-- name: CreateAPIToken :one +INSERT INTO api_tokens (org_id, user_id, name, token_hash, prefix, permissions, expires_at) +VALUES ($1, $2, $3, $4, $5, $6, $7) +RETURNING *; + +-- name: ListAPITokens :many +SELECT t.*, u.email AS user_email +FROM api_tokens t +JOIN users u ON u.id = t.user_id +WHERE t.org_id = $1 AND (sqlc.narg(user_id)::uuid IS NULL OR t.user_id = sqlc.narg(user_id)) +ORDER BY t.created_at DESC; + +-- name: GetAPIToken :one +SELECT * FROM api_tokens WHERE id = $1; + +-- name: DeleteAPIToken :execrows +DELETE FROM api_tokens WHERE id = $1; + +-- name: ClampAPITokenExpiry :execrows +-- Shortens tokens that would outlive a newly set maximum lifetime. +UPDATE api_tokens SET expires_at = now() + make_interval(days => sqlc.arg(max_days)::int) +WHERE org_id = sqlc.arg(org_id) + AND (expires_at IS NULL OR expires_at > now() + make_interval(days => sqlc.arg(max_days)::int)); diff --git a/internal/store/queries/invitations.sql b/internal/store/queries/invitations.sql new file mode 100644 index 0000000..0997f9b --- /dev/null +++ b/internal/store/queries/invitations.sql @@ -0,0 +1,31 @@ +-- name: InvitationOrg :one +SELECT coalesce(invitation_org(sqlc.arg(hash)::bytea), '00000000-0000-0000-0000-000000000000')::uuid AS org_id; + +-- name: CreateInvitation :one +INSERT INTO invitations (org_id, email, role_id, token_hash, invited_by, expires_at) +VALUES ($1, $2, $3, $4, $5, $6) +RETURNING *; + +-- name: GetInvitationByHash :one +SELECT i.*, r.name AS role_name, o.name AS org_name, o.slug AS org_slug +FROM invitations i +JOIN roles r ON r.id = i.role_id +JOIN orgs o ON o.id = i.org_id +WHERE i.token_hash = $1; + +-- name: ListPendingInvitations :many +SELECT i.id, i.email, i.expires_at, i.created_at, r.name AS role_name +FROM invitations i +JOIN roles r ON r.id = i.role_id +WHERE i.accepted_at IS NULL AND i.expires_at > now() +ORDER BY i.created_at DESC; + +-- name: GetInvitation :one +SELECT * FROM invitations WHERE id = $1; + +-- name: DeleteInvitation :execrows +DELETE FROM invitations WHERE id = $1; + +-- name: MarkInvitationAccepted :execrows +UPDATE invitations SET accepted_at = now() +WHERE id = $1 AND accepted_at IS NULL AND expires_at > now(); diff --git a/internal/store/queries/orgs.sql b/internal/store/queries/orgs.sql index 98a20f3..b8fbf58 100644 --- a/internal/store/queries/orgs.sql +++ b/internal/store/queries/orgs.sql @@ -13,3 +13,8 @@ SELECT * FROM orgs ORDER BY name; -- name: DeleteOrg :execrows DELETE FROM orgs WHERE id = $1; + +-- name: UpdateOrgPolicy :one +UPDATE orgs SET require_totp = $2, require_sso = $3, api_token_max_days = $4, updated_at = now() +WHERE id = $1 +RETURNING *; diff --git a/internal/store/queries/roles.sql b/internal/store/queries/roles.sql new file mode 100644 index 0000000..746b07e --- /dev/null +++ b/internal/store/queries/roles.sql @@ -0,0 +1,45 @@ +-- name: ListRoles :many +SELECT * FROM roles ORDER BY org_id NULLS FIRST, name; + +-- name: GetRole :one +SELECT * FROM roles WHERE id = $1; + +-- name: CreateRole :one +INSERT INTO roles (org_id, name, permissions) VALUES ($1, $2, $3) +RETURNING *; + +-- name: UpdateRole :one +UPDATE roles SET name = $2, permissions = $3, updated_at = now() +WHERE id = $1 AND org_id IS NOT NULL +RETURNING *; + +-- name: DeleteRole :execrows +DELETE FROM roles WHERE id = $1 AND org_id IS NOT NULL; + +-- name: CountRoleAssignments :one +SELECT count(*) FROM role_assignments WHERE role_id = $1; + +-- name: MemberGrants :many +-- Every role a member holds, with the scope it applies to. +SELECT r.permissions, a.resource_type, a.resource_id +FROM role_assignments a +JOIN roles r ON r.id = a.role_id +WHERE a.org_id = $1 AND a.user_id = $2; + +-- name: ListAssignments :many +SELECT a.id, a.user_id, a.role_id, r.name AS role_name, r.key AS role_key, a.resource_type, a.resource_id +FROM role_assignments a +JOIN roles r ON r.id = a.role_id +WHERE a.org_id = $1 +ORDER BY r.name; + +-- name: GetAssignment :one +SELECT * FROM role_assignments WHERE id = $1; + +-- name: CreateAssignment :one +INSERT INTO role_assignments (org_id, user_id, role_id, resource_type, resource_id) +VALUES ($1, $2, $3, $4, $5) +RETURNING *; + +-- name: DeleteAssignment :execrows +DELETE FROM role_assignments WHERE id = $1; diff --git a/internal/store/queries/sso.sql b/internal/store/queries/sso.sql index 32e25b6..0c31dac 100644 --- a/internal/store/queries/sso.sql +++ b/internal/store/queries/sso.sql @@ -2,8 +2,8 @@ SELECT coalesce(org_id_by_slug(sqlc.arg(slug)::citext), '00000000-0000-0000-0000-000000000000')::uuid AS id; -- name: CreateSSOProvider :one -INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) +INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, default_role_id) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING *; -- name: UpdateSSOProvider :one @@ -16,6 +16,7 @@ UPDATE sso_providers SET allowed_domains = $6, auto_provision = $7, enabled = $8, + default_role_id = $9, updated_at = now() WHERE id = $1 RETURNING *; diff --git a/internal/store/roles.sql.go b/internal/store/roles.sql.go new file mode 100644 index 0000000..6c912ab --- /dev/null +++ b/internal/store/roles.sql.go @@ -0,0 +1,290 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: roles.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const countRoleAssignments = `-- name: CountRoleAssignments :one +SELECT count(*) FROM role_assignments WHERE role_id = $1 +` + +func (q *Queries) CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error) { + row := q.db.QueryRow(ctx, countRoleAssignments, roleID) + var count int64 + err := row.Scan(&count) + return count, err +} + +const createAssignment = `-- name: CreateAssignment :one +INSERT INTO role_assignments (org_id, user_id, role_id, resource_type, resource_id) +VALUES ($1, $2, $3, $4, $5) +RETURNING id, org_id, user_id, role_id, resource_type, resource_id, created_at +` + +type CreateAssignmentParams struct { + OrgID uuid.UUID + UserID uuid.UUID + RoleID uuid.UUID + ResourceType *string + ResourceID *uuid.UUID +} + +func (q *Queries) CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (RoleAssignment, error) { + row := q.db.QueryRow(ctx, createAssignment, + arg.OrgID, + arg.UserID, + arg.RoleID, + arg.ResourceType, + arg.ResourceID, + ) + var i RoleAssignment + err := row.Scan( + &i.ID, + &i.OrgID, + &i.UserID, + &i.RoleID, + &i.ResourceType, + &i.ResourceID, + &i.CreatedAt, + ) + return i, err +} + +const createRole = `-- name: CreateRole :one +INSERT INTO roles (org_id, name, permissions) VALUES ($1, $2, $3) +RETURNING id, org_id, key, name, permissions, created_at, updated_at +` + +type CreateRoleParams struct { + OrgID *uuid.UUID + Name string + Permissions []string +} + +func (q *Queries) CreateRole(ctx context.Context, arg CreateRoleParams) (Role, error) { + row := q.db.QueryRow(ctx, createRole, arg.OrgID, arg.Name, arg.Permissions) + var i Role + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Key, + &i.Name, + &i.Permissions, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const deleteAssignment = `-- name: DeleteAssignment :execrows +DELETE FROM role_assignments WHERE id = $1 +` + +func (q *Queries) DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteAssignment, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteRole = `-- name: DeleteRole :execrows +DELETE FROM roles WHERE id = $1 AND org_id IS NOT NULL +` + +func (q *Queries) DeleteRole(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteRole, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getAssignment = `-- name: GetAssignment :one +SELECT id, org_id, user_id, role_id, resource_type, resource_id, created_at FROM role_assignments WHERE id = $1 +` + +func (q *Queries) GetAssignment(ctx context.Context, id uuid.UUID) (RoleAssignment, error) { + row := q.db.QueryRow(ctx, getAssignment, id) + var i RoleAssignment + err := row.Scan( + &i.ID, + &i.OrgID, + &i.UserID, + &i.RoleID, + &i.ResourceType, + &i.ResourceID, + &i.CreatedAt, + ) + return i, err +} + +const getRole = `-- name: GetRole :one +SELECT id, org_id, key, name, permissions, created_at, updated_at FROM roles WHERE id = $1 +` + +func (q *Queries) GetRole(ctx context.Context, id uuid.UUID) (Role, error) { + row := q.db.QueryRow(ctx, getRole, id) + var i Role + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Key, + &i.Name, + &i.Permissions, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const listAssignments = `-- name: ListAssignments :many +SELECT a.id, a.user_id, a.role_id, r.name AS role_name, r.key AS role_key, a.resource_type, a.resource_id +FROM role_assignments a +JOIN roles r ON r.id = a.role_id +WHERE a.org_id = $1 +ORDER BY r.name +` + +type ListAssignmentsRow struct { + ID uuid.UUID + UserID uuid.UUID + RoleID uuid.UUID + RoleName string + RoleKey *string + ResourceType *string + ResourceID *uuid.UUID +} + +func (q *Queries) ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error) { + rows, err := q.db.Query(ctx, listAssignments, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListAssignmentsRow{} + for rows.Next() { + var i ListAssignmentsRow + if err := rows.Scan( + &i.ID, + &i.UserID, + &i.RoleID, + &i.RoleName, + &i.RoleKey, + &i.ResourceType, + &i.ResourceID, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listRoles = `-- name: ListRoles :many +SELECT id, org_id, key, name, permissions, created_at, updated_at FROM roles ORDER BY org_id NULLS FIRST, name +` + +func (q *Queries) ListRoles(ctx context.Context) ([]Role, error) { + rows, err := q.db.Query(ctx, listRoles) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Role{} + for rows.Next() { + var i Role + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Key, + &i.Name, + &i.Permissions, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const memberGrants = `-- name: MemberGrants :many +SELECT r.permissions, a.resource_type, a.resource_id +FROM role_assignments a +JOIN roles r ON r.id = a.role_id +WHERE a.org_id = $1 AND a.user_id = $2 +` + +type MemberGrantsParams struct { + OrgID uuid.UUID + UserID uuid.UUID +} + +type MemberGrantsRow struct { + Permissions []string + ResourceType *string + ResourceID *uuid.UUID +} + +// Every role a member holds, with the scope it applies to. +func (q *Queries) MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error) { + rows, err := q.db.Query(ctx, memberGrants, arg.OrgID, arg.UserID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []MemberGrantsRow{} + for rows.Next() { + var i MemberGrantsRow + if err := rows.Scan(&i.Permissions, &i.ResourceType, &i.ResourceID); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const updateRole = `-- name: UpdateRole :one +UPDATE roles SET name = $2, permissions = $3, updated_at = now() +WHERE id = $1 AND org_id IS NOT NULL +RETURNING id, org_id, key, name, permissions, created_at, updated_at +` + +type UpdateRoleParams struct { + ID uuid.UUID + Name string + Permissions []string +} + +func (q *Queries) UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error) { + row := q.db.QueryRow(ctx, updateRole, arg.ID, arg.Name, arg.Permissions) + var i Role + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Key, + &i.Name, + &i.Permissions, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/internal/store/sso.sql.go b/internal/store/sso.sql.go index 2ed150f..b20ea99 100644 --- a/internal/store/sso.sql.go +++ b/internal/store/sso.sql.go @@ -37,9 +37,9 @@ func (q *Queries) CreateIdentity(ctx context.Context, arg CreateIdentityParams) } const createSSOProvider = `-- name: CreateSSOProvider :one -INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) -RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at +INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, default_role_id) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) +RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at, default_role_id ` type CreateSSOProviderParams struct { @@ -53,6 +53,7 @@ type CreateSSOProviderParams struct { AllowedDomains []string AutoProvision bool Enabled bool + DefaultRoleID *uuid.UUID } func (q *Queries) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) { @@ -67,6 +68,7 @@ func (q *Queries) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderPa arg.AllowedDomains, arg.AutoProvision, arg.Enabled, + arg.DefaultRoleID, ) var i SsoProvider err := row.Scan( @@ -82,6 +84,7 @@ func (q *Queries) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderPa &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.DefaultRoleID, ) return i, err } @@ -123,7 +126,7 @@ func (q *Queries) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserI } const getSSOProvider = `-- name: GetSSOProvider :one -SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at FROM sso_providers WHERE id = $1 +SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at, default_role_id FROM sso_providers WHERE id = $1 ` func (q *Queries) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) { @@ -142,6 +145,7 @@ func (q *Queries) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.DefaultRoleID, ) return i, err } @@ -192,7 +196,7 @@ func (q *Queries) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSO } const listSSOProviders = `-- name: ListSSOProviders :many -SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at FROM sso_providers ORDER BY name +SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at, default_role_id FROM sso_providers ORDER BY name ` func (q *Queries) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) { @@ -217,6 +221,7 @@ func (q *Queries) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) { &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.DefaultRoleID, ); err != nil { return nil, err } @@ -300,14 +305,15 @@ UPDATE sso_providers SET name = $2, issuer = $3, client_id = $4, - client_secret = coalesce($9, client_secret), + client_secret = coalesce($10, client_secret), scopes = $5, allowed_domains = $6, auto_provision = $7, enabled = $8, + default_role_id = $9, updated_at = now() WHERE id = $1 -RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at +RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at, default_role_id ` type UpdateSSOProviderParams struct { @@ -319,6 +325,7 @@ type UpdateSSOProviderParams struct { AllowedDomains []string AutoProvision bool Enabled bool + DefaultRoleID *uuid.UUID ClientSecret []byte } @@ -332,6 +339,7 @@ func (q *Queries) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderPa arg.AllowedDomains, arg.AutoProvision, arg.Enabled, + arg.DefaultRoleID, arg.ClientSecret, ) var i SsoProvider @@ -348,6 +356,7 @@ func (q *Queries) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderPa &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.DefaultRoleID, ) return i, err } diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js index a95524c..fc5e927 100644 --- a/internal/web/assets/app.js +++ b/internal/web/assets/app.js @@ -17,13 +17,22 @@ el.classList.toggle("hidden", !text); }; - // Inputs inside a hidden [data-step] are skipped, checkboxes become - // booleans and [data-list] inputs become comma-separated arrays. + // Inputs inside a hidden [data-step] are skipped. Checkboxes become + // booleans, or arrays of values with [data-multi]; [data-list] inputs are + // split on commas, [data-number] parsed and empty [data-nullable] sent as null. const serialize = (form) => { const out = {}; for (const el of form.elements) { - if (!el.name || el.disabled || el.closest("[data-step]")?.hidden) continue; + if (!el.name || el.closest("[data-step]")?.hidden) continue; + if (el.dataset.multi !== undefined) { + out[el.name] ??= []; + if (el.checked && !el.disabled) out[el.name].push(el.value); + continue; + } + if (el.disabled) continue; if (el.type === "checkbox") out[el.name] = el.checked; + else if (el.dataset.number !== undefined) out[el.name] = Number(el.value); + else if (el.dataset.nullable !== undefined) out[el.name] = el.value || null; else if (el.dataset.list !== undefined) out[el.name] = el.value.split(",").map((v) => v.trim()).filter(Boolean); else out[el.name] = el.value; @@ -54,6 +63,14 @@ out.hidden = false; return; } + if (form.dataset.showLink !== undefined && (res.data?.url || res.data?.token)) { + const out = form.querySelector("[data-link-output]"); + const input = out.querySelector("[data-link]"); + input.value = res.data.url || res.data.token; + out.hidden = false; + input.select(); + return; + } if (res.data?.status === "totp_required" && totpStep) { form.querySelector('[data-step="password"]').hidden = true; totpStep.hidden = false; diff --git a/internal/web/auth.templ b/internal/web/auth.templ index 14d9f59..fbf5b84 100644 --- a/internal/web/auth.templ +++ b/internal/web/auth.templ @@ -5,9 +5,9 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" ) -templ Login(p Page, signupAllowed bool) { +templ Login(p Page, signupAllowed bool, next string) { @authShell(p) { -
+ @formError()
@field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true) diff --git a/internal/web/auth_templ.go b/internal/web/auth_templ.go index 6ed711c..adfc79f 100644 --- a/internal/web/auth_templ.go +++ b/internal/web/auth_templ.go @@ -14,7 +14,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" ) -func Login(p Page, signupAllowed bool) templ.Component { +func Login(p Page, signupAllowed bool, next string) templ.Component { return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { @@ -43,7 +43,20 @@ func Login(p Page, signupAllowed bool) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -51,7 +64,7 @@ func Login(p Page, signupAllowed bool) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -63,20 +76,20 @@ func Login(p Page, signupAllowed bool) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -92,90 +105,90 @@ func Login(p Page, signupAllowed bool) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "

") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - var templ_7745c5c3_Var4 string - templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.heading")) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 23, Col: 108} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } var templ_7745c5c3_Var5 string - templ_7745c5c3_Var5, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "auth.sso.org_placeholder")).Resolve(ctx) + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.heading")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 28, Col: 58} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 23, Col: 108} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "\" aria-label=\"") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "\" autocomplete=\"organization\" required>
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if signupAllowed { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "

") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - var templ_7745c5c3_Var8 string - templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account")) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 38, Col: 42} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } var templ_7745c5c3_Var9 string - templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup")) + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 39, Col: 105} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 38, Col: 42} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var10 string + templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 39, Col: 105} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -207,7 +220,7 @@ func Signup(p Page) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var11 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var12 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -219,7 +232,7 @@ func Signup(p Page) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -239,7 +252,7 @@ func Signup(p Page) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -255,26 +268,26 @@ func Signup(p Page) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var12 string - templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login")) + var templ_7745c5c3_Var13 string + templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login")) if templ_7745c5c3_Err != nil { return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 57, Col: 137} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var12), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/console.templ b/internal/web/console.templ index 604d2a9..319f9fa 100644 --- a/internal/web/console.templ +++ b/internal/web/console.templ @@ -12,7 +12,11 @@ type Me struct { TOTP bool ActiveOrg string Orgs []Org - TOTPMissing bool + // Can holds the permissions in the active organization. + Can map[string]bool + // Policy is the error code of an unmet sign-in policy of the active + // organization, or empty. + Policy string // RecoveryCodesLeft counts unused TOTP recovery codes. RecoveryCodesLeft int } @@ -40,7 +44,15 @@ templ consoleShell(p Page, me Me) { { me.Orgs[0].Name } }
- if me.TOTPMissing { -
-

- { i18n.T(ctx, "console.totp_missing") } - { i18n.T(ctx, "console.totp_missing_action") } -

-
+ switch me.Policy { + case "totp_required_by_org": + @policyBanner("error.totp_required_by_org", "console.totp_missing_action", "/settings/security") + case "sso_required_by_org": + @policyBanner("error.sso_required_by_org", "console.sso_required_action", "/sso/"+me.ActiveSlug) }
@flash(p) @@ -150,3 +160,12 @@ templ recoveryOutput() { { i18n.T(ctx, "security.recovery.saved") } } + +templ policyBanner(msgID, actionID, href string) { +
+

+ { i18n.T(ctx, msgID) } + { i18n.T(ctx, actionID) } +

+
+} diff --git a/internal/web/console_templ.go b/internal/web/console_templ.go index 6f6c00c..21595a6 100644 --- a/internal/web/console_templ.go +++ b/internal/web/console_templ.go @@ -21,7 +21,11 @@ type Me struct { TOTP bool ActiveOrg string Orgs []Org - TOTPMissing bool + // Can holds the permissions in the active organization. + Can map[string]bool + // Policy is the error code of an unmet sign-in policy of the active + // organization, or empty. + Policy string // RecoveryCodesLeft counts unused TOTP recovery codes. RecoveryCodesLeft int } @@ -81,7 +85,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var3 string templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(o.ID).Resolve(ctx) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 36, Col: 27} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 40, Col: 27} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3) if templ_7745c5c3_Err != nil { @@ -104,7 +108,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var4 string templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 36, Col: 73} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 40, Col: 73} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) if templ_7745c5c3_Err != nil { @@ -127,7 +131,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var5 string templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(me.Orgs[0].Name) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 40, Col: 47} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 44, Col: 47} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) if templ_7745c5c3_Err != nil { @@ -142,52 +146,116 @@ func consoleShell(p Page, me Me) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - if me.IsOwner { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "") + if me.Can["members.read"] { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } var templ_7745c5c3_Var6 string - templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.sso")) + templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.members")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 44, Col: 96} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 48, Col: 104} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var7 string + templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.roles")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 49, Col: 100} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "") + if len(me.Orgs) > 0 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.tokens")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 52, Col: 102} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + if me.Can["org.manage"] { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.org")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 55, Col: 96} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var10 string + templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.sso")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 56, Col: 96} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var7 string - templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.security")) + var templ_7745c5c3_Var11 string + templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.security")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 46, Col: 105} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 58, Col: 105} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -195,43 +263,23 @@ func consoleShell(p Page, me Me) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - if me.TOTPMissing { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "

") + switch me.Policy { + case "totp_required_by_org": + templ_7745c5c3_Err = policyBanner("error.totp_required_by_org", "console.totp_missing_action", "/settings/security").Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var9 string - templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing")) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 55, Col: 42} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, " ") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - var templ_7745c5c3_Var10 string - templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing_action")) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 56, Col: 115} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "

") + case "sso_required_by_org": + templ_7745c5c3_Err = policyBanner("error.sso_required_by_org", "console.sso_required_action", "/sso/"+me.ActiveSlug).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -243,7 +291,7 @@ func consoleShell(p Page, me Me) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -274,7 +322,7 @@ func Dashboard(p Page, me Me) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var12 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var14 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -286,39 +334,39 @@ func Dashboard(p Page, me Me) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var13 string - templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title")) + var templ_7745c5c3_Var15 string + templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 69, Col: 75} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 79, Col: 75} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var14 string - templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty")) + var templ_7745c5c3_Var16 string + templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 70, Col: 76} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 80, Col: 76} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var12), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var14), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -349,7 +397,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var16 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var18 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -361,51 +409,51 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var17 string - templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title")) + var templ_7745c5c3_Var19 string + templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 82, Col: 72} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 92, Col: 72} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var18 string - templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading")) + var templ_7745c5c3_Var20 string + templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 84, Col: 114} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 94, Col: 114} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if me.TOTP { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "

● ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "

● ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var19 string - templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active")) + var templ_7745c5c3_Var21 string + templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 86, Col: 98} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 96, Col: 98} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -413,25 +461,25 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen templ_7745c5c3_ElementWriter := templ_7745c5c3_Buffer templ_7745c5c3_Buffer := templ.GetBuffer() var templ_7745c5c3_ElementScripts []templ.ComponentScript - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "

= 3)} - templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_Var20...) + var templ_7745c5c3_Var22 = []any{"mb-6 text-sm", templ.KV("text-down", me.RecoveryCodesLeft < 3), templ.KV("text-muted", me.RecoveryCodesLeft >= 3)} + templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_Var22...) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var21 string - templ_7745c5c3_Var21, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.CSSClasses(templ_7745c5c3_Var20).String()).Resolve(ctx) + var templ_7745c5c3_Var23 string + templ_7745c5c3_Var23, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.CSSClasses(templ_7745c5c3_Var22).String()).Resolve(ctx) if templ_7745c5c3_Err != nil { return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 1, Col: 0} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var23) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\"") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\"") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -445,33 +493,33 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen } templ.ReleaseBuffer(templ_7745c5c3_Buffer) } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, ">") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, ">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var22 string - templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft)) + var templ_7745c5c3_Var24 string + templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 88, Col: 75} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 98, Col: 75} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var23 string - templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.regenerate")) + var templ_7745c5c3_Var25 string + templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.regenerate")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 91, Col: 116} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 101, Col: 116} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -495,20 +543,20 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var24 string - templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.disable")) + var templ_7745c5c3_Var26 string + templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.disable")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 101, Col: 109} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 111, Col: 109} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -528,51 +576,51 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "

● ") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - var templ_7745c5c3_Var25 string - templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.inactive")) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 110, Col: 105} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var28 string - templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading")) + var templ_7745c5c3_Var30 string + templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 127, Col: 113} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 137, Col: 113} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if len(identities) == 0 { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var29 string - templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none")) + var templ_7745c5c3_Var31 string + templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 129, Col: 73} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 139, Col: 73} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "
    ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "
      ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } for _, id := range identities { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "
    • ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "
    • ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var30 string - templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider) + var templ_7745c5c3_Var32 string + templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 133, Col: 69} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 143, Col: 69} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var31 string - templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email) + var templ_7745c5c3_Var33 string + templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 133, Col: 131} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 143, Col: 131} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "
    • ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "
    ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } if canLink { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "\" class=\"inline-block border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var33 string - templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link")) + var templ_7745c5c3_Var35 string + templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 138, Col: 190} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 148, Col: 190} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var16), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var18), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -739,33 +787,97 @@ func recoveryOutput() templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func policyBanner(msgID, actionID, href string) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var40 string + templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, msgID)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 167, Col: 23} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var42 string + templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, actionID)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 168, Col: 95} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/org.templ b/internal/web/org.templ new file mode 100644 index 0000000..3a975f4 --- /dev/null +++ b/internal/web/org.templ @@ -0,0 +1,447 @@ +package web + +import ( + "slices" + "strconv" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" +) + +// Role is a built-in or custom role. +type Role struct { + ID string + Name string + BuiltIn bool + Permissions []string +} + +// Assignment is one role a member holds. +type Assignment struct { + ID string + RoleName string + // Scope is empty for organization-wide assignments. + Scope string +} + +// Member is a row on the members page. +type Member struct { + UserID string + Email string + DisplayName string + IsOwner bool + Assignments []Assignment +} + +// PendingInvite is an invitation that was not accepted yet. +type PendingInvite struct { + ID string + Email string + RoleName string +} + +// MembersView is the data of the members page. +type MembersView struct { + Members []Member + Roles []Role + Invitations []PendingInvite + CanManage bool +} + +templ settingsHeading(titleID, introID string) { +

{ i18n.T(ctx, titleID) }

+ if introID != "" { +

{ i18n.T(ctx, introID) }

+ } +} + +templ sectionHeading(id string) { +

{ i18n.T(ctx, id) }

+} + +templ roleSelect(roles []Role, name string) { + +} + +templ MembersPage(p Page, me Me, v MembersView) { + @consoleShell(p, me) { + @settingsHeading("members.title", "members.intro") + + + + + + + + + + for _, m := range v.Members { + + + + + + } + +
{ i18n.T(ctx, "auth.field.email") }{ i18n.T(ctx, "members.roles") }
+ { m.Email } + if m.DisplayName != "" { + { m.DisplayName } + } + + if m.IsOwner { + { i18n.T(ctx, "members.owner") } + } +
    + for _, a := range m.Assignments { +
  • + { a.RoleName } + if a.Scope != "" { + · { a.Scope } + } + if v.CanManage { + + } +
  • + } +
+
+ if v.CanManage && !m.IsOwner { +
+ { i18n.T(ctx, "sso.action.edit") } +
+
+ @formError() + @roleSelect(v.Roles, "role_id") + @submit(i18n.T(ctx, "members.assign")) +
+ +
+
+ } +
+ if v.CanManage { +
+
+ @sectionHeading("members.invite") +
+ @formError() + @field(i18n.T(ctx, "auth.field.email"), "email", "email", "off", true) + + @submit(i18n.T(ctx, "members.invite_submit")) + +
+
+ if len(v.Invitations) > 0 { +
+ @sectionHeading("members.pending") +
    + for _, inv := range v.Invitations { +
  • + { inv.Email } · { inv.RoleName } + +
  • + } +
+
+ } +
+ } + } +} + +// RolesView is the data of the roles page. +type RolesView struct { + Roles []Role + Permissions []string + // Grantable lists the permissions the viewer may put into a role. + Grantable []string + CanManage bool +} + +templ permissionChecks(all, grantable, checked []string) { +
+ for _, perm := range all { + + } +
+} + +templ RolesPage(p Page, me Me, v RolesView) { + @consoleShell(p, me) { + @settingsHeading("roles.title", "roles.intro") +
+ for _, r := range v.Roles { +
+
+

+ { r.Name } + if r.BuiltIn { + { i18n.T(ctx, "roles.built_in") } + } +

+ if v.CanManage && !r.BuiltIn { + + } +
+ if v.CanManage && !r.BuiltIn { +
+ @formError() + @valueField(i18n.T(ctx, "sso.field.name"), "name", r.Name, "", true) + @permissionChecks(v.Permissions, v.Grantable, r.Permissions) + @submit(i18n.T(ctx, "common.save")) +
+ } else { +
    + for _, perm := range r.Permissions { +
  • { i18n.T(ctx, "perm."+perm) }
  • + } +
+ } +
+ } +
+ if v.CanManage { +
+ @sectionHeading("roles.create") +
+ @formError() + @valueField(i18n.T(ctx, "sso.field.name"), "name", "", "", true) + @permissionChecks(v.Permissions, v.Grantable, nil) + @submit(i18n.T(ctx, "roles.create")) +
+
+ } + } +} + +// Token is a row on the tokens page. +type Token struct { + ID string + Name string + Prefix string + UserEmail string + Permissions []string + CreatedAt string + ExpiresAt string + LastUsedAt string +} + +// TokensView is the data of the tokens page. +type TokensView struct { + Tokens []Token + Grantable []string + // ShowOwner is set when the viewer oversees all tokens of the org. + ShowOwner bool + // MaxDays is the org's token lifetime limit, 0 if none. + MaxDays int + // ExpiryDays are the lifetimes offered when creating a token; 0 means + // no expiry. + ExpiryDays []int +} + +templ TokensPage(p Page, me Me, v TokensView) { + @consoleShell(p, me) { + if v.ShowOwner { + @settingsHeading("tokens.title", "tokens.intro_all") + } else { + @settingsHeading("tokens.title", "tokens.intro") + } + if v.MaxDays > 0 { +

{ i18n.T(ctx, "tokens.policy", "Count", v.MaxDays) }

+ } + if len(v.Tokens) > 0 { + + + + + if v.ShowOwner { + + } + + + + + + + + + for _, t := range v.Tokens { + + + if v.ShowOwner { + + } + + + + + + + } + +
{ i18n.T(ctx, "sso.field.name") }{ i18n.T(ctx, "tokens.owner") }{ i18n.T(ctx, "tokens.permissions") }{ i18n.T(ctx, "tokens.created") }{ i18n.T(ctx, "tokens.expires") }{ i18n.T(ctx, "tokens.last_used") }
{ t.Name } { t.Prefix }…{ t.UserEmail } +
    + for _, perm := range t.Permissions { +
  • { i18n.T(ctx, "perm."+perm) }
  • + } +
+
{ t.CreatedAt }{ t.ExpiresAt }{ t.LastUsedAt } + +
+ } +
+ @sectionHeading("tokens.create") +
+ @formError() + @valueField(i18n.T(ctx, "sso.field.name"), "name", "", "", true) + @permissionChecks(v.Grantable, v.Grantable, nil) + + @submit(i18n.T(ctx, "tokens.create")) + +
+
+ } +} + +// OrgSettings is the data of the organization settings page. +type OrgSettings struct { + RequireTOTP bool + RequireSSO bool + // TokenMaxDays is 0 when API token lifetime is unlimited. + TokenMaxDays int +} + +templ OrgSettingsPage(p Page, me Me, v OrgSettings) { + @consoleShell(p, me) { + @settingsHeading("org.title", "") +
+ @sectionHeading("org.policy") +
+ @formError() + @checkbox(i18n.T(ctx, "org.require_totp"), "require_totp", v.RequireTOTP) +

{ i18n.T(ctx, "org.require_totp_hint") }

+ @checkbox(i18n.T(ctx, "org.require_sso"), "require_sso", v.RequireSSO) +

{ i18n.T(ctx, "org.require_sso_hint") }

+ +

{ i18n.T(ctx, "org.token_max_days_hint") }

+ @submit(i18n.T(ctx, "common.save")) +
+
+ } +} + +// Invitation is the data of the invitation landing page. +type Invitation struct { + Token string + Valid bool + OrgName string + RoleName string + Email string + SignedInAs string + AccountExists bool +} + +templ InvitationPage(p Page, v Invitation) { + @authShell(p) { + if !v.Valid { +

{ i18n.T(ctx, "error.invitation_invalid") }

+ } else { +

{ i18n.T(ctx, "invite.summary", "Org", v.OrgName, "Role", v.RoleName) }

+

{ v.Email }

+ switch { + case v.SignedInAs == v.Email: +
+ @formError() + @submit(i18n.T(ctx, "invite.accept")) +
+ case v.SignedInAs != "": +

{ i18n.T(ctx, "error.invitation_email_mismatch") }

+ + case v.AccountExists: + { i18n.T(ctx, "invite.sign_in") } + default: +
+ @formError() + @field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false) + @field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true) + @submit(i18n.T(ctx, "invite.create_account")) +
+ } + } + } +} + +func maxDaysValue(d int) string { + if d == 0 { + return "" + } + return strconv.Itoa(d) +} diff --git a/internal/web/org_templ.go b/internal/web/org_templ.go new file mode 100644 index 0000000..f285de1 --- /dev/null +++ b/internal/web/org_templ.go @@ -0,0 +1,1949 @@ +// Code generated by templ - DO NOT EDIT. + +// templ: version: v0.3.1118 + +package web + +//lint:file-ignore SA4006 This context is only used if a nested component is present. + +import "github.com/a-h/templ" +import templruntime "github.com/a-h/templ/runtime" + +import ( + "slices" + "strconv" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" +) + +// Role is a built-in or custom role. +type Role struct { + ID string + Name string + BuiltIn bool + Permissions []string +} + +// Assignment is one role a member holds. +type Assignment struct { + ID string + RoleName string + // Scope is empty for organization-wide assignments. + Scope string +} + +// Member is a row on the members page. +type Member struct { + UserID string + Email string + DisplayName string + IsOwner bool + Assignments []Assignment +} + +// PendingInvite is an invitation that was not accepted yet. +type PendingInvite struct { + ID string + Email string + RoleName string +} + +// MembersView is the data of the members page. +type MembersView struct { + Members []Member + Roles []Role + Invitations []PendingInvite + CanManage bool +} + +func settingsHeading(titleID, introID string) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var2 string + templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, titleID)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 52, Col: 62} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if introID != "" { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var3 string + templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, introID)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 54, Col: 69} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + return nil + }) +} + +func sectionHeading(id string) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, id)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 59, Col: 91} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func roleSelect(roles []Role, name string) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func MembersPage(p Page, me Me, v MembersView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var11 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = settingsHeading("members.title", "members.intro").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, m := range v.Members { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var12 string + templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.field.email")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 76, Col: 72} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var13 string + templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "members.roles")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 77, Col: 69} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var14 string + templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(m.Email) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 85, Col: 16} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if m.DisplayName != "" { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var15 string + templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(m.DisplayName) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 87, Col: 62} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if m.IsOwner { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var16 string + templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "members.owner")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 92, Col: 64} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "
    ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, a := range m.Assignments { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var17 string + templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(a.RoleName) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 97, Col: 22} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if a.Scope != "" { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "· ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var18 string + templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(a.Scope) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 99, Col: 48} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + if v.CanManage { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if v.CanManage && !m.IsOwner { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var21 string + templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.action.edit")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 116, Col: 99} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = roleSelect(v.Roles, "role_id").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "members.assign")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if v.CanManage { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("members.invite").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.email"), "email", "email", "off", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "members.invite_submit")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if len(v.Invitations) > 0 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("members.pending").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "
    ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, inv := range v.Invitations { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var28 string + templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(inv.Email) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 161, Col: 26} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, " · ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var29 string + templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(inv.RoleName) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 161, Col: 71} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +// RolesView is the data of the roles page. +type RolesView struct { + Roles []Role + Permissions []string + // Grantable lists the permissions the viewer may put into a role. + Grantable []string + CanManage bool +} + +func permissionChecks(all, grantable, checked []string) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, perm := range all { + { + templ_7745c5c3_ElementWriter := templ_7745c5c3_Buffer + templ_7745c5c3_Buffer := templ.GetBuffer() + var templ_7745c5c3_ElementScripts []templ.ComponentScript + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func RolesPage(p Page, me Me, v RolesView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var38 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = settingsHeading("roles.title", "roles.intro").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, r := range v.Roles { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var39 string + templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(r.Name) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 209, Col: 15} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if r.BuiltIn { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var40 string + templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "roles.built_in")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 211, Col: 77} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if v.CanManage && !r.BuiltIn { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if v.CanManage && !r.BuiltIn { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", r.Name, "", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = permissionChecks(v.Permissions, v.Grantable, r.Permissions).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "common.save")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "
    ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, perm := range r.Permissions { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var45 string + templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "perm."+perm)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 233, Col: 80} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var45)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if v.CanManage { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("roles.create").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", "", "", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = permissionChecks(v.Permissions, v.Grantable, nil).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "roles.create")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var38), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +// Token is a row on the tokens page. +type Token struct { + ID string + Name string + Prefix string + UserEmail string + Permissions []string + CreatedAt string + ExpiresAt string + LastUsedAt string +} + +// TokensView is the data of the tokens page. +type TokensView struct { + Tokens []Token + Grantable []string + // ShowOwner is set when the viewer oversees all tokens of the org. + ShowOwner bool + // MaxDays is the org's token lifetime limit, 0 if none. + MaxDays int + // ExpiryDays are the lifetimes offered when creating a token; 0 means + // no expiry. + ExpiryDays []int +} + +func TokensPage(p Page, me Me, v TokensView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var47 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + if v.ShowOwner { + templ_7745c5c3_Err = settingsHeading("tokens.title", "tokens.intro_all").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + templ_7745c5c3_Err = settingsHeading("tokens.title", "tokens.intro").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if v.MaxDays > 0 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var48 string + templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "tokens.policy", "Count", v.MaxDays)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 287, Col: 83} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var48)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if len(v.Tokens) > 0 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if v.ShowOwner { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, t := range v.Tokens { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 104, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if v.ShowOwner { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 107, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 109, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 119, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var49 string + templ_7745c5c3_Var49, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.name")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 293, Col: 71} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var49)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var50 string + templ_7745c5c3_Var50, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "tokens.owner")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 295, Col: 70} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var50)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var51 string + templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "tokens.permissions")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 297, Col: 75} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var51)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 100, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var52 string + templ_7745c5c3_Var52, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "tokens.created")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 298, Col: 71} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var52)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 101, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var53 string + templ_7745c5c3_Var53, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "tokens.expires")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 299, Col: 71} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var53)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 102, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var54 string + templ_7745c5c3_Var54, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "tokens.last_used")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 300, Col: 73} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var54)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 103, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var55 string + templ_7745c5c3_Var55, templ_7745c5c3_Err = templ.JoinStringErrs(t.Name) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 307, Col: 39} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var55)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 105, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var56 string + templ_7745c5c3_Var56, templ_7745c5c3_Err = templ.JoinStringErrs(t.Prefix) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 307, Col: 101} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var56)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 106, "…") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var57 string + templ_7745c5c3_Var57, templ_7745c5c3_Err = templ.JoinStringErrs(t.UserEmail) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 309, Col: 45} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var57)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 108, "
    ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, perm := range t.Permissions { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 110, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var58 string + templ_7745c5c3_Var58, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "perm."+perm)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 314, Col: 79} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var58)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 111, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 112, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var59 string + templ_7745c5c3_Var59, templ_7745c5c3_Err = templ.JoinStringErrs(t.CreatedAt) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 318, Col: 80} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var59)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 113, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var60 string + templ_7745c5c3_Var60, templ_7745c5c3_Err = templ.JoinStringErrs(t.ExpiresAt) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 319, Col: 80} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var60)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 114, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var61 string + templ_7745c5c3_Var61, templ_7745c5c3_Err = templ.JoinStringErrs(t.LastUsedAt) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 320, Col: 81} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var61)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 115, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 120, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("tokens.create").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 121, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", "", "", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = permissionChecks(v.Grantable, v.Grantable, nil).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 122, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "tokens.create")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 132, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var47), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +// OrgSettings is the data of the organization settings page. +type OrgSettings struct { + RequireTOTP bool + RequireSSO bool + // TokenMaxDays is 0 when API token lifetime is unlimited. + TokenMaxDays int +} + +func OrgSettingsPage(p Page, me Me, v OrgSettings) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var71 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = settingsHeading("org.title", "").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 134, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("org.policy").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 135, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = checkbox(i18n.T(ctx, "org.require_totp"), "require_totp", v.RequireTOTP).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 136, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var72 string + templ_7745c5c3_Var72, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "org.require_totp_hint")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 378, Col: 82} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var72)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 137, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = checkbox(i18n.T(ctx, "org.require_sso"), "require_sso", v.RequireSSO).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 138, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var73 string + templ_7745c5c3_Var73, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "org.require_sso_hint")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 380, Col: 81} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var73)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 139, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var77 string + templ_7745c5c3_Var77, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "org.token_max_days_hint")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 394, Col: 79} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var77)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 143, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "common.save")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 144, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var71), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +// Invitation is the data of the invitation landing page. +type Invitation struct { + Token string + Valid bool + OrgName string + RoleName string + Email string + SignedInAs string + AccountExists bool +} + +func InvitationPage(p Page, v Invitation) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var79 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + if !v.Valid { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 145, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var80 string + templ_7745c5c3_Var80, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "error.invitation_invalid")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 415, Col: 63} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var80)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 146, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 147, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var81 string + templ_7745c5c3_Var81, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "invite.summary", "Org", v.OrgName, "Role", v.RoleName)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 417, Col: 96} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var81)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 148, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var82 string + templ_7745c5c3_Var82, templ_7745c5c3_Err = templ.JoinStringErrs(v.Email) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 418, Col: 46} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var82)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 149, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + switch { + case v.SignedInAs == v.Email: + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 150, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "invite.accept")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 152, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + case v.SignedInAs != "": + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 153, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var84 string + templ_7745c5c3_Var84, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "error.invitation_email_mismatch")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 426, Col: 82} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var84)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 154, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + case v.AccountExists: + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 156, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var87 string + templ_7745c5c3_Var87, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "invite.sign_in")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/org.templ`, Line: 429, Col: 153} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var87)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 158, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + default: + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 159, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "invite.create_account")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 161, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + } + return nil + }) + templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var79), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func maxDaysValue(d int) string { + if d == 0 { + return "" + } + return strconv.Itoa(d) +} + +var _ = templruntime.GeneratedTemplate diff --git a/internal/web/sso.templ b/internal/web/sso.templ index 2651a50..ffbbce5 100644 --- a/internal/web/sso.templ +++ b/internal/web/sso.templ @@ -28,6 +28,7 @@ type SSOProvider struct { HasSecret bool AllowedDomains string AutoProvision bool + DefaultRoleID string Enabled bool } @@ -36,6 +37,7 @@ type SSOSettings struct { Providers []SSOProvider RedirectURL string LoginURL string + Roles []Role } templ SSOSettingsPage(p Page, me Me, s SSOSettings) { @@ -70,7 +72,7 @@ templ SSOSettingsPage(p Page, me Me, s SSOSettings) {
{ i18n.T(ctx, "sso.action.edit") }
- @ssoForm(pr, "put", "/org/sso/"+pr.ID) + @ssoForm(pr, s.Roles, "put", "/org/sso/"+pr.ID)