Last active
June 26, 2023 06:46
-
-
Save 342b45/df45d8a5267a136402bad6a6ec664bad to your computer and use it in GitHub Desktop.
Magic Link Implementation using lucia auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.post("signin/email", async (c) => { | |
const env = c.env as Env; | |
const { email } = formSchema.parse(await c.req.json()); | |
const token = await generateEmailVerificationToken(email, env); | |
try { | |
const data = await sendEmailVerificationLink(email, token, env); | |
return new Response(JSON.stringify(data), { | |
status: 200, | |
}); | |
} catch (error) { | |
return new Response(null, { | |
status: 500, | |
}); | |
} | |
}); | |
app.get("callback/email/:token", async (c) => { | |
const { token } = c.req.param(); | |
const env = c.env as Env; | |
const headers = new Headers(); | |
const db = initDB(env).drizzleClient; | |
const authRequest = auth(env).handleRequest(c.req.raw, headers); | |
const email = await validateEmailVerificationToken(token, env); | |
const { existingUser, createUser, createKey } = await providerUserAuth( | |
auth(env), | |
"email", | |
email!, | |
); | |
try { | |
let currentUser: User | undefined; | |
if (!existingUser) { | |
const dbUser = await db.query.users | |
.findFirst({ | |
where: eq(users.email, email!), | |
}) | |
.execute(); | |
currentUser = { | |
userId: dbUser?.id as string, | |
email: dbUser?.email as string, | |
name: dbUser?.name as string, | |
image: dbUser?.image as string, | |
}; | |
if (dbUser) { | |
await createKey(dbUser.id); | |
} | |
} | |
// If existing user, else create a new user | |
const user = existingUser ? existingUser : currentUser; | |
// Create a new session | |
const session = await auth(env).createSession(user?.userId as string); | |
// Set the session in the request | |
authRequest.setSession(session); | |
// Redirect to the home | |
headers.set("Location", "/"); | |
return new Response(null, { | |
headers, | |
status: 302, | |
}); | |
} catch (error) { | |
if ( | |
error instanceof LuciaError && | |
error.message === `AUTH_INVALID_USER_ID` | |
) { | |
const user = await createUser({ | |
name: "", | |
email: email!, | |
image: `https://source.boringavatars.com/marble/120/${email}`, | |
}); | |
// Create a new session | |
const session = await auth(env).createSession(user.userId); | |
// Set the session in the request | |
authRequest.setSession(session); | |
// Redirect to the home | |
headers.set("Location", "/"); | |
return new Response(null, { | |
headers, | |
status: 302, | |
}); | |
} | |
console.error(error); | |
return new Response(null, { | |
status: 500, | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment