Skip to content

Commit 63567d0

Browse files
apphelper: sign in with an emailed code (#158)
Login adds an Email me a code option: request a 6-digit code, then sign in with it through /users/loginWithCode; two-factor accounts still get the authenticator step.
1 parent 9b47fc7 commit 63567d0

7 files changed

Lines changed: 282 additions & 4 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@churchapps/apphelper": minor
3+
---
4+
5+
Login: add "Email me a code" sign-in. The member enters their email, gets a 6-digit code, and is signed in with it (two-factor accounts still get the authenticator step). Needs the Api `/membership/users/requestLoginCode` and `/membership/users/loginWithCode` endpoints.

‎apphelper/public/locales/en.json‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,9 @@
267267
"continueMicrosoft": "Continue with Microsoft",
268268
"createAccount": "Create an Account",
269269
"email": "Email",
270+
"emailCode": "Email me a code",
271+
"emailCodeInstructions": "Enter your email and we'll send you a 6-digit code to sign in.",
272+
"emailCodeTitle": "Sign In with a Code",
270273
"enterCode": "Enter Verification Code",
271274
"enterCodeInstructions": "Enter the 6-digit code we just emailed you.",
272275
"expiredLink": "The current link is expired.",
@@ -289,12 +292,15 @@
289292
"resetInstructions": "Enter your email address to request a password reset.",
290293
"resetPassword": "Reset Password",
291294
"resetSent": "Password reset email sent!",
295+
"sendCode": "Send Code",
292296
"setPassword": "Set Password",
293297
"signIn": "Sign In",
294298
"signInTitle": "Please Sign In",
299+
"usePassword": "Sign in with password",
295300
"validate": {
296301
"code": "Please enter the 6-digit code.",
297302
"email": "Please enter a valid email address.",
303+
"emailCode": "That code didn't work or has expired. Please try again or request a new code.",
298304
"firstName": "Please enter your first name.",
299305
"invalid": "Invalid login. Please check your email or password.",
300306
"lastName": "Please enter your last name.",

‎apphelper/src/login/LoginPage.tsx‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { Alert, PaperProps } from "@mui/material";
1313
import { Login } from "./components/Login";
1414
import { LoginSetPassword } from "./components/LoginSetPassword";
1515
import { MfaCode } from "./components/MfaCode";
16+
import { EmailCode } from "./components/EmailCode";
1617
import ga4 from "react-ga4";
1718

1819
interface Props {
@@ -55,6 +56,7 @@ const LoginPageContent: React.FC<Props> = ({ showLogo = true, loginContainerCssP
5556
const [errors, setErrors] = React.useState<string[]>([]);
5657
const [cookies, setCookie] = useCookies(["jwt", "name", "email", "lastChurchId"]);
5758
const [showForgot, setShowForgot] = React.useState(false);
59+
const [emailCodeFor, setEmailCodeFor] = React.useState<string | null>(null);
5860
const [showRegister, setShowRegister] = React.useState(false);
5961
const [showSelectModal, setShowSelectModal] = React.useState(false);
6062
const [loginResponse, setLoginResponse] = React.useState<LoginResponseInterface | null>(null);
@@ -294,11 +296,11 @@ const LoginPageContent: React.FC<Props> = ({ showLogo = true, loginContainerCssP
294296
}
295297
};
296298

297-
const login = async (data: any) => {
299+
const login = async (data: any, path = "/users/login") => {
298300
setErrors([]);
299301
setIsSubmitting(true);
300302
try {
301-
const resp: LoginResponseInterface = await ApiHelper.postAnonymous("/users/login", data, "MembershipApi");
303+
const resp: LoginResponseInterface = await ApiHelper.postAnonymous(path, data, "MembershipApi");
302304
setIsSubmitting(false);
303305
if (resp.mfaRequired) {
304306
setPendingAutoLogin(false);
@@ -312,6 +314,7 @@ const LoginPageContent: React.FC<Props> = ({ showLogo = true, loginContainerCssP
312314
setPendingAutoLogin(false);
313315
setWelcomeBackName("");
314316
if (data.mfaToken) setErrors([e?.message === "Too many requests" ? e.message : Locale.label("login.mfaInvalid")]);
317+
else if (data.code) setErrors([e?.message === "Too many requests" ? e.message : Locale.label("login.validate.emailCode")]);
315318
else if (!data.jwt) handleLoginErrors([e.toString()], data.email);
316319
setIsSubmitting(false);
317320
}
@@ -340,7 +343,8 @@ const LoginPageContent: React.FC<Props> = ({ showLogo = true, loginContainerCssP
340343
const handleCodeVerified = (authGuid: string, email?: string) => { setVerifiedAuth(authGuid); if (email) setVerifiedEmail(email); setShowForgot(false); setShowRegister(false); };
341344

342345
const getInputBox = () => {
343-
if (mfaToken) return <MfaCode isSubmitting={isSubmitting} submit={(code) => login({ mfaToken, mfaCode: code })} cancel={() => { setMfaToken(""); setErrors([]); }} />;
346+
if (mfaToken) return <MfaCode isSubmitting={isSubmitting} submit={(code) => login({ mfaToken, mfaCode: code })} cancel={() => { setMfaToken(""); setEmailCodeFor(null); setErrors([]); }} />;
347+
if (emailCodeFor !== null) return <EmailCode defaultEmail={emailCodeFor} isSubmitting={isSubmitting} submit={(email, code) => login({ email, code, appName: props.appName }, "/users/loginWithCode")} loginCallback={() => { setEmailCodeFor(null); setErrors([]); }} />;
344348
if (verifiedAuth) return (<LoginSetPassword setErrors={setErrors} setShowForgot={setShowForgot} isSubmitting={isSubmitting} auth={verifiedAuth} email={verifiedEmail} login={login} appName={props.appName || ""} appUrl={cleanAppUrl() || ""} />);
345349
if (showRegister) {
346350
return (
@@ -350,7 +354,7 @@ const LoginPageContent: React.FC<Props> = ({ showLogo = true, loginContainerCssP
350354
);
351355
} else if (showForgot) return (<Forgot registerCallback={handleRegisterCallback} loginCallback={handleLoginCallback} onVerified={handleCodeVerified} />);
352356
else if (props.auth) return (<LoginSetPassword setErrors={setErrors} setShowForgot={setShowForgot} isSubmitting={isSubmitting} auth={props.auth} login={login} appName={props.appName || ""} appUrl={cleanAppUrl() || ""} />);
353-
else return <Login setShowRegister={setShowRegister} setShowForgot={setShowForgot} setErrors={setErrors} isSubmitting={isSubmitting} login={login} mainContainerCssProps={loginContainerCssProps} defaultEmail={props.defaultEmail} defaultPassword={props.defaultPassword} showFooter={props.showFooter} onRegisterClick={(email) => { setRegistrationData({ email }); }} />;
357+
else return <Login setShowRegister={setShowRegister} setShowForgot={setShowForgot} setErrors={setErrors} isSubmitting={isSubmitting} login={login} mainContainerCssProps={loginContainerCssProps} defaultEmail={props.defaultEmail} defaultPassword={props.defaultPassword} showFooter={props.showFooter} onRegisterClick={(email) => { setRegistrationData({ email }); }} onEmailCodeClick={(email) => { setErrors([]); setEmailCodeFor(email); }} />;
354358
};
355359

356360
React.useEffect(init, []); //eslint-disable-line
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import React from "react";
2+
import { act } from "react";
3+
import { createRoot, type Root } from "react-dom/client";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { ApiHelper } from "@churchapps/helpers";
6+
import { LoginPage } from "../LoginPage";
7+
8+
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
9+
10+
const context: any = { setUser: vi.fn(), setUserChurches: vi.fn(), setUserChurch: vi.fn(), setPerson: vi.fn() };
11+
let container: HTMLDivElement | null = null;
12+
let root: Root | null = null;
13+
14+
const mount = async () => {
15+
container = document.createElement("div");
16+
document.body.appendChild(container);
17+
root = createRoot(container);
18+
await act(async () => { root!.render(<LoginPage context={context} jwt="" auth="" appName="B1" />); });
19+
};
20+
21+
const setValue = async (input: HTMLInputElement, value: string) => {
22+
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
23+
await act(async () => {
24+
setter.call(input, value);
25+
input.dispatchEvent(new Event("input", { bubbles: true }));
26+
});
27+
};
28+
29+
const submit = async (selector: string) => {
30+
await act(async () => { container!.querySelector(selector)!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })); });
31+
};
32+
33+
const typeCode = async (code: string) => {
34+
const digits = Array.from(container!.querySelectorAll<HTMLInputElement>("#email-code-verify-form input[type='text']"));
35+
for (const [i, d] of code.split("").entries()) await setValue(digits[i], d);
36+
};
37+
38+
// Click "Email me a code", enter the address, and send the request.
39+
const requestCode = async (email = "member@example.com") => {
40+
await setValue(container!.querySelector<HTMLInputElement>("#login-email-field input, input#login-email-field")!, email);
41+
await act(async () => { container!.querySelector<HTMLButtonElement>("#email-code-link")!.click(); });
42+
expect(container!.querySelector<HTMLInputElement>("#email-code-email")!.value).toBe(email);
43+
await submit("#email-code-request-form");
44+
};
45+
46+
afterEach(() => {
47+
if (root) act(() => { root!.unmount(); });
48+
container?.remove();
49+
root = null;
50+
container = null;
51+
vi.restoreAllMocks();
52+
window.history.replaceState(null, "", "/");
53+
});
54+
55+
describe("LoginPage email code sign-in", () => {
56+
it("requests a code for the typed email, then signs in with it", async () => {
57+
const post = vi.spyOn(ApiHelper, "postAnonymous")
58+
.mockResolvedValueOnce({ emailed: true } as any)
59+
.mockResolvedValueOnce({ user: { id: "u1", email: "member@example.com", firstName: "A", lastName: "B", jwt: "jwt" }, userChurches: [] } as any);
60+
await mount();
61+
await requestCode();
62+
expect(post).toHaveBeenNthCalledWith(1, "/users/requestLoginCode", { email: "member@example.com" }, "MembershipApi");
63+
64+
await typeCode("123456");
65+
expect(post).toHaveBeenNthCalledWith(2, "/users/loginWithCode", { email: "member@example.com", code: "123456", appName: "B1" }, "MembershipApi");
66+
expect(post).toHaveBeenCalledTimes(2);
67+
});
68+
69+
it("shows a plain error for a wrong code and stays on the code step", async () => {
70+
vi.spyOn(ApiHelper, "postAnonymous")
71+
.mockResolvedValueOnce({ emailed: true } as any)
72+
.mockRejectedValueOnce(new Error("Invalid or expired code"));
73+
await mount();
74+
await requestCode();
75+
await typeCode("000000");
76+
expect(container!.textContent).toContain("That code didn't work or has expired");
77+
expect(container!.querySelector("#email-code-verify-form")).not.toBeNull();
78+
expect(container!.textContent).not.toContain("No account");
79+
});
80+
81+
it("goes to the two-factor step when the account has MFA", async () => {
82+
const post = vi.spyOn(ApiHelper, "postAnonymous")
83+
.mockResolvedValueOnce({ emailed: true } as any)
84+
.mockResolvedValueOnce({ mfaRequired: true, mfaToken: "challenge" } as any);
85+
await mount();
86+
await requestCode();
87+
await typeCode("123456");
88+
expect(container!.querySelector("#mfa-code")).not.toBeNull();
89+
expect(post).toHaveBeenCalledTimes(2);
90+
});
91+
92+
it("returns to the password form", async () => {
93+
vi.spyOn(ApiHelper, "postAnonymous");
94+
await mount();
95+
await act(async () => { container!.querySelector<HTMLButtonElement>("#email-code-link")!.click(); });
96+
const back = Array.from(container!.querySelectorAll("button")).find((b) => b.textContent === "Sign in with password")!;
97+
await act(async () => { back.click(); });
98+
expect(container!.querySelector("#login-password-field")).not.toBeNull();
99+
expect(ApiHelper.postAnonymous).not.toHaveBeenCalled();
100+
});
101+
});
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
"use client";
2+
3+
import React, { FormEventHandler } from "react";
4+
import { ApiHelper } from "@churchapps/helpers";
5+
import { Locale } from "../helpers";
6+
import { TextField, Typography, Card, CardContent, Button } from "@mui/material";
7+
import { VerificationCodeInput } from "./VerificationCodeInput";
8+
9+
interface Props {
10+
defaultEmail?: string;
11+
isSubmitting: boolean;
12+
submit: (email: string, code: string) => void;
13+
loginCallback: () => void;
14+
}
15+
16+
const RESEND_COOLDOWN_SECONDS = 30;
17+
18+
const buttonSx = {
19+
backgroundColor: "hsl(218, 85%, 55%)",
20+
color: "white",
21+
padding: "12px",
22+
textTransform: "none",
23+
fontSize: "16px",
24+
fontWeight: 500,
25+
borderRadius: "6px",
26+
"&:hover": { backgroundColor: "hsl(218, 85%, 50%)" },
27+
"&:disabled": { backgroundColor: "#9ca3af" }
28+
} as const;
29+
30+
const linkStyle: React.CSSProperties = { background: "none", border: "none", color: "#3b82f6", fontSize: "14px", cursor: "pointer", textDecoration: "none" };
31+
32+
export const EmailCode: React.FC<Props> = (props) => {
33+
const [errors, setErrors] = React.useState<string[]>([]);
34+
const [email, setEmail] = React.useState(props.defaultEmail || "");
35+
const [isSending, setIsSending] = React.useState(false);
36+
const [codeSent, setCodeSent] = React.useState(false);
37+
const [code, setCode] = React.useState("");
38+
const [resendCooldown, setResendCooldown] = React.useState(0);
39+
40+
React.useEffect(() => {
41+
if (resendCooldown <= 0) return;
42+
const t = setTimeout(() => setResendCooldown(resendCooldown - 1), 1000);
43+
return () => clearTimeout(t);
44+
}, [resendCooldown]);
45+
46+
const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
47+
48+
const requestCode = async () => {
49+
if (!validEmail) { setErrors([Locale.label("login.validate.email")]); return; }
50+
setIsSending(true);
51+
try {
52+
const resp: any = await ApiHelper.postAnonymous("/users/requestLoginCode", { email }, "MembershipApi");
53+
if (resp?.errors?.length) setErrors(resp.errors);
54+
else {
55+
setErrors([]);
56+
setCode("");
57+
setCodeSent(true);
58+
setResendCooldown(RESEND_COOLDOWN_SECONDS);
59+
}
60+
} catch (e: any) {
61+
setErrors([e?.message || Locale.label("login.validate.email")]);
62+
} finally {
63+
setIsSending(false);
64+
}
65+
};
66+
67+
const verify = (submittedCode: string) => {
68+
if (props.isSubmitting) return;
69+
if (submittedCode.length !== 6) { setErrors([Locale.label("login.validate.code")]); return; }
70+
setErrors([]);
71+
props.submit(email, submittedCode);
72+
};
73+
74+
const sendForm: FormEventHandler = (e) => { e.preventDefault(); requestCode(); };
75+
const codeForm: FormEventHandler = (e) => { e.preventDefault(); verify(code); };
76+
const busy = isSending || props.isSubmitting;
77+
78+
return (
79+
<Card id="email-code-card" sx={{
80+
width: "100%",
81+
maxWidth: { xs: "400px", sm: "500px" },
82+
backgroundColor: "white",
83+
border: "1px solid #e5e7eb",
84+
boxShadow: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"
85+
}}>
86+
<CardContent sx={{ textAlign: "center", padding: "32px" }}>
87+
<Typography component="h1" sx={{ fontSize: "24px", fontWeight: "bold", color: "#111827", marginBottom: "8px" }}>
88+
{Locale.label("login.emailCodeTitle")}
89+
</Typography>
90+
<Typography sx={{ color: "#6b7280", marginBottom: "32px" }}>
91+
{codeSent ? Locale.label("login.enterCodeInstructions") : Locale.label("login.emailCodeInstructions")}
92+
</Typography>
93+
94+
{errors.length > 0 && (
95+
<div style={{ backgroundColor: "#fef2f2", border: "1px solid #fecaca", borderRadius: "6px", padding: "12px", textAlign: "left", marginBottom: "16px" }}>
96+
{errors.map((error) => <div key={error} style={{ color: "#dc2626", fontSize: "14px" }}>{error}</div>)}
97+
</div>
98+
)}
99+
100+
{!codeSent ? (
101+
<form id="email-code-request-form" onSubmit={sendForm} style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
102+
<TextField
103+
id="email-code-email"
104+
name="email"
105+
type="email"
106+
label={Locale.label("login.email")}
107+
value={email}
108+
onChange={(e) => setEmail(e.target.value)}
109+
autoFocus
110+
required
111+
autoComplete="email"
112+
fullWidth
113+
/>
114+
<Button id="email-code-send" type="submit" variant="contained" fullWidth disabled={busy} sx={buttonSx}>
115+
{busy ? Locale.label("common.pleaseWait") : Locale.label("login.sendCode")}
116+
</Button>
117+
<button type="button" onClick={props.loginCallback} style={linkStyle}>{Locale.label("login.usePassword")}</button>
118+
</form>
119+
) : (
120+
<form id="email-code-verify-form" onSubmit={codeForm} style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
121+
<Typography variant="body2" sx={{ color: "#6b7280", fontSize: "14px" }}>
122+
<b>{email}</b>
123+
</Typography>
124+
<VerificationCodeInput value={code} onChange={setCode} onComplete={verify} disabled={busy} autoFocus />
125+
<Button id="email-code-submit" type="submit" variant="contained" fullWidth disabled={busy || code.length !== 6} sx={buttonSx}>
126+
{busy ? Locale.label("common.pleaseWait") : Locale.label("login.signIn")}
127+
</Button>
128+
<div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: "8px" }}>
129+
<button type="button" disabled={resendCooldown > 0 || busy} onClick={requestCode} style={{ ...linkStyle, color: resendCooldown > 0 ? "#9ca3af" : "#3b82f6", cursor: resendCooldown > 0 ? "default" : "pointer" }}>
130+
{resendCooldown > 0 ? `${Locale.label("login.resendCode")} (${resendCooldown}s)` : Locale.label("login.resendCode")}
131+
</button>
132+
<span style={{ fontSize: "14px", color: "#6b7280" }}>|</span>
133+
<button type="button" onClick={props.loginCallback} style={linkStyle}>{Locale.label("login.usePassword")}</button>
134+
</div>
135+
</form>
136+
)}
137+
</CardContent>
138+
</Card>
139+
);
140+
};

‎apphelper/src/login/components/Login.tsx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ interface Props {
1313
setShowForgot: (showForgot: boolean) => void,
1414
setErrors: (errors: string[]) => void;
1515
onRegisterClick?: (email: string) => void;
16+
onEmailCodeClick?: (email: string) => void;
1617
mainContainerCssProps?: PaperProps;
1718
defaultEmail?: string;
1819
defaultPassword?: string;
@@ -213,6 +214,18 @@ export const Login: React.FC<Props> = ({ mainContainerCssProps = {}, ...props })
213214
<SsoButtons />
214215

215216
<div id="login-links" style={{ textAlign: "center", display: "flex", flexDirection: "column", gap: "8px" }}>
217+
{props.onEmailCodeClick && (
218+
<button
219+
id="email-code-link"
220+
type="button"
221+
onClick={(e) => { e.preventDefault(); props.onEmailCodeClick?.(email); }}
222+
style={{ background: "none", border: "none", color: "#3b82f6", fontSize: "14px", cursor: "pointer", textDecoration: "none" }}
223+
onMouseOver={(e) => e.currentTarget.style.textDecoration = "underline"}
224+
onMouseOut={(e) => e.currentTarget.style.textDecoration = "none"}
225+
>
226+
{Locale.label("login.emailCode")}
227+
</button>
228+
)}
216229
<button
217230
id="forgot-password-link"
218231
type="button"

‎apphelper/src/login/helpers/Locale.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ export class Locale {
5757
"createAccount": "Create an Account",
5858
"email": "Email",
5959
"expiredLink": "The current link is expired.",
60+
"emailCode": "Email me a code",
61+
"emailCodeInstructions": "Enter your email and we'll send you a 6-digit code to sign in.",
62+
"emailCodeTitle": "Sign In with a Code",
63+
"enterCodeInstructions": "Enter the 6-digit code we just emailed you.",
6064
"forgot": "Forgot Password",
6165
"goLogin": "Go to Login",
6266
"login": "Login",
@@ -69,18 +73,23 @@ export class Locale {
6973
"register": "Register",
7074
"registerThankYou": "Thank you for registering! Please check your email to verify your account.",
7175
"requestLink": "Request a new reset link",
76+
"resendCode": "Resend code",
7277
"reset": "Reset",
7378
"resetInstructions": "Enter your email address to request a password reset.",
7479
"resetPassword": "Reset Password",
7580
"resetSent": "Password reset email sent!",
81+
"sendCode": "Send Code",
7682
"setPassword": "Set Password",
7783
"signIn": "Sign In",
7884
"signInTitle": "Please Sign In",
85+
"usePassword": "Sign in with password",
7986
"verifyPassword": "Verify Password",
8087
"welcomeName": "Welcome back, <b>{}</b>! Please wait while we load your data.",
8188
"welcomeBack": "Welcome back",
8289
"validate": {
90+
"code": "Please enter the 6-digit code.",
8391
"email": "Please enter a valid email address.",
92+
"emailCode": "That code didn't work or has expired. Please try again or request a new code.",
8493
"firstName": "Please enter your first name.",
8594
"invalid": "Invalid login. Please check your email or password.",
8695
"lastName": "Please enter your last name.",

0 commit comments

Comments
 (0)