forked from jorge-menjivar/unsaged
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
43 lines (35 loc) · 1.21 KB
/
middleware.ts
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
import { withAuth } from 'next-auth/middleware';
import { get } from '@vercel/edge-config';
import { dockerEnvVarFix } from './utils/app/docker/envFix';
const getSecret = () => {
return dockerEnvVarFix(process.env.NEXTAUTH_SECRET);
};
const getEmailPatterns = async () => {
let patternsString = dockerEnvVarFix(process.env.NEXTAUTH_EMAIL_PATTERNS);
if (dockerEnvVarFix(process.env.EDGE_CONFIG))
patternsString = await get<string>('NEXTAUTH_EMAIL_PATTERNS');
return patternsString ? patternsString.split(',') : [];
};
export default withAuth({
callbacks: {
async authorized({ token }) {
if (!token?.email) {
return false;
} else {
const patterns = await getEmailPatterns();
if (patterns.length === 0) {
return true; // No patterns specified, allow access
}
const email = token.email.toLowerCase();
for (const pattern of patterns) {
const regex = new RegExp(pattern.trim());
if (email.match(regex)) {
return true; // Email matches one of the patterns, allow access
}
}
return false; // Email does not match any of the patterns, deny access
}
},
},
secret: getSecret(),
});