File size: 5,626 Bytes
fb43301
af1bee9
 
 
 
fb43301
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d811c3
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { IconCircleCheck as CircleCheck, IconLock as Lock, IconMail as Mail, IconMailCheck as MailCheck } from '@/components/icons';
import { useMemo, useState, type FormEvent } from 'react';
import { Link } from 'react-router-dom';
import { StatefulButton, type ButtonState } from '@/components/ui/motion/button/stateful';
import { Input } from '@/components/ui/motion/input';
import { api, unwrap } from '../../api/client';
import { AUTH_BUTTON_PRIMARY, AUTH_LINK, AuthDone, AuthError, AuthShell, FIELD } from './AuthShell';

/** "Forgot your password?": asks Supabase to e-mail a reset link. The answer never says whether the address exists. */
export function ForgotPage() {
  const [email, setEmail] = useState('');
  const [state, setState] = useState<ButtonState>('idle');
  const [err, setErr] = useState<unknown>(null);
  const [sent, setSent] = useState(false);
  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setState('loading');
    setErr(null);
    try {
      await unwrap(api.POST('/api/auth/forgot', { body: { email } }));
      setSent(true);
    } catch (x) {
      setErr(x);
    } finally {
      setState('idle');
    }
  };
  return (
    <AuthShell label="Reset your password" title="Reset your password" sub="Enter your work e-mail and we will send you a link to set a new one.">

      <form onSubmit={submit} aria-label="Reset your password">

        {sent ? (

          <AuthDone testId="forgot-sent" icon={<MailCheck aria-hidden />} title="Check your inbox"

            action={<Link to="/login" className={AUTH_BUTTON_PRIMARY}>Back to sign in</Link>}>

            If an account exists for <b className="text-[var(--label)]">{email}</b>, we sent a link to set a new password. It works once and expires after a short time.

          </AuthDone>

        ) : (

          <div className="flex flex-col gap-4">

            {!!err && <AuthError err={err} />}

            <Input label="Work e-mail" type="email" placeholder="you@company.com" autoComplete="email" required value={email} onChange={setEmail}

              autoFocus leftIcon={<Mail aria-hidden />} classNames={FIELD} />

            <StatefulButton type="submit" state={state} size="lg" className="mt-2 w-full border-0 font-semibold" disabled={!email}

              loadingText="Sending">Send the reset link</StatefulButton>

            <p className="m-0 text-center text-sm"><Link to="/login" className={AUTH_LINK}>Back to sign in</Link></p>

          </div>

        )}

      </form>

    </AuthShell>
  );
}

/** Opened from the reset e-mail: Supabase puts a short-lived token in the address (#access_token=...&type=recovery). */
export function ResetPage() {
  const params = useMemo(() => new URLSearchParams((typeof window !== 'undefined' ? window.location.hash : '').replace(/^#/, '')), []);
  const token = params.get('access_token') || '';
  const linkError = params.get('error_description');
  const [password, setPassword] = useState('');
  const [again, setAgain] = useState('');
  const [state, setState] = useState<ButtonState>('idle');
  const [err, setErr] = useState<unknown>(null);
  const [done, setDone] = useState(false);
  const mismatch = again.length > 0 && again !== password;
  const submit = async (e: FormEvent) => {
    e.preventDefault();
    if (mismatch || password.length < 10) return;
    setState('loading');
    setErr(null);
    try {
      await unwrap(api.POST('/api/auth/reset', { body: { access_token: token, password } }));
      if (typeof window !== 'undefined') window.history.replaceState(null, '', '/reset'); // drop the token from the address bar
      setDone(true);
    } catch (x) {
      setErr(x);
    } finally {
      setState('idle');
    }
  };
  return (
    <AuthShell label="Set a new password" title="Choose a new password" sub="Choose a password of at least 10 characters.">

      <form onSubmit={submit} aria-label="Set a new password">

        {done ? (

          <AuthDone testId="reset-done" icon={<CircleCheck aria-hidden />} title="Password changed"

            action={<Link to="/login" className={AUTH_BUTTON_PRIMARY}>Go to sign in</Link>}>

            Your new password is set. Sign in with it now.

          </AuthDone>

        ) : !token ? (

          <AuthDone title="This link can't be used" action={<Link to="/forgot" className={AUTH_BUTTON_PRIMARY}>Send a new reset link</Link>}>

            {linkError ? decodeURIComponent(linkError.replace(/\+/g, ' ')) : 'The reset link is incomplete or has already been used.'} Ask for a new one.

          </AuthDone>

        ) : (

          <div className="flex flex-col gap-4">

            {!!err && <AuthError err={err} />}

            <Input label="New password" type="password" autoComplete="new-password" required value={password} onChange={setPassword}

              error={password.length > 0 && password.length < 10 ? 'Use at least 10 characters.' : undefined} leftIcon={<Lock aria-hidden />} classNames={FIELD} autoFocus />

            <Input label="Repeat the new password" type="password" autoComplete="new-password" required value={again} onChange={setAgain}

              error={mismatch ? 'The two passwords are different.' : undefined} leftIcon={<Lock aria-hidden />} classNames={FIELD} />

            <StatefulButton type="submit" state={state} size="lg" className="mt-2 w-full border-0 font-semibold" disabled={mismatch || password.length < 10}

              loadingText="Saving">Save the new password</StatefulButton>

          </div>

        )}

      </form>

    </AuthShell>
  );
}