Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Normalize emails to lowercase across auth

Richie McIlroy99af812b6061
diff --git a/apps/web/app/(org)/login/form.tsx b/apps/web/app/(org)/login/form.tsx
index 8348b136e..3d631c0f0 100644
--- a/apps/web/app/(org)/login/form.tsx
+++ b/apps/web/app/(org)/login/form.tsx
@@ -269,8 +269,9 @@ export function LoginForm() {
method: "email",
is_signup: !oauthError,
});
+ const normalizedEmail = email.trim().toLowerCase();
signIn("email", {
- email,
+ email: normalizedEmail,
redirect: false,
...(next && next.length > 0
? { callbackUrl: next }
@@ -283,10 +284,10 @@ export function LoginForm() {
setEmailSent(true);
setLastEmailSentTime(Date.now());
trackEvent("auth_email_sent", {
- email_domain: email.split("@")[1],
+ email_domain: normalizedEmail.split("@")[1],
});
const params = new URLSearchParams({
- email,
+ email: normalizedEmail,
...(next && { next }),
lastSent: Date.now().toString(),
});
@@ -421,7 +422,7 @@ const NormalLogin = ({
value={email}
disabled={emailSent || loading}
onChange={(e) => {
- setEmail(e.target.value);
+ setEmail(e.target.value.toLowerCase());
}}
/>
<MotionButton
diff --git a/apps/web/app/(org)/signup/form.tsx b/apps/web/app/(org)/signup/form.tsx
index 94bfc864e..7ec96287e 100644
--- a/apps/web/app/(org)/signup/form.tsx
+++ b/apps/web/app/(org)/signup/form.tsx
@@ -269,8 +269,9 @@ export function SignupForm() {
method: "email",
is_signup: true,
});
+ const normalizedEmail = email.trim().toLowerCase();
signIn("email", {
- email,
+ email: normalizedEmail,
redirect: false,
...(next && next.length > 0
? { callbackUrl: next }
@@ -283,10 +284,10 @@ export function SignupForm() {
setEmailSent(true);
setLastEmailSentTime(Date.now());
trackEvent("auth_email_sent", {
- email_domain: email.split("@")[1],
+ email_domain: normalizedEmail.split("@")[1],
});
const params = new URLSearchParams({
- email,
+ email: normalizedEmail,
...(next && { next }),
lastSent: Date.now().toString(),
});
@@ -435,7 +436,7 @@ const NormalSignup = ({
value={email}
disabled={emailSent || loading}
onChange={(e) => {
- setEmail(e.target.value);
+ setEmail(e.target.value.toLowerCase());
}}
/>
<MotionButton
diff --git a/apps/web/app/(org)/verify-otp/form.tsx b/apps/web/app/(org)/verify-otp/form.tsx
index 57253e074..4ecdc0c02 100644
--- a/apps/web/app/(org)/verify-otp/form.tsx
+++ b/apps/web/app/(org)/verify-otp/form.tsx
@@ -70,14 +70,15 @@ export function VerifyOTPForm({
}
};
+ const normalizedEmail = email.toLowerCase();
+
const handleVerify = useMutation({
mutationFn: async () => {
const otpCode = code.join("");
if (otpCode.length !== 6) throw "Please enter a complete 6-digit code";
- // shoutout https://github.com/buoyad/Tally/pull/14
const res = await fetch(
- `/api/auth/callback/email?email=${encodeURIComponent(email)}&token=${encodeURIComponent(otpCode)}&callbackUrl=${encodeURIComponent("/login-success")}`,
+ `/api/auth/callback/email?email=${encodeURIComponent(normalizedEmail)}&token=${encodeURIComponent(otpCode)}&callbackUrl=${encodeURIComponent("/login-success")}`,
);
if (!res.url.includes("/login-success")) {
@@ -115,7 +116,7 @@ export function VerifyOTPForm({
}
const result = await signIn("email", {
- email,
+ email: normalizedEmail,
redirect: false,
});
@@ -164,7 +165,7 @@ export function VerifyOTPForm({
Enter verification code
</h1>
<p className="text-sm text-gray-10">
- We sent a 6-digit code to {email}
+ We sent a 6-digit code to {normalizedEmail}
</p>
</div>
diff --git a/apps/web/app/(org)/verify-otp/page.tsx b/apps/web/app/(org)/verify-otp/page.tsx
index a31859b07..bf2c91e90 100644
--- a/apps/web/app/(org)/verify-otp/page.tsx
+++ b/apps/web/app/(org)/verify-otp/page.tsx
@@ -25,7 +25,7 @@ export default async function VerifyOTPPage(props: {
<div className="flex h-screen w-full items-center justify-center">
<Suspense fallback={null}>
<VerifyOTPForm
- email={searchParams.email}
+ email={searchParams.email?.toLowerCase() ?? ""}
next={searchParams.next}
lastSent={searchParams.lastSent}
/>
diff --git a/apps/web/app/s/[videoId]/_components/AuthOverlay.tsx b/apps/web/app/s/[videoId]/_components/AuthOverlay.tsx
index 6c3ea5599..c7f9cdfef 100644
--- a/apps/web/app/s/[videoId]/_components/AuthOverlay.tsx
+++ b/apps/web/app/s/[videoId]/_components/AuthOverlay.tsx
@@ -154,7 +154,7 @@ const StepOne = ({
setLoading(true);
signIn("email", {
- email,
+ email: email.trim().toLowerCase(),
redirect: false,
})
.then((res) => {
@@ -189,7 +189,7 @@ const StepOne = ({
value={email}
disabled={emailSent || loading}
onChange={(e) => {
- setEmail(e.target.value);
+ setEmail(e.target.value.toLowerCase());
}}
/>
</div>
diff --git a/apps/web/app/s/[videoId]/_components/OtpForm.tsx b/apps/web/app/s/[videoId]/_components/OtpForm.tsx
index 34d474389..ca359bd53 100644
--- a/apps/web/app/s/[videoId]/_components/OtpForm.tsx
+++ b/apps/web/app/s/[videoId]/_components/OtpForm.tsx
@@ -70,13 +70,15 @@ const OtpForm = ({
}
};
+ const normalizedEmail = email.toLowerCase();
+
const handleVerify = useMutation({
mutationFn: async () => {
const otpCode = code.join("");
if (otpCode.length !== 6) throw "Please enter a complete 6-digit code";
const res = await fetch(
- `/api/auth/callback/email?email=${encodeURIComponent(email)}&token=${encodeURIComponent(otpCode)}&callbackUrl=${encodeURIComponent("/login-success")}`,
+ `/api/auth/callback/email?email=${encodeURIComponent(normalizedEmail)}&token=${encodeURIComponent(otpCode)}&callbackUrl=${encodeURIComponent("/login-success")}`,
);
if (!res.url.includes("/login-success")) {
@@ -114,7 +116,7 @@ const OtpForm = ({
}
const result = await signIn("email", {
- email,
+ email: normalizedEmail,
redirect: false,
});
diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.ts
index c250a202f..f5b39b3a4 100644
--- a/packages/database/auth/auth-options.ts
+++ b/packages/database/auth/auth-options.ts
@@ -122,15 +122,15 @@ export const authOptions = (): NextAuthOptions => {
const allowedDomains = serverEnv().CAP_ALLOWED_SIGNUP_DOMAINS;
if (!allowedDomains) return true;
- // Get email from either user object (OAuth) or email parameter (email provider)
- const userEmail =
+ const rawEmail =
user?.email ||
(typeof email === "string"
? email
: typeof credentials?.email === "string"
? credentials.email
: null);
- if (!userEmail || typeof userEmail !== "string") return true;
+ if (!rawEmail || typeof rawEmail !== "string") return true;
+ const userEmail = rawEmail.toLowerCase();
const [existingUser] = await db()
.select()
@@ -172,7 +172,7 @@ export const authOptions = (): NextAuthOptions => {
image: users.image,
})
.from(users)
- .where(eq(users.email, token.email || ""))
+ .where(eq(users.email, (token.email || "").toLowerCase()))
.limit(1);
if (!dbUser) {
diff --git a/packages/database/auth/drizzle-adapter.ts b/packages/database/auth/drizzle-adapter.ts
index 7edaca2ea..e9a4cd338 100644
--- a/packages/database/auth/drizzle-adapter.ts
+++ b/packages/database/auth/drizzle-adapter.ts
@@ -18,6 +18,7 @@ import {
export function DrizzleAdapter(db: MySql2Database): Adapter {
return {
async createUser(userData: any) {
+ const normalizedEmail = (userData.email as string)?.toLowerCase() ?? "";
const userId = User.UserId.make(nanoId());
await db.transaction(async (tx) => {
const [pendingInvite] = await tx
@@ -25,7 +26,7 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
.from(organizationInvites)
.where(
and(
- eq(organizationInvites.invitedEmail, userData.email),
+ eq(organizationInvites.invitedEmail, normalizedEmail),
eq(organizationInvites.status, "pending"),
),
)
@@ -33,7 +34,7 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
await tx.insert(users).values({
id: userId,
- email: userData.email,
+ email: normalizedEmail,
emailVerified: userData.emailVerified,
name: userData.name,
image: userData.image,
@@ -78,7 +79,7 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
if (STRIPE_AVAILABLE()) {
const existingCustomers = await stripe().customers.list({
- email: userData.email,
+ email: normalizedEmail,
limit: 1,
});
@@ -94,7 +95,7 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
});
} else {
customer = await stripe().customers.create({
- email: userData.email,
+ email: normalizedEmail,
metadata: {
userId: row.id,
},
@@ -153,10 +154,11 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
return row ?? null;
},
async getUserByEmail(email) {
+ const normalizedEmail = email?.toLowerCase() ?? "";
const rows = await db
.select()
.from(users)
- .where(eq(users.email, email))
+ .where(eq(users.email, normalizedEmail))
.limit(1)
.catch((e) => {
throw e;
@@ -288,10 +290,12 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
await db.delete(sessions).where(eq(sessions.sessionToken, sessionToken));
},
async createVerificationToken(verificationToken) {
+ const normalizedIdentifier =
+ verificationToken.identifier?.toLowerCase() ?? "";
const existingTokens = await db
.select()
.from(verificationTokens)
- .where(eq(verificationTokens.identifier, verificationToken.identifier))
+ .where(eq(verificationTokens.identifier, normalizedIdentifier))
.limit(1);
if (existingTokens.length > 0) {
@@ -301,23 +305,19 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
token: verificationToken.token,
expires: verificationToken.expires,
})
- .where(
- eq(verificationTokens.identifier, verificationToken.identifier),
- );
+ .where(eq(verificationTokens.identifier, normalizedIdentifier));
return await db
.select()
.from(verificationTokens)
- .where(
- eq(verificationTokens.identifier, verificationToken.identifier),
- )
+ .where(eq(verificationTokens.identifier, normalizedIdentifier))
.limit(1)
.then((rows) => rows[0]);
}
await db.insert(verificationTokens).values({
expires: verificationToken.expires,
- identifier: verificationToken.identifier,
+ identifier: normalizedIdentifier,
token: verificationToken.token,
});
@@ -338,15 +338,18 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
.limit(1);
const row = rows[0];
if (!row) return null;
+ const normalizedIdentifier = identifier?.toLowerCase() ?? "";
+ const storedIdentifier = row.identifier?.toLowerCase() ?? "";
+ if (normalizedIdentifier !== storedIdentifier) return null;
await db
.delete(verificationTokens)
.where(
and(
eq(verificationTokens.token, token),
- eq(verificationTokens.identifier, identifier),
+ eq(verificationTokens.identifier, row.identifier),
),
);
- return row;
+ return { ...row, identifier: storedIdentifier };
},
};
}