-
Notifications
You must be signed in to change notification settings - Fork 23
/
AuthContainer.js
113 lines (110 loc) · 3.03 KB
/
AuthContainer.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
103
104
105
106
107
108
109
110
111
112
113
import React, { useState } from "react";
import AuthPresenter from "./AuthPresenter";
import useInput from "../../Hooks/useInput";
import { useMutation } from "react-apollo-hooks";
import {
LOG_IN,
CREATE_ACCOUNT,
CONFIRM_SECRET,
LOCAL_LOG_IN
} from "./AuthQueries";
import { toast } from "react-toastify";
export default () => {
const [action, setAction] = useState("logIn");
const username = useInput("");
const firstName = useInput("");
const lastName = useInput("");
const secret = useInput("");
const email = useInput("");
const requestSecretMutation = useMutation(LOG_IN, {
variables: { email: email.value }
});
const createAccountMutation = useMutation(CREATE_ACCOUNT, {
variables: {
email: email.value,
username: username.value,
firstName: firstName.value,
lastName: lastName.value
}
});
const confirmSecretMutation = useMutation(CONFIRM_SECRET, {
variables: {
email: email.value,
secret: secret.value
}
});
const localLogInMutation = useMutation(LOCAL_LOG_IN);
const onSubmit = async e => {
e.preventDefault();
if (action === "logIn") {
if (email.value !== "") {
try {
const {
data: { requestSecret }
} = await requestSecretMutation();
if (!requestSecret) {
toast.error("You dont have an account yet, create one");
setTimeout(() => setAction("signUp"), 3000);
} else {
toast.success("Check your inbox for your login secret");
setAction("confirm");
}
} catch {
toast.error("Can't request secret, try again");
}
} else {
toast.error("Email is required");
}
} else if (action === "signUp") {
if (
email.value !== "" &&
username.value !== "" &&
firstName.value !== "" &&
lastName.value !== ""
) {
try {
const {
data: { createAccount }
} = await createAccountMutation();
if (!createAccount) {
toast.error("Can't create account");
} else {
toast.success("Account created! Log In now");
setTimeout(() => setAction("logIn"), 3000);
}
} catch (e) {
toast.error(e.message);
}
} else {
toast.error("All field are required");
}
} else if (action === "confirm") {
if (secret.value !== "") {
try {
const {
data: { confirmSecret: token }
} = await confirmSecretMutation();
if (token !== "" && token !== undefined) {
localLogInMutation({ variables: { token } });
} else {
throw Error();
}
} catch {
toast.error("Cant confirm secret,check again");
}
}
}
};
return (
<AuthPresenter
setAction={setAction}
action={action}
username={username}
firstName={firstName}
lastName={lastName}
email={email}
secret={secret}
onSubmit={onSubmit}
/>
);
};