Repository navigation
Expand file tree
/
Copy pathauth.ts
More file actions
102 lines (93 loc) · 2.93 KB
/
Copy pathauth.ts
File metadata and controls
102 lines (93 loc) · 2.93 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
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
import NextAuth from "next-auth";
import EntraIDProvider from "next-auth/providers/microsoft-entra-id";
import { getUserProfile } from "@/lib/profile";
import { PostPermissionsResponse } from "./app/api/permissions/route";
import { getEnv } from "./lib/utils";
import { UserRole } from "./types";
const baseURL = process.env.APP_URL ?? "http://127.0.0.1:3000";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
EntraIDProvider({
clientId: getEnv("AUTH_MICROSOFT_ENTRA_ID_ID"),
clientSecret: getEnv("AUTH_MICROSOFT_ENTRA_ID_SECRET"),
issuer: `https://login.microsoftonline.com/${getEnv("AUTH_MICROSOFT_ENTRA_ID_TENANT_ID")}/v2.0`,
authorization: {
params: {
scope: "openid email profile User.Read",
},
},
}),
],
callbacks: {
// Check if user is on official roster and authorized to access
async signIn({ profile }) {
if (!profile?.email) {
console.error("Email does not exist in profile");
return false;
}
const isAuthorized = await fetch(
`${baseURL}/api/permissions`,
{
method: "POST",
body: JSON.stringify({
email: profile.email,
}),
},
)
.then((response) => response.json())
.then((response) => response.isAuthorized);
console.debug(isAuthorized ? "User authorized" : "User not authorized");
return isAuthorized;
},
// Add extra properties to the JWT token
async jwt({ token, user, account, profile }) {
if (user) {
// Fetch additional user data from Microsoft Graph
const graphProfile = await getUserProfile(
account?.access_token as string,
);
// Get user role
const rosterData = await fetch(
`${baseURL}/api/permissions`,
{
method: "POST",
body: JSON.stringify({
email: user.email,
}),
},
)
.then((response) => response.json())
.then((response: PostPermissionsResponse) => {
return {
role: response?.data?.role,
branch: response?.data?.branch,
team: response?.data?.team,
position: response?.data?.position,
};
});
// Enrich token with user details
token.user = {
name: user.name,
email: user.email,
image: user.image,
nuid: graphProfile.nuid,
role: rosterData?.role || UserRole.MEMBER,
branch: rosterData?.branch,
team: rosterData?.team,
position: rosterData?.position
};
}
return token;
},
session({ session, token }) {
if (!token.user) throw new Error("No user data");
// Add properties to session
session.user = token.user as any;
return session;
},
},
pages: {
signIn: "/auth/login",
error: "/auth/error",
},
});