-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
193 lines (187 loc) Β· 7.31 KB
/
auth.ts
File metadata and controls
193 lines (187 loc) Β· 7.31 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
import prisma from './prisma.js';
import { admin, createAuthMiddleware, oneTimeToken } from 'better-auth/plugins';
import { CORS_ORIGIN_STRINGIFIED } from './utils/originConfig.js';
import { getNameFromEmail } from './helpers/email.js';
import type { GithubProfile, MicrosoftEntraIDProfile } from 'better-auth/social-providers';
import Logger from './utils/logger.js';
import { getIo, notify } from './socketIoServer.js';
import User from './models/User.js';
import { IoRoom } from './routes/socketEvents.js';
import { IoEvent, RecordType } from './routes/socketEventTypes.js';
import { adminAc, userAc } from 'better-auth/plugins/admin/access';
import { teacher } from './auth/permissions.js';
// If your Prisma file is located elsewhere, you can change the path
const COOKIE_PREFIX = process.env.APP_NAME || 'tdev';
const getNameFromMsftProfile = (profile: MicrosoftEntraIDProfile) => {
if (profile.name) {
const parts = profile.name.split(', ')[0]?.split(' ') || [];
if (parts.length > 1) {
const firstName = parts.pop()!;
const lastName = parts.join(' ');
return { firstName, lastName };
}
}
return getNameFromEmail(profile.email || profile.preferred_username);
};
const getNameFromGithubProfile = (profile: GithubProfile) => {
if (profile.name) {
const parts = profile.name.split(', ')[0]?.split(' ') || [];
if (parts.length > 1) {
const firstName = parts.pop()!;
const lastName = parts.join(' ');
return { firstName, lastName };
}
}
const { firstName, lastName } = getNameFromEmail(profile.email);
return { firstName: firstName ?? profile.login, lastName: lastName ?? profile.login };
};
const HAS_PROVIDER_GH = !!process.env.BETTER_AUTH_GITHUB_ID && !!process.env.BETTER_AUTH_GITHUB_SECRET;
const HAS_PROVIDER_MSFT = !!process.env.MSAL_CLIENT_ID && !!process.env.MSAL_CLIENT_SECRET;
export const auth = betterAuth({
user: {
additionalFields: {
firstName: { type: 'string', required: true, input: true },
lastName: { type: 'string', required: true, input: true }
},
deleteUser: {
enabled: false
}
},
account: {
encryptOAuthTokens: false,
accountLinking: {
enabled: true,
trustedProviders: ['github', 'microsoft', 'email-password'],
allowDifferentEmails: true
}
},
emailAndPassword: {
enabled: true,
disableSignUp: true,
revokeSessionsOnPasswordReset: true
},
socialProviders: {
...(HAS_PROVIDER_GH
? {
github: {
clientId: process.env.BETTER_AUTH_GITHUB_ID!,
clientSecret: process.env.BETTER_AUTH_GITHUB_SECRET!,
mapProfileToUser: (profile) => {
const name = getNameFromGithubProfile(profile);
return {
...profile,
firstName: name.firstName || '',
lastName: name.lastName || ''
};
}
}
}
: {}),
...(HAS_PROVIDER_MSFT
? {
microsoft: {
clientId: process.env.MSAL_CLIENT_ID as string,
clientSecret: process.env.MSAL_CLIENT_SECRET as string,
tenantId: process.env.MSAL_TENANT_ID || 'common', // Use 'common' for multi-tenant applications
authority: 'https://login.microsoftonline.com', // Authentication authority URL
prompt: 'select_account', // Forces account selection,
responseMode: 'query',
mapProfileToUser: (profile) => {
const email = (profile.email || profile.preferred_username)?.toLowerCase();
const name = getNameFromMsftProfile(profile);
return {
id: profile.oid,
email: email,
firstName: name.firstName || '',
lastName: name.lastName || ''
// You can extract and map other fields as needed
};
}
}
}
: {})
},
trustedOrigins: CORS_ORIGIN_STRINGIFIED,
database: prismaAdapter(prisma, { provider: 'postgresql', usePlural: false }),
advanced: {
cookiePrefix: COOKIE_PREFIX,
crossSubDomainCookies: {
enabled: true
},
cookies: process.env.NETLIFY_PROJECT_NAME
? {
session_token: {
attributes: {
sameSite: 'none',
secure: true
}
}
}
: undefined,
database: { generateId: false, useNumberId: false }
},
hooks: {
after: createAuthMiddleware(async (ctx) => {
const userId = ctx.body?.userId as string | undefined;
switch (ctx.path) {
case '/admin/update-user':
case '/admin/unban-user':
case '/admin/set-user-password':
if (userId) {
const user = await User.findModel(userId);
if (user) {
notify({
to: [user.id, IoRoom.ADMIN],
event: IoEvent.CHANGED_RECORD,
message: {
type: RecordType.User,
record: user
}
});
}
}
break;
case '/admin/ban-user':
if (userId) {
const user = await User.findModel(userId);
if (user) {
notify({
to: [IoRoom.ADMIN],
event: IoEvent.CHANGED_RECORD,
message: {
type: RecordType.User,
record: user
}
});
getIo().to(user.id).emit(IoEvent.ACTION, 'nav-reload');
}
}
default:
return;
}
})
},
plugins: [
oneTimeToken(),
admin({
roles: {
admin: adminAc,
teacher: teacher,
student: userAc
},
defaultRole: 'student',
adminRoles: ['teacher', 'admin']
})
],
logger: {
level: 'info',
log: (level, message, ...args) => {
// Custom logging implementation
Logger.info(
`[${level}] ${message}: ${args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(', ')}`
);
}
}
});