File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed
Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -181,6 +181,39 @@ export const auth = betterAuth({
181181 if ( ctx . path . startsWith ( '/sign-up' ) && isTruthy ( env . DISABLE_REGISTRATION ) )
182182 throw new Error ( 'Registration is disabled, please contact your admin.' )
183183
184+ // Check email and domain whitelist for sign-in and sign-up
185+ if (
186+ ( ctx . path . startsWith ( '/sign-in' ) || ctx . path . startsWith ( '/sign-up' ) ) &&
187+ ( env . ALLOWED_LOGIN_EMAILS || env . ALLOWED_LOGIN_DOMAINS )
188+ ) {
189+ const requestEmail = ctx . body ?. email ?. toLowerCase ( )
190+
191+ if ( requestEmail ) {
192+ let isAllowed = false
193+
194+ // Check specific email whitelist
195+ if ( env . ALLOWED_LOGIN_EMAILS ) {
196+ const allowedEmails = env . ALLOWED_LOGIN_EMAILS . split ( ',' ) . map ( ( email ) =>
197+ email . trim ( ) . toLowerCase ( )
198+ )
199+ isAllowed = allowedEmails . includes ( requestEmail )
200+ }
201+
202+ // Check domain whitelist if not already allowed
203+ if ( ! isAllowed && env . ALLOWED_LOGIN_DOMAINS ) {
204+ const allowedDomains = env . ALLOWED_LOGIN_DOMAINS . split ( ',' ) . map ( ( domain ) =>
205+ domain . trim ( ) . toLowerCase ( )
206+ )
207+ const emailDomain = requestEmail . split ( '@' ) [ 1 ]
208+ isAllowed = emailDomain && allowedDomains . includes ( emailDomain )
209+ }
210+
211+ if ( ! isAllowed ) {
212+ throw new Error ( 'Access restricted. Please contact your administrator.' )
213+ }
214+ }
215+ }
216+
184217 return
185218 } ) ,
186219 } ,
Original file line number Diff line number Diff line change @@ -20,6 +20,8 @@ export const env = createEnv({
2020 BETTER_AUTH_URL : z . string ( ) . url ( ) , // Base URL for Better Auth service
2121 BETTER_AUTH_SECRET : z . string ( ) . min ( 32 ) , // Secret key for Better Auth JWT signing
2222 DISABLE_REGISTRATION : z . boolean ( ) . optional ( ) , // Flag to disable new user registration
23+ ALLOWED_LOGIN_EMAILS : z . string ( ) . optional ( ) , // Comma-separated list of allowed email addresses for login
24+ ALLOWED_LOGIN_DOMAINS : z . string ( ) . optional ( ) , // Comma-separated list of allowed email domains for login
2325 ENCRYPTION_KEY : z . string ( ) . min ( 32 ) , // Key for encrypting sensitive data
2426 INTERNAL_API_SECRET : z . string ( ) . min ( 32 ) , // Secret for internal API authentication
2527 SIM_AGENT_API_KEY : z . string ( ) . min ( 1 ) . optional ( ) , // Secret for internal sim agent API authentication
You can’t perform that action at this time.
0 commit comments