/
Login.js
276 lines (252 loc) · 8.31 KB
/
Login.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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import React, { useState,useReducer, useEffect } from "react";
import { useForm } from "react-hook-form";
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import CardHeader from "@material-ui/core/CardHeader";
import Button from "@material-ui/core/Button";
import { useAuth } from "../contexts/AuthContext"
import { Link , useHistory} from "react-router-dom"
import {TwitterSingUpLogin } from "./firebaseprovider/Twitter"
const useStyles = makeStyles((theme: Theme) =>
createStyles({
container: {
display: "flex",
flexWrap: "wrap",
width: 400,
margin: `${theme.spacing(0)} auto`
},
loginBtn: {
marginTop: theme.spacing(2),
flexGrow: 1
},
header: {
textAlign: "center",
background: "#212121",
color: "#fff"
},
card: {
marginTop: theme.spacing(10)
}
})
);
//state type
type State = {
username: string,
password: string,
isButtonDisabled: boolean,
helperText: string,
isError: boolean
};
const initialState: State = {
username: "",
password: "",
isButtonDisabled: true,
helperText: "",
isError: false
};
type Action =
| { type: "setUsername", payload: string }
| { type: "setPassword", payload: string }
| { type: "setIsButtonDisabled", payload: boolean }
| { type: "loginSuccess", payload: string }
| { type: "loginFailed", payload: string }
| { type: "setIsError", payload: boolean };
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "setUsername":
return {
...state,
username: action.payload
};
case "setPassword":
return {
...state,
password: action.payload
};
case "setIsButtonDisabled":
return {
...state,
isButtonDisabled: action.payload
};
case "loginSuccess":
return {
...state,
helperText: action.payload,
isError: false
};
case "loginFailed":
return {
...state,
helperText: action.payload,
isError: true
};
case "setIsError":
return {
...state,
isError: action.payload
};
default:
return state;
}
};
const Login = () => {
const classes = useStyles();
const [state, dispatch] = useReducer(reducer, initialState);
const [error, setError] = useState("")
const { login } = useAuth()
const { register, handleSubmit, errors, trigger } = useForm();
const history = useHistory()
useEffect(() => {
if (state.username.trim() && state.password.trim()){
//trigger();
dispatch({
type: "setIsButtonDisabled",
payload: false
});
} else {
//clearErrors()
dispatch({
type: "setIsButtonDisabled",
payload: true
});
}
}, [state.username, state.password]);
async function handleLogin (data) { //react-hook-formを導入したためevent -> dataに変更
//event.preventDefault() //react-hook-formを導入したため削除
try {
setError("")
//sing up ボタンの無効化
dispatch({
type: "setIsButtonDisabled",
payload: true
});
await login(state.username, state.password)
history.push("/dashboard")
} catch (e){
//エラーのメッセージの表示
switch (e.code) {
case "auth/network-request-failed":
setError("通信がエラーになったのか、またはタイムアウトになりました。通信環境がいい所で再度やり直してください。");
break;
case "auth/weak-password":
setError("メールアドレスまたはパスワードが間違えています。");
break;
case "auth/invalid-email":
setError("メールアドレスまたはパスワードが間違えています。");
break;
case "auth/user-not-found":
setError("メールアドレスまたはパスワードが間違えています。");
break;
case "auth/user-disabled":
setError("入力されたメールアドレスは無効(BAN)になっています。");
break;
case "auth/wrong-password":
setError("メールアドレスまたはパスワードが間違えています。");
break;
default: //想定外
setError("ログインに失敗しました。通信環境がいい所で再度やり直してください。");
console.log(e)
}
//dispatch({
// type: "loginFailed",
// payload: "Incorrect username or password"
//});
//sing up ボタンの有効化
dispatch({
type: "setIsButtonDisabled",
payload: false
});
}
};
const handleKeyPress = (event: React.KeyboardEvent) => {
if (event.keyCode === 13 || event.which === 13) {
if (!state.isButtonDisabled){
handleKeyPresstrigger()
if (errors) {
//errorメッセージを表示する
} else {
handleLogin()
}
}
}
};
async function handleKeyPresstrigger () {
const result = await trigger();
return result
}
const handleUsernameChange: React.ChangeEventHandler<HTMLInputElement> = (
event
) => {
dispatch({
type: "setUsername",
payload: event.target.value
});
};
const handlePasswordChange: React.ChangeEventHandler<HTMLInputElement> = (
event
) => {
dispatch({
type: "setPassword",
payload: event.target.value
});
};
return (
<form className={classes.container} noValidate autoComplete="off">
<Card className={classes.card}>
<CardHeader className={classes.header} title="Login" />
<CardContent>
<div>
{error && <div style={{ color: "red" }}>{error}</div>}
<TextField
error={state.isError}
fullWidth
id="username"
name="username"
type="email"
label="Username"
placeholder="Username"
margin="normal"
onChange={handleUsernameChange}
onKeyPress={handleKeyPress}
inputRef={register({pattern: /^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/ })}
/>
{errors.username?.type === "pattern" &&
<div style={{ color: "red" }}>メールアドレスの形式で入力されていません</div>}
<TextField
error={state.isError}
fullWidth
id="password"
name="password"
type="password"
label="Password"
placeholder="Password"
margin="normal"
onChange={handlePasswordChange}
onKeyPress={handleKeyPress}
inputRef={register({ required: true, minLength: 6 })}
/>
{errors.password?.type === "minLength" &&
<div style={{ color: "red" }}>パスワードは6文字以上で入力してください</div>}
</div>
もしアカウントがないなら<Link to="/signup">こちら</Link>からアカウントを作成してください
<Button
fullWidth
variant="contained"
size="large"
color="secondary"
className={classes.loginBtn}
onClick={handleSubmit(handleLogin)}
disabled={state.isButtonDisabled}
>
Login
</Button>
もしくは
<TwitterSingUpLogin title="TwitterでLoginする"/>
</CardContent>
</Card>
</form>
);
};
export default Login;