garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /crates/atlas/web/src/components/pages/password/password.tsx

raw

import m, {MithrilComponent} from '@garage44/mithril'
import {Alert, Button, Card, FieldText} from '@garage44/mithril/components'
import {validation, validations} from '@garage44/mithril/validation'

import {$s} from '@/app'
import {COMMUNITY} from '@/lib/base'
import {bind, local} from '@/lib/reactive'
import {forgotPassword, resetPassword, tokenFromLocation} from '@/lib/signup'

/**
 * "Forgot your password?": an address in, a link out.
 *
 * Says the same thing whatever the address, as the server does — "no account
 * has that address" would tell anyone whether a person is here. The mail
 * names the account, for the person who forgot that too.
 */
export class Forgot extends MithrilComponent {
    s = local({busy: false, email: '', sent: false})

    v = validations({
        email: validation(bind(this.s, 'email'))
            .required('That does not look like an email address.')
            .check((value) => {
                const address = value.trim()
                const at = address.lastIndexOf('@')
                return at >= 1 && address.slice(at + 1).includes('.')
            }, 'That does not look like an email address.'),
    })

    send = async (e: Event) => {
        e.preventDefault()
        const s = this.s
        if (s.busy || !this.v.$validate()) {
            return
        }
        s.busy = true
        s.sent = await forgotPassword(s.email.trim())
        s.busy = false
    }

    view() {
        const s = this.s

        if (s.sent) {
            return (
                <div class="auth">
                    <Card title="Check your inbox">
                        <Alert tone="success">
                            If <b>{s.email.trim()}</b> belongs to an account here, we've sent it a link to choose a
                            new password. It works once and expires in an hour.
                        </Alert>
                        <p class="auth__lede">
                            Nothing arrived? It may be in a spam folder, or the account may use another address.
                        </p>
                        <div class="auth__actions">
                            <Button onclick={() => (s.sent = false)} variant="ghost">
                                Try another address
                            </Button>
                            <Button onclick={() => m.route.set(COMMUNITY)} variant="ghost">
                                Back to sign in
                            </Button>
                        </div>
                    </Card>
                </div>
            )
        }

        return (
            // A form, so Enter or the phone's Go key sends the link.
            <form class="auth" novalidate onsubmit={this.send}>
                <Card title="Forgot your password?">
                    <p class="auth__lede">
                        Enter the email address of your account, and we'll send a link to choose a new password.
                    </p>
                    <FieldText
                        autocomplete="email"
                        disabled={s.busy}
                        label="Email"
                        model={bind(s, 'email')}
                        type="email"
                        validation={this.v.email}
                    />
                    <div class="auth__actions">
                        <Button disabled={!this.v.$valid} loading={s.busy} type="submit" variant="primary">
                            Send the link
                        </Button>
                        <Button disabled={s.busy} onclick={() => m.route.set(COMMUNITY)} variant="ghost">
                            Back to sign in
                        </Button>
                    </div>
                    <p class="auth__lede">
                        Signed up through Discord, Google or another site? Sign in there again instead — there is no
                        password to reset.
                    </p>
                </Card>
            </form>
        )
    }
}

type Phase = 'choosing' | 'done' | 'no-token'

/**
 * Where the link in the mail lands: choose the new password.
 *
 * Nothing is spent on opening the page — only the button does that — so a mail
 * scanner fetching the link changes nothing.
 */
export class ResetPassword extends MithrilComponent {
    s = local({busy: false, password: '', phase: 'choosing' as Phase, token: ''})

    v = validations({
        password: validation(bind(this.s, 'password'))
            .required()
            .rule((value) => {
                const min = $s.registration?.min_password_length ?? 0
                return value.length >= min ? null : `The password needs at least ${min} characters.`
            }),
    })

    oninit() {
        const token = tokenFromLocation(window.location.search)
        this.s.token = token
        if (!token) {
            this.s.phase = 'no-token'
        }
    }

    save = async (e: Event) => {
        e.preventDefault()
        const s = this.s
        if (s.busy || !this.v.$validate()) {
            return
        }
        s.busy = true
        const ok = await resetPassword(s.token, s.password)
        s.busy = false
        if (ok) {
            s.password = ''
            s.phase = 'done'
        }
    }

    view() {
        const s = this.s

        if (s.phase === 'done') {
            return (
                <div class="auth">
                    <Card title="Password changed">
                        <Alert tone="success">
                            Your new password works now, here and in the app. You've been signed out everywhere
                            else.
                        </Alert>
                        <div class="auth__actions">
                            <Button onclick={() => m.route.set(COMMUNITY)} variant="primary">
                                Sign in
                            </Button>
                        </div>
                    </Card>
                </div>
            )
        }

        if (s.phase === 'no-token') {
            return (
                <div class="auth">
                    <Card title="Choose a new password">
                        <Alert title="That link is incomplete" tone="danger">
                            Open the link from the mail in full, or ask for a new one.
                        </Alert>
                        <div class="auth__actions">
                            <Button onclick={() => m.route.set('/forgot')} variant="primary">
                                Ask for a new link
                            </Button>
                        </div>
                    </Card>
                </div>
            )
        }

        const min = $s.registration?.min_password_length
        return (
            <form class="auth" novalidate onsubmit={this.save}>
                <Card title="Choose a new password">
                    <FieldText
                        autocomplete="new-password"
                        disabled={s.busy}
                        help={min ? `At least ${min} characters.` : undefined}
                        label="New password"
                        model={bind(s, 'password')}
                        type="password"
                        validation={this.v.password}
                    />
                    <div class="auth__actions">
                        <Button disabled={!this.v.$valid} loading={s.busy} type="submit" variant="primary">
                            Save the password
                        </Button>
                        <Button disabled={s.busy} onclick={() => m.route.set('/forgot')} variant="ghost">
                            Ask for a new link
                        </Button>
                    </div>
                </Card>
            </form>
        )
    }
}