-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
55 lines (39 loc) · 1.48 KB
/
auth.ts
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
import type { Decoded } from '@redwoodjs/api'
import { AuthenticationError, ForbiddenError } from '@redwoodjs/graphql-server'
import { bypassDb } from 'src/lib/db'
type AllowedRoles = string | string[] | undefined
interface RequireAuthArgs {
roles?: AllowedRoles
}
export const getCurrentUser = async (session: Decoded) => {
if (!session || typeof session.id !== 'string')
throw new AuthenticationError('Invalid session')
return bypassDb.user.findUnique({ where: { id: session.id } })
}
export const hasRole = (roles: AllowedRoles) => {
if (!isAuthenticated()) return false
const currentRoles = context.currentUser?.roles
if (typeof roles === 'string') {
if (typeof currentRoles === 'string') return currentRoles === roles
if (Array.isArray(currentRoles))
return currentRoles?.some((allowed) => roles === allowed)
}
if (Array.isArray(roles)) {
if (Array.isArray(currentRoles))
return currentRoles?.some((allowed) => roles.includes(allowed))
if (typeof currentRoles === 'string')
return roles.some((allowed) => currentRoles === allowed)
}
// roles not found
return false
}
export const isAuthenticated = () => {
return !!context.currentUser
}
export const requireAuth = ({ roles }: RequireAuthArgs) => {
console.log(context.currentUser)
if (!isAuthenticated())
throw new AuthenticationError("You don't have permission to do that.")
if (roles && !hasRole(roles))
throw new ForbiddenError("You don't have access to do that.")
}