(cookies: Record<string, string>)
| 78 | export const AUTH_COOKIE = `bulletproof_react_app_token`; |
| 79 | |
| 80 | export function requireAuth(cookies: Record<string, string>) { |
| 81 | try { |
| 82 | const encodedToken = cookies[AUTH_COOKIE] || Cookies.get(AUTH_COOKIE); |
| 83 | if (!encodedToken) { |
| 84 | return { error: 'Unauthorized', user: null }; |
| 85 | } |
| 86 | const decodedToken = decode(encodedToken) as { id: string }; |
| 87 | |
| 88 | const user = db.user.findFirst({ |
| 89 | where: { |
| 90 | id: { |
| 91 | equals: decodedToken.id, |
| 92 | }, |
| 93 | }, |
| 94 | }); |
| 95 | |
| 96 | if (!user) { |
| 97 | return { error: 'Unauthorized', user: null }; |
| 98 | } |
| 99 | |
| 100 | return { user: sanitizeUser(user) }; |
| 101 | } catch (err: any) { |
| 102 | return { error: 'Unauthorized', user: null }; |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | export function requireAdmin(user: any) { |
| 107 | if (user.role !== 'ADMIN') { |
no test coverage detected