-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrequireAuth.ts
More file actions
39 lines (33 loc) · 1.09 KB
/
requireAuth.ts
File metadata and controls
39 lines (33 loc) · 1.09 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
import type { H3Event } from 'h3'
type AuthSession = NonNullable<Awaited<ReturnType<typeof auth.api.getSession>>>
type AuthSessionWithActiveOrg = Omit<AuthSession, 'session'> & {
session: AuthSession['session'] & {
activeOrganizationId: string
}
}
/**
* Require an authenticated session with an active organization.
* Throws 401 if not authenticated, 403 if no active organization selected.
*
* Usage: `const session = await requireAuth(event)`
* Then: `const orgId = session.session.activeOrganizationId!`
*/
export async function requireAuth(event: H3Event) {
const session = await auth.api.getSession({
headers: event.headers,
})
if (!session) {
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' })
}
const activeOrganizationId = (session.session as { activeOrganizationId?: string }).activeOrganizationId
if (!activeOrganizationId) {
throw createError({ statusCode: 403, statusMessage: 'No active organization' })
}
return {
...session,
session: {
...session.session,
activeOrganizationId,
},
} as AuthSessionWithActiveOrg
}