@@ -4,6 +4,7 @@ import { betterAuth } from "better-auth";
44import { admin , bearer } from "better-auth/plugins" ;
55import { Kysely } from "kysely" ;
66import { D1Dialect } from "kysely-d1" ;
7+ import { sendVerificationEmail } from "./emailService" ;
78import type { Env } from "./types" ;
89
910export function createAuth ( env : Env ) {
@@ -14,13 +15,30 @@ export function createAuth(env: Env) {
1415 } ,
1516 basePath : "/api/auth" ,
1617 baseURL : {
17- allowedHosts : env . ALLOWED_HOSTS . split ( "," ) ,
18+ allowedHosts : authAllowedHosts ( env ) ,
1819 fallback : `https://${ env . ALLOWED_HOSTS . split ( "," ) [ 0 ] } ` ,
1920 protocol : "auto" ,
2021 } ,
2122 secret : env . AUTH_SECRET ,
2223 emailAndPassword : {
2324 enabled : true ,
25+ requireEmailVerification : true ,
26+ customSyntheticUser : ( { coreFields, additionalFields, id } ) => ( {
27+ ...coreFields ,
28+ role : "user" ,
29+ banned : false ,
30+ banReason : null ,
31+ banExpires : null ,
32+ ...additionalFields ,
33+ id,
34+ } ) ,
35+ } ,
36+ emailVerification : {
37+ autoSignInAfterVerification : true ,
38+ sendOnSignIn : true ,
39+ sendVerificationEmail : async ( { user, url } , request ) => {
40+ await sendVerificationEmail ( env , user . email , verificationPageUrl ( env , url , request ) ) ;
41+ } ,
2442 } ,
2543 socialProviders : {
2644 github : {
@@ -68,3 +86,22 @@ export function createAuth(env: Env) {
6886}
6987
7088export type Auth = ReturnType < typeof createAuth > ;
89+
90+ function authAllowedHosts ( env : Env ) : string [ ] {
91+ const hosts = env . ALLOWED_HOSTS . split ( "," ) ;
92+ if ( ! hosts . some ( ( host ) => host . startsWith ( "localhost" ) || host . startsWith ( "127.0.0.1" ) ) ) return hosts ;
93+ return [ ...hosts , "localhost:*" , "127.0.0.1:*" ] ;
94+ }
95+
96+ function verificationUrlForRequest ( env : Env , url : string , request ?: Request ) : string {
97+ if ( ! request ) return new URL ( url , `https://${ env . ALLOWED_HOSTS . split ( "," ) [ 0 ] } ` ) . toString ( ) ;
98+ const origin = new URL ( request . url ) . origin ;
99+ return new URL ( url , origin ) . toString ( ) ;
100+ }
101+
102+ function verificationPageUrl ( env : Env , url : string , request ?: Request ) : string {
103+ const resolved = new URL ( verificationUrlForRequest ( env , url , request ) ) ;
104+ const page = new URL ( "/auth/verify" , resolved . origin ) ;
105+ page . searchParams . set ( "token" , resolved . searchParams . get ( "token" ) || "" ) ;
106+ return page . toString ( ) ;
107+ }
0 commit comments