-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathauthentication.tsx
112 lines (92 loc) · 3.22 KB
/
authentication.tsx
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
105
106
107
108
109
110
111
112
import { headers } from 'next/headers'
import { logger } from '@navikt/next-logger'
import { validateToken, getToken } from '@navikt/oasis'
import { redirect } from 'next/navigation'
import { isLocal } from '../utils/env'
import { raise } from '../utils/ts-utils'
import { fakeToken } from './fake-token'
import { getMembersOf } from './ms-graph'
/**
* Validates the wonderwall token according to nais.io. Should only actually redirect if the token has expired.
*/
export async function validateWonderwallToken(redirectPath: string): Promise<void> {
const requestHeaders = await headers()
if (isLocal) {
logger.warn('Is running locally, skipping RSC auth')
return
}
const token = getToken(requestHeaders)
if (!token) {
logger.warn('Found no token, redirecting to login, why was this not picked up by middleware.ts?')
redirect(`/oauth2/login?redirect=${redirectPath}`)
}
const validationResult = await validateToken(token)
if (!validationResult.ok) {
if (validationResult.errorType !== 'token expired') {
logger.error(
new Error(
`Invalid JWT token found (cause: ${validationResult.errorType} ${validationResult.error.message}, redirecting to login.`,
{ cause: validationResult.error },
),
)
}
redirect(`/oauth2/login?redirect=${redirectPath}`)
}
}
export function getUserToken(headers: Headers): string {
if (isLocal) return fakeToken
return (
headers.get('authorization')?.replace('Bearer ', '') ??
raise(new Error('Tried to get token, but header is missing'))
)
}
export async function getUser(): Promise<{
name: string
email: string
}> {
const token = getUserToken(await headers())
const jwt = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString('utf8'))
return {
name: jwt.name,
email: jwt.preferred_username,
}
}
export async function getUsersGroups(): Promise<string[]> {
const membersOf = await getMembersOf()
if ('error' in membersOf) {
throw new Error(
`Failed to get groups for user, MS responded with ${membersOf.status} ${membersOf.statusText}`,
{
cause: membersOf.error,
},
)
}
if (membersOf['@odata.nextLink'] != null) {
const user = await getUser()
logger.error(
`Whops! A user (${user.email}) has more than max page groups (${membersOf.value.length}), time to implement pagination?`,
)
}
return membersOf.value.map((group) => group.id)
}
export async function isUserLoggedIn(): Promise<boolean> {
try {
await getUser()
return true
} catch {
return false
}
}
export async function userHasAdGroup(groupId: string | null): Promise<boolean> {
if (!groupId) return false
const membersOf = await getMembersOf()
if ('error' in membersOf) {
throw new Error(
`Failed to get groups for user, MS responded with ${membersOf.status} ${membersOf.statusText}`,
{
cause: membersOf.error,
},
)
}
return membersOf.value.some((group) => group.id === groupId)
}