aboutsummaryrefslogtreecommitdiff
path: root/src/web/components/login/Login.jsx
blob: 7944aa3586b51f76d5339c4a7403bc7c7878af8c (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import React, {Fragment, useState, useContext} from "react";
import {Link} from "react-router-dom";

import Card from "components/card/Card.jsx";
import Button from "components/button/Button.jsx";
import Darken from "components/darken/Darken.jsx";
import Loading from "components/loading/Loading.jsx";
import Input from "components/input/Input.jsx";
import {UserContext} from "contexts/UserContext.jsx";
import {maybeAuthFromCookie} from "helpers/Auth.jsx";
import {getFieldError, correctFieldAnimate} from "helpers/Input.jsx";

import styles from "./Login.css";

const validateEmail = (email) => getFieldError(email?.target?.value, [3, 254]);
const validatePassword = (password) => getFieldError(password?.target?.value, [8, 64]);

function RequestButton({email, password, apiPath, promise, setPromise, setEmail, 
                        setPassword, setLoginActive, setError, children}) {

    const userState = useContext(UserContext);

    const onClick = () => {
        if (promise != null) {
            return;
        }
        setError(null);

        // We don't want to send a worthless request, we should animate the bad values.
        const emailErrors = validateEmail(email);
        const passwordErrors = validatePassword(password);
        if (emailErrors != null || passwordErrors != null) {
            correctFieldAnimate(email, setEmail, emailErrors);
            correctFieldAnimate(password, setPassword, passwordErrors);
            return;
        }

        const init = {
            method: "POST",
            headers: {
                'Content-Type': "application/json"
            },
            body: JSON.stringify({
                "email": email.target.value,
                "password": password.target.value
            }),
            referrer: "same-origin",
        };
        setPromise(fetch(apiPath, init)
            .then((response) => {
                if (response.ok) {
                    if (!maybeAuthFromCookie(userState)) {
                        throw new Error("rejected authentication token");
                    }

                    setLoginActive(false);
                    return;
                }

                return response.json()
                    .then((json) => {
                        if ("error" in json) {
                            throw new Error(json.error);
                        }
                        throw new Error("unexpected data received");
                    })
            })
            .catch((error) => {
                console.log(error);
                setError(error.message);
            })
            .finally(() => {
                setPromise(null);
            })
        );
    };

    // I'm not worried about this object becoming unmounted mid promise because
    // our website design removes this possibility.
    return (
        <Button className={(promise != null ? styles.buttonLoading : null)}
            onClick={onClick}>

            {children}
        </Button>
    );
}

function CardError({active, text}) {
    return (
        <div className={styles.cardError + (active ? " " + styles.cardErrorActive : "")}>
            <p>
                {text}
            </p>
        </div>
    );
}

function FormContents(props) {
    const {setLoginActive,
           isRegister,
           setIsRegister,
           title, 
           prompt,
           linkContents,
           apiPath} = props;

    const [error, setError] = useState(null);
    // Email and password .value's are null here to represent the state where the user
    // has not typed in anything yet. This is to only validate after at least some
    // input has been received.
    const [email, setEmail] = useState(null);
    const [password, setPassword] = useState(null);
    const [promise, setPromise] = useState(null);

    return (
        <div className={styles.formContainer}>
            <CardError active={error != null} text={error} />

            <h1>{title}</h1>

            <Input type="text"
                title="Email" 
                field={email}
                setField={setEmail}
                validateField={validateEmail} />

            <Input type="text"
                title="Password"
                field={password}
                setField={setPassword}
                validateField={validatePassword} />

            <div className={styles.promptContainer}>
                {prompt}
            </div>

            <RequestButton email={email}
                password={password}
                promise={promise}
                setEmail={setEmail}
                setPassword={setPassword}
                setLoginActive={setLoginActive}
                setPromise={setPromise}
                setError={setError}
                apiPath={apiPath}>

                {promise == null ? title : <Loading className={styles.loading} />}
            </RequestButton>

            <a onClick={() => {
                if (promise != null) { // disallow mid transaction change
                    return;
                }
                setIsRegister(!isRegister);
                setError(null);
                setEmail({...email, value: null, animating: false});
                setPassword({...password, value: null, animating: false});}}>

                {linkContents}
            </a>
        </div>
    );
};

function RegisterPrompt() {
    return (
        <p>
            By registering, you agree to both our privacy policy and to
            waive all rights of basic privacy and security.
        </p>
    );
}

function LoginPrompt(props) {
    const {setLoginActive} = props;

    return (
        <Fragment>
            <div>
                <input type="checkbox" id="save_login" /><label htmlFor="save_login">Save Login</label>
            </div>
            <Link to="settings/recover" onClick={() => setLoginActive(false)}>
                Can't log in?
            </Link>
        </Fragment>
    );
}

function Prompt(props) {
    const {setLoginActive} = props; 
    const [isRegister, setIsRegister] = useState(true);
    return (
        <FormContents setLoginActive={setLoginActive}
            isRegister={isRegister}
            setIsRegister={setIsRegister}
            title={isRegister ? "Sign Up" : "Login"}
            prompt={isRegister ? <RegisterPrompt /> : <LoginPrompt setLoginActive={setLoginActive} />}
            linkContents={isRegister ? "Already have an account?" : "Don't have an account?"}
            apiPath={isRegister ? "/api/signup" : "/api/login"} />
    );
}

// A popup which asks for login/register info.
export default function Login(props) {
    const {active, setActive} = props;

    return (
        <Fragment>
            <Darken active={active} onClick={() => setActive(false)} className={styles.darken} />
            <div className={styles.screenCenter}>
                <Card className={styles.login + (active ? " " + styles.loginActive : "")}>
                    <Prompt setLoginActive={setActive} />
                </Card>
            </div>
        </Fragment>
    );
}