verification emails and full email setup

This commit is contained in:
2026-01-29 00:43:24 +00:00
parent 14520618d1
commit d943561e89
31 changed files with 2190 additions and 53 deletions

View File

@@ -2,7 +2,6 @@
import { USER_EMAIL_MAX_LENGTH, USER_NAME_MAX_LENGTH, USER_USERNAME_MAX_LENGTH } from "@sprint/shared";
import { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import Avatar from "@/components/avatar";
import { useSession } from "@/components/session-provider";
import { Button } from "@/components/ui/button";
@@ -26,9 +25,7 @@ export default function LogInForm({
showWarning: boolean;
setShowWarning: (value: boolean) => void;
}) {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { setUser } = useSession();
const { setUser, setEmailVerified } = useSession();
const [loginDetailsOpen, setLoginDetailsOpen] = useState(false);
@@ -59,8 +56,7 @@ export default function LogInForm({
const data = await res.json();
setCsrfToken(data.csrfToken);
setUser(data.user);
const next = searchParams.get("next") || "/issues";
navigate(next, { replace: true });
setEmailVerified(data.user.emailVerified);
}
// unauthorized
else if (res.status === 401) {
@@ -98,8 +94,7 @@ export default function LogInForm({
const data = await res.json();
setCsrfToken(data.csrfToken);
setUser(data.user);
const next = searchParams.get("next") || "/issues";
navigate(next, { replace: true });
setEmailVerified(data.user.emailVerified);
}
// bad request (probably a bad user input)
else if (res.status === 400) {

View File

@@ -15,21 +15,21 @@ interface LoginModalProps {
export function LoginModal({ open, onOpenChange, onSuccess, dismissible = true }: LoginModalProps) {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { user, isLoading } = useSession();
const { user, isLoading, emailVerified } = useSession();
const [hasRedirected, setHasRedirected] = useState(false);
const [showWarning, setShowWarning] = useState(() => {
return localStorage.getItem("hide-under-construction") !== "true";
});
useEffect(() => {
if (open && !isLoading && user && !hasRedirected) {
if (open && !isLoading && user && emailVerified && !hasRedirected) {
setHasRedirected(true);
const next = searchParams.get("next") || "/issues";
navigate(next, { replace: true });
onSuccess?.();
onOpenChange(false);
}
}, [open, user, isLoading, navigate, searchParams, onSuccess, onOpenChange, hasRedirected]);
}, [open, user, isLoading, emailVerified, navigate, searchParams, onSuccess, onOpenChange, hasRedirected]);
useEffect(() => {
if (!open) {

View File

@@ -3,12 +3,16 @@ import { createContext, useCallback, useContext, useEffect, useRef, useState } f
import Loading from "@/components/loading";
import { LoginModal } from "@/components/login-modal";
import { VerificationModal } from "@/components/verification-modal";
import { clearAuth, getServerURL, setCsrfToken } from "@/lib/utils";
interface SessionContextValue {
user: UserResponse | null;
setUser: (user: UserResponse) => void;
isLoading: boolean;
emailVerified: boolean;
setEmailVerified: (verified: boolean) => void;
refreshUser: () => Promise<void>;
}
const SessionContext = createContext<SessionContextValue | null>(null);
@@ -39,6 +43,7 @@ export function useAuthenticatedSession(): { user: UserResponse; setUser: (user:
export function SessionProvider({ children }: { children: React.ReactNode }) {
const [user, setUserState] = useState<UserResponse | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [emailVerified, setEmailVerified] = useState(true);
const fetched = useRef(false);
const setUser = useCallback((user: UserResponse) => {
@@ -46,6 +51,19 @@ export function SessionProvider({ children }: { children: React.ReactNode }) {
localStorage.setItem("user", JSON.stringify(user));
}, []);
const refreshUser = useCallback(async () => {
const res = await fetch(`${getServerURL()}/auth/me`, {
credentials: "include",
});
if (!res.ok) {
throw new Error(`auth check failed: ${res.status}`);
}
const data = (await res.json()) as { user: UserResponse; csrfToken: string; emailVerified: boolean };
setUser(data.user);
setCsrfToken(data.csrfToken);
setEmailVerified(data.emailVerified);
}, [setUser]);
useEffect(() => {
if (fetched.current) return;
fetched.current = true;
@@ -57,9 +75,10 @@ export function SessionProvider({ children }: { children: React.ReactNode }) {
if (!res.ok) {
throw new Error(`auth check failed: ${res.status}`);
}
const data = (await res.json()) as { user: UserResponse; csrfToken: string };
const data = (await res.json()) as { user: UserResponse; csrfToken: string; emailVerified: boolean };
setUser(data.user);
setCsrfToken(data.csrfToken);
setEmailVerified(data.emailVerified);
})
.catch(() => {
setUserState(null);
@@ -70,11 +89,17 @@ export function SessionProvider({ children }: { children: React.ReactNode }) {
});
}, [setUser]);
return <SessionContext.Provider value={{ user, setUser, isLoading }}>{children}</SessionContext.Provider>;
return (
<SessionContext.Provider
value={{ user, setUser, isLoading, emailVerified, setEmailVerified, refreshUser }}
>
{children}
</SessionContext.Provider>
);
}
export function RequireAuth({ children }: { children: React.ReactNode }) {
const { user, isLoading } = useSession();
const { user, isLoading, emailVerified } = useSession();
const [loginModalOpen, setLoginModalOpen] = useState(false);
useEffect(() => {
@@ -93,5 +118,9 @@ export function RequireAuth({ children }: { children: React.ReactNode }) {
return <LoginModal open={loginModalOpen} onOpenChange={setLoginModalOpen} dismissible={false} />;
}
if (user && !emailVerified) {
return <VerificationModal open={true} onOpenChange={() => {}} />;
}
return <>{children}</>;
}

View File

@@ -0,0 +1,69 @@
/** biome-ignore-all lint/a11y/useFocusableInteractive: <> */
/** biome-ignore-all lint/a11y/useAriaPropsForRole: <> */
/** biome-ignore-all lint/a11y/useSemanticElements: <> */
import { OTPInput, OTPInputContext } from "input-otp";
import { MinusIcon } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string;
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn("flex items-center gap-2 has-disabled:opacity-50", containerClassName)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
);
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="input-otp-group" className={cn("flex items-center", className)} {...props} />;
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & {
index: number;
}) {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {};
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
className,
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
);
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };

View File

@@ -1,7 +1,7 @@
import { useRef, useState } from "react";
import { toast } from "sonner";
import Avatar from "@/components/avatar";
import { useAuthenticatedSession } from "@/components/session-provider";
import { useSession } from "@/components/session-provider";
import { Button } from "@/components/ui/button";
import Icon from "@/components/ui/icon";
import { Label } from "@/components/ui/label";
@@ -56,7 +56,7 @@ export function UploadAvatar({
skipOrgCheck?: boolean;
className?: string;
}) {
const { user } = useAuthenticatedSession();
const { user } = useSession();
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -68,7 +68,7 @@ export function UploadAvatar({
if (!file) return;
// check for animated GIF for free users
if (user.plan !== "pro" && file.type === "image/gif") {
if (user?.plan !== "pro" && file.type === "image/gif") {
const isAnimated = await isAnimatedGIF(file);
if (isAnimated) {
setError("Animated avatars are only available on Pro. Upgrade to upload animated avatars.");

View File

@@ -0,0 +1,104 @@
import { useState } from "react";
import { useSession } from "@/components/session-provider";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { useResendVerification, useVerifyEmail } from "@/lib/query/hooks";
interface VerificationModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function VerificationModal({ open, onOpenChange }: VerificationModalProps) {
const { refreshUser, setEmailVerified } = useSession();
const [code, setCode] = useState("");
const [error, setError] = useState<string | null>(null);
const [resendSuccess, setResendSuccess] = useState(false);
const verifyMutation = useVerifyEmail();
const resendMutation = useResendVerification();
const handleVerify = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setResendSuccess(false);
try {
await verifyMutation.mutateAsync({ code: code.trim() });
setEmailVerified(true);
onOpenChange(false);
await refreshUser();
} catch (err) {
setError(err instanceof Error ? err.message : "Verification failed");
}
};
const handleResend = async () => {
setError(null);
setResendSuccess(false);
try {
await resendMutation.mutateAsync();
setResendSuccess(true);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to resend code");
}
};
return (
<Dialog open={open} onOpenChange={() => {}}>
<DialogContent className="sm:max-w-md" showCloseButton={false}>
<DialogHeader>
<DialogTitle>Verify your email</DialogTitle>
<DialogDescription>
We've sent a 6-digit verification code to your email. Enter it below to complete your
registration.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleVerify} className="space-y-4">
<div className="space-y-2">
<div className="flex justify-center">
<InputOTP
maxLength={6}
value={code}
onChange={setCode}
disabled={verifyMutation.isPending}
autoFocus
className="gap-2"
>
<InputOTPGroup className="gap-2">
<InputOTPSlot index={0} className="w-14 h-16 text-2xl" />
<InputOTPSlot index={1} className="w-14 h-16 text-2xl" />
<InputOTPSlot index={2} className="w-14 h-16 text-2xl" />
<InputOTPSlot index={3} className="w-14 h-16 text-2xl" />
<InputOTPSlot index={4} className="w-14 h-16 text-2xl" />
<InputOTPSlot index={5} className="w-14 h-16 text-2xl" />
</InputOTPGroup>
</InputOTP>
</div>
{error && <p className="text-sm text-destructive text-center">{error}</p>}
{resendSuccess && <p className="text-sm text-green-600 text-center">Verification code sent!</p>}
</div>
<div className="flex flex-col gap-2">
<Button type="submit" disabled={code.length !== 6 || verifyMutation.isPending} className="w-full">
{verifyMutation.isPending ? "Verifying..." : "Verify email"}
</Button>
<Button
type="button"
variant="ghost"
onClick={handleResend}
disabled={resendMutation.isPending}
className="w-full"
>
{resendMutation.isPending ? "Sending..." : "Resend code"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}