-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path007_CREATE_ORG_POLICY.sql
104 lines (100 loc) · 2.42 KB
/
007_CREATE_ORG_POLICY.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
-- Function is incompatible with current schema, see 021_FIX_PENDING_ORGANIZATION.sql for new definition
CREATE OR REPLACE FUNCTION user_has_pending_organization(user_email text)
RETURNS boolean AS $$
BEGIN
RETURN EXISTS (
SELECT 1
FROM organizations o
JOIN users u ON o.creator_id = u.id
WHERE u.email = user_email
AND o.state = 'PENDING'
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE POLICY "Allow authenticated users to create pending organizations"
ON public.organizations
FOR INSERT
WITH CHECK (
EXISTS (
SELECT 1
FROM users AS u
WHERE (u.email = (auth.jwt() ->> 'email'))
)
/* Don't allow users to create an organization if they already have one pending */
AND NOT user_has_pending_organization(auth.jwt() ->> 'email')
AND public.organizations.state = 'PENDING'
);
CREATE POLICY "Allow authenticated users to update pending organizations"
ON public.organizations
FOR UPDATE
USING (
EXISTS (
SELECT 1
FROM users AS u
INNER JOIN memberships as m ON (m.user_id = u.id)
WHERE (
u.email = (auth.jwt() ->> 'email')
AND m.role = 'CREATOR'
AND public.organizations.id = m.organization_id
)
)
AND public.organizations.state = 'PENDING'
)
WITH CHECK (
EXISTS (
SELECT 1
FROM users AS u
INNER JOIN memberships as m ON (m.user_id = u.id)
WHERE (
u.email = (auth.jwt() ->> 'email')
AND m.role = 'CREATOR'
AND public.organizations.id = m.organization_id
)
)
AND public.organizations.state = 'PENDING'
);
CREATE POLICY "Allow authenticated users to delete their own organization"
ON public.organizations
FOR DELETE
USING (
EXISTS (
SELECT 1
FROM users AS u
INNER JOIN memberships as m ON (m.user_id = u.id)
WHERE (
u.email = (auth.jwt() ->> 'email')
AND m.role = 'CREATOR'
AND public.organizations.id = m.organization_id
)
)
);
CREATE POLICY "Enable all access to site admins"
ON public.organizations
FOR ALL
TO authenticated
USING (
EXISTS (
SELECT 1
FROM permissions as p
INNER JOIN users as u ON (p.user_id = u.id)
WHERE (
u.email = auth.jwt() ->> 'email'
AND ( -- roles here
p.permission = 'ADMIN'
)
)
)
)
WITH CHECK (
EXISTS (
SELECT 1
FROM permissions as p
INNER JOIN users as u ON (p.user_id = u.id)
WHERE (
u.email = auth.jwt() ->> 'email'
AND ( -- roles here
p.permission = 'ADMIN'
)
)
)
);