Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(auth): ask for the emailed code after sign-up

spacesdrive396d94f383c7
diff --git a/frontend/src/context/AuthContext.tsx b/frontend/src/context/AuthContext.tsx
index 404e4d1..5fd3350 100644
--- a/frontend/src/context/AuthContext.tsx
+++ b/frontend/src/context/AuthContext.tsx
@@ -10,6 +10,8 @@ export interface AuthContextValue {
user: User | null;
signIn: (email: string, password: string) => ReturnType<Auth['signInWithPassword']>;
signUp: (email: string, password: string) => ReturnType<Auth['signUp']>;
+ verifySignUpCode: (email: string, code: string) => ReturnType<Auth['verifyOtp']>;
+ resendSignUpCode: (email: string) => ReturnType<Auth['resend']>;
signInWithGoogle: (idToken: string, nonce: string) => ReturnType<Auth['signInWithIdToken']>;
signOut: () => ReturnType<Auth['signOut']>;
}
@@ -33,6 +35,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const signUp = (email: string, password: string) =>
supabase.auth.signUp({ email, password });
+ // the code from the confirmation email; a correct one confirms the address and signs the user in
+ const verifySignUpCode = (email: string, code: string) =>
+ supabase.auth.verifyOtp({ email, token: code, type: 'signup' });
+
+ const resendSignUpCode = (email: string) =>
+ supabase.auth.resend({ type: 'signup', email });
+
// the raw nonce lets supabase confirm the google token came from this sign-in
const signInWithGoogle = (idToken: string, nonce: string) =>
supabase.auth.signInWithIdToken({ provider: 'google', token: idToken, nonce });
@@ -40,7 +49,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const signOut = () => supabase.auth.signOut();
return (
- <AuthContext.Provider value={{ session, user: session?.user ?? null, signIn, signUp, signInWithGoogle, signOut }}>
+ <AuthContext.Provider value={{ session, user: session?.user ?? null, signIn, signUp, verifySignUpCode, resendSignUpCode, signInWithGoogle, signOut }}>
{children}
</AuthContext.Provider>
);
diff --git a/frontend/src/lib/authErrors.ts b/frontend/src/lib/authErrors.ts
new file mode 100644
index 0000000..5115116
--- /dev/null
+++ b/frontend/src/lib/authErrors.ts
@@ -0,0 +1,42 @@
+// the parts of a Supabase AuthError the login page reads
+export interface AuthErrorLike {
+ message: string;
+ status?: number;
+ code?: string;
+}
+
+export interface EmailErrorNotice {
+ message: string;
+ // true when no more codes can be emailed today, so Google sign-in is the way in
+ emailLimitReached: boolean;
+}
+
+const WAIT_SECONDS = /\d+\s+seconds?/i;
+
+const LIMIT_WITH_GOOGLE = 'Twiligent has sent all the verification emails it can today. Sign in with Google instead, or try again tomorrow.';
+const WRONG_CODE = 'The code is wrong or has expired. Check it, or send a new one.';
+const LIMIT_WITHOUT_GOOGLE = 'Twiligent has sent all the verification emails it can today. Try again tomorrow.';
+
+// Supabase's own email limit and the Worker's daily cap both answer 429; the per-address cap and the short wait between codes do too,
+// but those messages already say what to do and Google would not help
+export function emailErrorNotice(error: AuthErrorLike, googleAvailable: boolean): EmailErrorNotice {
+ const limitMessage = googleAvailable ? LIMIT_WITH_GOOGLE : LIMIT_WITHOUT_GOOGLE;
+ if (error.code === 'otp_expired') return { message: WRONG_CODE, emailLimitReached: false };
+ if (error.status !== 429 || WAIT_SECONDS.test(error.message)) return { message: error.message, emailLimitReached: false };
+ if (error.code === 'over_email_send_rate_limit' || /sign in with google/i.test(error.message)) {
+ return { message: limitMessage, emailLimitReached: true };
+ }
+ return { message: error.message, emailLimitReached: false };
+}
+
+// Supabase answers a sign-up for an address that already has an account with a user and no identities, and sends nothing
+export function isExistingAccount(user: { identities?: unknown[] } | null | undefined): boolean {
+ return !!user && Array.isArray(user.identities) && user.identities.length === 0;
+}
+
+export const CODE_LENGTH = 6;
+
+// people paste codes with spaces or dashes; only the digits count
+export function cleanCode(value: string): string {
+ return value.replace(/\D/g, '').slice(0, CODE_LENGTH);
+}
diff --git a/frontend/src/pages/Login.tsx b/frontend/src/pages/Login.tsx
index 9b81792..d4f30bc 100644
--- a/frontend/src/pages/Login.tsx
+++ b/frontend/src/pages/Login.tsx
@@ -1,16 +1,20 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import type { FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
-import { BookOpen } from 'lucide-react';
+import { BookOpen, MailWarning } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { Button } from '@/components/ui/button';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Logo } from '@/components/brand/Logo';
import GoogleSignInButton from '@/components/GoogleSignInButton';
import type { GoogleButtonText } from '@/lib/googleIdentity';
import { GOOGLE_CLIENT_ID } from '@/lib/googleIdentity';
+import { emailErrorNotice, isExistingAccount } from '@/lib/authErrors';
+import type { AuthErrorLike } from '@/lib/authErrors';
import LoginBrandPanel from './LoginBrandPanel';
import LoginForm from './LoginForm';
+import LoginCodeForm from './LoginCodeForm';
import { LOGIN_COPY, PRIVACY_URL } from './loginCopy';
import type { LoginMode } from './loginCopy';
@@ -37,38 +41,109 @@ function GoogleOption({ text, onCredential }: GoogleOptionProps) {
}
export default function Login() {
- const { signIn, signUp, signInWithGoogle } = useAuth();
+ const { signIn, signUp, verifySignUpCode, resendSignUpCode, signInWithGoogle } = useAuth();
const navigate = useNavigate();
const [mode, setMode] = useState<LoginMode>('login');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
+ const [code, setCode] = useState('');
// kept here, above the keyed panel, so only the mode switch link resets it
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
+ const [resending, setResending] = useState(false);
+ const [resendIn, setResendIn] = useState(0);
+ const [emailLimitMessage, setEmailLimitMessage] = useState<string | null>(null);
const isLogin = mode === 'login';
const copy = LOGIN_COPY[mode];
+ useEffect(() => {
+ if (resendIn <= 0) return;
+ const timer = setTimeout(() => setResendIn(seconds => seconds - 1), 1000);
+ return () => clearTimeout(timer);
+ }, [resendIn]);
+
+ // Supabase allows one code a minute per address, so the button waits as long after each send
+ function openCodeStep(justSent: boolean) {
+ setCode('');
+ setResendIn(justSent ? 60 : 0);
+ setMode('verify');
+ }
+
+ function showEmailError(prefix: string, err: unknown) {
+ const notice = emailErrorNotice(err as AuthErrorLike, !!GOOGLE_CLIENT_ID);
+ // the warning above the Google button says it already
+ if (notice.emailLimitReached) setEmailLimitMessage(notice.message);
+ else toast.error(`${prefix} ${notice.message}`);
+ }
+
+ async function submitLogin() {
+ const { error } = await signIn(email, password);
+ if (error?.code === 'email_not_confirmed') {
+ openCodeStep(false);
+ toast.info('Confirm your email to sign in. Enter the code from your sign-up email, or send a new one.');
+ return;
+ }
+ if (error) throw error;
+ navigate('/');
+ }
+
+ async function submitSignUp() {
+ const { data, error } = await signUp(email, password);
+ if (error) throw error;
+ // email confirmation is off in Supabase, so the account is ready
+ if (data.session) {
+ navigate('/');
+ return;
+ }
+ if (isExistingAccount(data.user)) {
+ toast.error('This email already has an account. Sign in instead.');
+ setMode('login');
+ return;
+ }
+ openCodeStep(true);
+ }
+
+ async function submitCode() {
+ const { error } = await verifySignUpCode(email, code);
+ if (error) throw error;
+ toast.success('Email confirmed');
+ navigate('/');
+ }
+
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
try {
- if (isLogin) {
- const { error } = await signIn(email, password);
- if (error) throw error;
- navigate('/');
- } else {
- const { error } = await signUp(email, password);
- if (error) throw error;
- toast.success('Account created. Sign in to continue.');
- setMode('login');
- }
+ if (mode === 'verify') await submitCode();
+ else if (isLogin) await submitLogin();
+ else await submitSignUp();
} catch (err) {
- toast.error(isLogin ? `Couldn't sign in. ${(err as Error).message}` : `Couldn't create the account. ${(err as Error).message}`);
+ const prefix = { login: "Couldn't sign in.", signup: "Couldn't create the account.", verify: "Couldn't confirm the email." }[mode];
+ showEmailError(prefix, err);
} finally {
setLoading(false);
}
}
+ async function handleResend() {
+ setResending(true);
+ try {
+ const { error } = await resendSignUpCode(email);
+ if (error) throw error;
+ setResendIn(60);
+ toast.success('New code sent');
+ } catch (err) {
+ showEmailError("Couldn't send a new code.", err);
+ } finally {
+ setResending(false);
+ }
+ }
+
+ function switchMode() {
+ setMode(mode === 'signup' ? 'login' : 'signup');
+ setShowPassword(false);
+ }
+
async function handleGoogleCredential(idToken: string, nonce: string) {
setLoading(true);
try {
@@ -100,26 +175,48 @@ export default function Login() {
<p className="text-sm text-ink-muted">{copy.lead}</p>
</div>
- {GOOGLE_CLIENT_ID && <GoogleOption text={copy.google} onCredential={handleGoogleCredential} />}
-
- <LoginForm
- isLogin={isLogin}
- copy={copy}
- email={email}
- password={password}
- onEmailChange={setEmail}
- onPasswordChange={setPassword}
- showPassword={showPassword}
- onTogglePassword={() => setShowPassword(visible => !visible)}
- loading={loading}
- onSubmit={handleSubmit}
- />
+ {emailLimitMessage && !isLogin && (
+ <Alert variant="warning">
+ <MailWarning />
+ <AlertTitle>Email codes are paused until tomorrow</AlertTitle>
+ <AlertDescription>{emailLimitMessage}</AlertDescription>
+ </Alert>
+ )}
+
+ {GOOGLE_CLIENT_ID && (mode !== 'verify' || emailLimitMessage) && <GoogleOption text={copy.google} onCredential={handleGoogleCredential} />}
+
+ {mode === 'verify' ? (
+ <LoginCodeForm
+ copy={copy}
+ email={email}
+ code={code}
+ onCodeChange={setCode}
+ loading={loading}
+ onSubmit={handleSubmit}
+ resendIn={resendIn}
+ resending={resending}
+ onResend={handleResend}
+ />
+ ) : (
+ <LoginForm
+ isLogin={isLogin}
+ copy={copy}
+ email={email}
+ password={password}
+ onEmailChange={setEmail}
+ onPasswordChange={setPassword}
+ showPassword={showPassword}
+ onTogglePassword={() => setShowPassword(visible => !visible)}
+ loading={loading}
+ onSubmit={handleSubmit}
+ />
+ )}
<p className="text-center text-sm text-ink-muted">
{copy.switchPrompt}{' '}
<button
type="button"
- onClick={() => { setMode(isLogin ? 'signup' : 'login'); setShowPassword(false); }}
+ onClick={switchMode}
className="rounded-sm font-medium text-brand-text underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
>
{copy.switchAction}
diff --git a/frontend/src/pages/LoginCodeForm.tsx b/frontend/src/pages/LoginCodeForm.tsx
new file mode 100644
index 0000000..81b4e14
--- /dev/null
+++ b/frontend/src/pages/LoginCodeForm.tsx
@@ -0,0 +1,58 @@
+import type { FormEvent } from 'react';
+import { ArrowRight, RotateCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Spinner } from '@/components/ui/spinner';
+import { FieldRow } from '@/components/DetailPanel';
+import { CODE_LENGTH, cleanCode } from '@/lib/authErrors';
+import type { LoginCopy } from './loginCopy';
+
+export interface LoginCodeFormProps {
+ copy: LoginCopy;
+ email: string;
+ code: string;
+ onCodeChange: (value: string) => void;
+ loading: boolean;
+ onSubmit: (e: FormEvent<HTMLFormElement>) => void;
+ // seconds until another code may be sent; 0 when it may be sent now
+ resendIn: number;
+ resending: boolean;
+ onResend: () => void;
+}
+
+export default function LoginCodeForm({
+ copy, email, code, onCodeChange, loading, onSubmit, resendIn, resending, onResend,
+}: LoginCodeFormProps) {
+ return (
+ <form onSubmit={onSubmit} className="flex flex-col gap-4">
+ <FieldRow label="Verification code" htmlFor="code">
+ <Input
+ id="code"
+ className="h-(--control-h-lg) text-center font-mono text-lg tracking-[0.4em]"
+ placeholder="000000"
+ value={code}
+ onChange={e => onCodeChange(cleanCode(e.target.value))}
+ required
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ pattern={`\\d{${CODE_LENGTH}}`}
+ maxLength={CODE_LENGTH + 4}
+ aria-describedby="code-help"
+ autoFocus
+ />
+ </FieldRow>
+ <p id="code-help" className="text-sm text-ink-muted">
+ Sent to <span className="font-medium text-ink">{email}</span>. If it has not arrived, check your spam folder.
+ </p>
+ <Button type="submit" size="lg" className="mt-2 w-full" disabled={loading || code.length !== CODE_LENGTH}>
+ {loading && <Spinner className="size-4" />}
+ {loading ? copy.busy : copy.submit}
+ {!loading && <ArrowRight data-icon="inline-end" />}
+ </Button>
+ <Button type="button" variant="ghost" size="sm" className="self-center" onClick={onResend} disabled={resending || resendIn > 0}>
+ {resending ? <Spinner className="size-4" /> : <RotateCw data-icon="inline-start" />}
+ {resendIn > 0 ? `Send a new code in ${resendIn}s` : 'Send a new code'}
+ </Button>
+ </form>
+ );
+}
diff --git a/frontend/src/pages/loginCopy.ts b/frontend/src/pages/loginCopy.ts
index da8bab1..82abb0b 100644
--- a/frontend/src/pages/loginCopy.ts
+++ b/frontend/src/pages/loginCopy.ts
@@ -2,7 +2,8 @@ import type { GoogleButtonText } from '@/lib/googleIdentity';
export const PRIVACY_URL = 'https://blog.ujjwal.fyi/privacy/';
-export type LoginMode = 'login' | 'signup';
+// verify is the code step after sign-up, or after signing in with an email that is not confirmed yet
+export type LoginMode = 'login' | 'signup' | 'verify';
export interface LoginCopy {
title: string;
@@ -33,4 +34,13 @@ export const LOGIN_COPY: Record<LoginMode, LoginCopy> = {
switchAction: 'Sign in',
google: 'signup_with',
},
+ verify: {
+ title: 'Check your email',
+ lead: 'Enter the 6-digit code we emailed you to confirm your address.',
+ submit: 'Confirm email',
+ busy: 'Confirming',
+ switchPrompt: 'Wrong address?',
+ switchAction: 'Start again',
+ google: 'continue_with',
+ },
};
diff --git a/frontend/tests/lib/authErrors.test.ts b/frontend/tests/lib/authErrors.test.ts
new file mode 100644
index 0000000..d3651cd
--- /dev/null
+++ b/frontend/tests/lib/authErrors.test.ts
@@ -0,0 +1,52 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { cleanCode, emailErrorNotice, isExistingAccount } from '../../src/lib/authErrors.ts';
+
+const WORKER_LIMIT = 'Twiligent has sent all the verification emails it can today. Sign in with Google instead, or try again tomorrow.';
+
+test('the daily cap points to Google when the Google button is on the page', () => {
+ assert.deepEqual(emailErrorNotice({ message: WORKER_LIMIT, status: 429 }, true), { message: WORKER_LIMIT, emailLimitReached: true });
+ assert.deepEqual(emailErrorNotice({ message: WORKER_LIMIT, status: 429 }, false), {
+ message: 'Twiligent has sent all the verification emails it can today. Try again tomorrow.',
+ emailLimitReached: true,
+ });
+});
+
+test('Supabase\'s own email limit reads the same way', () => {
+ const notice = emailErrorNotice({ message: 'email rate limit exceeded', status: 429, code: 'over_email_send_rate_limit' }, true);
+ assert.deepEqual(notice, { message: WORKER_LIMIT, emailLimitReached: true });
+});
+
+test('a short wait between codes and the per-address cap keep their own messages', () => {
+ const wait = { message: 'For security purposes, you can only request this after 42 seconds.', status: 429, code: 'over_email_send_rate_limit' };
+ assert.deepEqual(emailErrorNotice(wait, true), { message: wait.message, emailLimitReached: false });
+ const perAddress = { message: 'This address has received the most codes allowed today. Use the latest code you received, or try again tomorrow.', status: 429 };
+ assert.deepEqual(emailErrorNotice(perAddress, true), { message: perAddress.message, emailLimitReached: false });
+});
+
+test('a wrong or expired code says what to do next', () => {
+ assert.deepEqual(emailErrorNotice({ message: 'Token has expired or is invalid', status: 403, code: 'otp_expired' }, true), {
+ message: 'The code is wrong or has expired. Check it, or send a new one.',
+ emailLimitReached: false,
+ });
+});
+
+test('other errors pass through', () => {
+ assert.deepEqual(emailErrorNotice({ message: 'Password should be at least 6 characters.', status: 422 }, true), {
+ message: 'Password should be at least 6 characters.',
+ emailLimitReached: false,
+ });
+});
+
+test('a sign-up answer with no identities means the address already has an account', () => {
+ assert.equal(isExistingAccount({ identities: [] }), true);
+ assert.equal(isExistingAccount({ identities: [{ provider: 'email' }] }), false);
+ assert.equal(isExistingAccount({}), false);
+ assert.equal(isExistingAccount(null), false);
+});
+
+test('a pasted code keeps its first six digits only', () => {
+ assert.equal(cleanCode(' 123-456 '), '123456');
+ assert.equal(cleanCode('12345678'), '123456');
+ assert.equal(cleanCode('abc'), '');
+});