This repository has been archived by the owner on Oct 10, 2023. It is now read-only.
/
Auth.js
102 lines (96 loc) · 2.74 KB
/
Auth.js
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
// @flow
import React, { useState } from 'react';
import { View } from 'react-native';
import Heading from './Heading';
import Block from './Block';
import TextInput from './TextInput';
import Row from './Row';
import { SignInButton, SignUpButton } from './buttons';
import { defineMessages } from 'react-intl';
import type { Href } from '../../browser/sitemap';
import useIntl from '../../hooks/useIntl';
import { useAuthMutation } from '../../mutations/AuthMutation';
import Router from 'next/router';
import { setCookie } from '../../browser/cookie';
const messages = defineMessages({
emailPlaceholder: {
defaultMessage: 'email',
id: 'auth.emailPlaceholder',
},
passwordPlaceholder: {
defaultMessage: 'password',
id: 'auth.passwordPlaceholder',
},
});
type AuthProps = {|
redirectUrl?: Href,
|};
export default function Auth(props: AuthProps) {
const intl = useIntl();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [commit, errors, pending] = useAuthMutation();
function onSuccess(auth) {
const { token } = auth;
if (token == null) return;
setCookie({ token });
// TODO: Typed useRouter.
if (Router.query.redirectUrl) {
Router.replace(Router.query.redirectUrl);
} else if (props.redirectUrl) {
// $FlowFixMe Wrong libdef.
Router.replace(props.redirectUrl);
} else {
// $FlowFixMe Wrong libdef.
Router.replace({
pathname: Router.pathname,
query: Router.query,
});
}
}
function auth(isSignUp = false) {
commit({ email, password, isSignUp }, onSuccess);
}
return (
<View>
<Heading size={1}>Auth</Heading>
<Block>
<TextInput
autoComplete="email"
disabled={pending}
error={errors && errors.email}
focusOnError={errors}
keyboardType="email-address"
name="email"
onChangeText={setEmail}
placeholder={intl.formatMessage(messages.emailPlaceholder)}
value={email}
onSubmitEditing={() => auth()}
/>
<TextInput
disabled={pending}
error={errors && errors.password}
focusOnError={errors}
name="password"
onChangeText={setPassword}
placeholder={intl.formatMessage(messages.passwordPlaceholder)}
secureTextEntry
value={password}
onSubmitEditing={() => auth()}
/>
<Row>
<SignInButton
disabled={pending}
onPress={() => auth()}
color="primary"
/>
<SignUpButton
disabled={pending}
onPress={() => auth(true)}
color="primary"
/>
</Row>
</Block>
</View>
);
}