Skip to content

Commit 94be1e1

Browse files
feat: login email whitelist (#197)
* feat: parse domain whitelist in next-auth signin callback * feat: add domain whitelist env var to example envs
1 parent 50868e8 commit 94be1e1

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

.env.dev.example

+4
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
HOST=localhost
2121
HTTP_PROTOCOL=https://
2222

23+
# Whitelist email domains that users are allowed to sign-in with, as a comma separated list.
24+
# Leave commented to allow all email domains
25+
#USER_EMAIL_DOMAIN_WHITELIST=mydomain.com,subdomain.mydomain.com
26+
2327
# Frontend dev
2428
NEXTAUTH_URL=https://localhost
2529
OAUTH_REDIRECT_URI=https://localhost

.env.example

+4
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@
2121
HOST=localhost
2222
HTTP_PROTOCOL=https://
2323

24+
# Whitelist email domains that users are allowed to sign-in with, as a comma separated list.
25+
# Leave commented to allow all email domains
26+
#USER_EMAIL_DOMAIN_WHITELIST=mydomain.com,subdomain.mydomain.com
27+
2428
# WARNING: Replace these with a cryptographically strong random values. You can use `openssl rand -hex 32` to generate these.
2529
NEXTAUTH_SECRET=82031b3760ac58352bb2d48fd9f32e9f72a0614343b669038139f18652ed1447
2630
SECRET_KEY=92d44efc4f9a4c0556cc67d2d033d3217829c263d5ab7d1954cf4b5bfd533e58

frontend/pages/api/auth/[...nextauth].ts

+17
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,23 @@ export const authOptions: NextAuthOptionsCallback = (_req, res) => {
5252
},
5353
providers,
5454
callbacks: {
55+
async signIn({ user }) {
56+
const domainWhitelist = process.env.USER_EMAIL_DOMAIN_WHITELIST?.split(',') || []
57+
58+
if (domainWhitelist.length) {
59+
let userEmail = user.email!
60+
61+
// Extract domain from email
62+
const domain = userEmail?.split('@')[1]
63+
64+
if (domainWhitelist.includes(domain)) {
65+
return true // Sign-in allowed
66+
} else {
67+
return false // Sign-in denied
68+
}
69+
}
70+
return true
71+
},
5572
async jwt({ token, user, account, profile }) {
5673
if (user) {
5774
if (account?.provider) {

0 commit comments

Comments
 (0)