-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathroute.ts
More file actions
70 lines (61 loc) · 1.99 KB
/
Copy pathroute.ts
File metadata and controls
70 lines (61 loc) · 1.99 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
59
60
61
62
63
64
65
66
67
68
69
70
import { authkit, refreshSession } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';
import { workos } from '../api/workos';
import { NextRequest } from 'next/server';
export const GET = async (request: NextRequest) => {
let { session } = await authkit(request);
if (!session || !session.user) {
return redirect('/pricing');
}
// If this is a new user who just subscribed, their role won't have been updated
// so we need to refresh the session to get the updated role
if (session && !session.role) {
// Get the user's organization memberships so we can extract the org ID
const oms = await workos.userManagement.listOrganizationMemberships({
userId: session.user.id,
});
if (oms.data.length > 0) {
session = await refreshSession({
organizationId: oms.data[0].organizationId,
ensureSignedIn: true,
});
}
}
if (session && session.organizationId) {
// Create a new audit log entry
await workos.auditLogs.createEvent(session.organizationId, {
action: 'user.logged_in',
occurredAt: new Date(),
actor: {
type: 'user',
id: session.user?.id,
name: session.user?.firstName + ' ' + session.user?.lastName,
metadata: {
role: session.role as string,
},
},
targets: [
{
type: 'user',
id: session.user?.id,
name: session.user?.firstName + ' ' + session.user?.lastName,
},
],
context: {
location: request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown',
},
metadata: {},
});
}
const role = session?.role;
// Redirect based on the user's role
switch (role) {
case 'admin':
return redirect('/dashboard');
case 'member':
return redirect('/product');
default:
// If there's no role that means the user hasn't subscribed yet, so redirect them to the pricing page
return redirect('/pricing');
}
};