-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathauth.ts
More file actions
58 lines (54 loc) · 1.72 KB
/
auth.ts
File metadata and controls
58 lines (54 loc) · 1.72 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
import { cache } from 'react';
import { cookies } from 'next/headers';
import { fetchAuthSession } from 'aws-amplify/auth/server';
import { runWithAmplifyServerContext } from '@/lib/amplifyServerUtils';
import { prisma } from '@/lib/prisma';
/**
* Get the authenticated session without DB access.
* Use when only userId/email/accessToken is needed.
* Memoized per request via React cache().
*/
export const getAuthSession = cache(async () => {
const session = await runWithAmplifyServerContext({
nextServerContext: { cookies },
operation: (contextSpec) => fetchAuthSession(contextSpec),
});
if (session.userSub == null || session.tokens?.idToken == null || session.tokens?.accessToken == null) {
throw new Error('session not found');
}
const email = session.tokens.idToken.payload.email;
if (typeof email != 'string') {
throw new Error(`invalid email ${session.userSub}.`);
}
return {
userId: session.userSub,
email,
accessToken: session.tokens.accessToken.toString(),
};
});
/**
* Try to get the authenticated session, returning null on failure.
* Use in API Routes where you need to distinguish 401 from 500.
*/
export async function tryGetAuthSession() {
try {
return await getAuthSession();
} catch {
return null;
}
}
/**
* Get the authenticated session with the User record from DB.
* Memoized per request via React cache().
*/
export const getSessionWithUser = cache(async () => {
const auth = await getAuthSession();
const user = await prisma.user.findUnique({ where: { id: auth.userId } });
if (user == null) {
throw new UserNotFoundError(auth.userId);
}
return { ...auth, user };
});
export class UserNotFoundError {
constructor(public readonly userId: string) {}
}