-
Notifications
You must be signed in to change notification settings - Fork 464
Expand file tree
/
Copy pathpermissions.server.ts
More file actions
82 lines (79 loc) · 1.99 KB
/
Copy pathpermissions.server.ts
File metadata and controls
82 lines (79 loc) · 1.99 KB
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
import { data } from 'react-router'
import { cachified, lruCache } from './cache.server.ts'
import { requireUserId } from './auth.server.ts'
import { prisma } from './db.server.ts'
import { type PermissionString, parsePermissionString } from './user.ts'
const permissionCacheKey = (userId: string, permission: PermissionString) =>
`permission-check:${userId}:${permission}`
const roleCacheKey = (userId: string, name: string) =>
`role-check:${userId}:${name}`
export async function requireUserWithPermission(
request: Request,
permission: PermissionString,
) {
const userId = await requireUserId(request)
const permissionData = parsePermissionString(permission)
const allowed = await cachified({
key: permissionCacheKey(userId, permission),
cache: lruCache,
ttl: 1000 * 60 * 2,
async getFreshValue() {
const user = await prisma.user.findFirst({
select: { id: true },
where: {
id: userId,
roles: {
some: {
permissions: {
some: {
...permissionData,
access: permissionData.access
? { in: permissionData.access }
: undefined,
},
},
},
},
},
})
return Boolean(user)
},
})
if (!allowed) {
throw data(
{
error: 'Unauthorized',
requiredPermission: permissionData,
message: `Unauthorized: required permissions: ${permission}`,
},
{ status: 403 },
)
}
return userId
}
export async function requireUserWithRole(request: Request, name: string) {
const userId = await requireUserId(request)
const allowed = await cachified({
key: roleCacheKey(userId, name),
cache: lruCache,
ttl: 1000 * 60 * 2,
async getFreshValue() {
const user = await prisma.user.findFirst({
select: { id: true },
where: { id: userId, roles: { some: { name } } },
})
return Boolean(user)
},
})
if (!allowed) {
throw data(
{
error: 'Unauthorized',
requiredRole: name,
message: `Unauthorized: required role: ${name}`,
},
{ status: 403 },
)
}
return userId
}