feat(store): add roles, role assignments, api tokens and invitations

Built-in roles are seeded with fixed ids and are read-only for every org.
Existing non-owner members receive the Viewer role.

Refs #6, #7, #8, #9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 00:49:35 +01:00
1 parent 15932db98a
commit ee09c497de
15 files changed
+1063 -13

No files matched your search

+66
View File
@@ -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;
@@ -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;
@@ -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;
+191
View File
@@ -0,0 +1,191 @@
// 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 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
}
+194
View File
@@ -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
}
+47
View File
@@ -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
@@ -24,6 +49,7 @@ type Org struct {
CreatedAt time.Time
UpdatedAt time.Time
RequireTotp bool
RequireSso bool
}
type RecoveryCode struct {
@@ -33,6 +59,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 +92,7 @@ type SsoProvider struct {
Enabled bool
CreatedAt time.Time
UpdatedAt time.Time
DefaultRoleID *uuid.UUID
}
type User struct {
+35 -4
View File
@@ -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
`
type CreateOrgParams struct {
@@ -32,6 +32,7 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro
&i.CreatedAt,
&i.UpdatedAt,
&i.RequireTotp,
&i.RequireSso,
)
return i, err
}
@@ -49,7 +50,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 FROM orgs WHERE id = $1
`
func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
@@ -62,12 +63,13 @@ func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
&i.CreatedAt,
&i.UpdatedAt,
&i.RequireTotp,
&i.RequireSso,
)
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 FROM orgs WHERE slug = $1
`
func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
@@ -80,12 +82,13 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
&i.CreatedAt,
&i.UpdatedAt,
&i.RequireTotp,
&i.RequireSso,
)
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 FROM orgs ORDER BY name
`
func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
@@ -104,6 +107,7 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
&i.CreatedAt,
&i.UpdatedAt,
&i.RequireTotp,
&i.RequireSso,
); err != nil {
return nil, err
}
@@ -114,3 +118,30 @@ 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, updated_at = now()
WHERE id = $1
RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso
`
type UpdateOrgPolicyParams struct {
ID uuid.UUID
RequireTotp bool
RequireSso bool
}
func (q *Queries) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error) {
row := q.db.QueryRow(ctx, updateOrgPolicy, arg.ID, arg.RequireTotp, arg.RequireSso)
var i Org
err := row.Scan(
&i.ID,
&i.Slug,
&i.Name,
&i.CreatedAt,
&i.UpdatedAt,
&i.RequireTotp,
&i.RequireSso,
)
return i, err
}
+27
View File
@@ -11,39 +11,66 @@ 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)
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)
}
+27
View File
@@ -0,0 +1,27 @@
-- 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;
+31
View File
@@ -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();
+5
View File
@@ -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, updated_at = now()
WHERE id = $1
RETURNING *;
+45
View File
@@ -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;
+3 -2
View File
@@ -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 *;
+290
View File
@@ -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
}
+16 -7
View File
@@ -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
}