swa07016

jwt 기반 로그인 기능 완성

1 import React, { useState } from 'react'; 1 import React, { useState } from 'react';
2 import { Button, Form, FormGroup, Label, Input} from 'reactstrap'; 2 import { Button, Form, FormGroup, Label, Input} from 'reactstrap';
3 -import {FacebookLoginButton} from 'react-social-login-buttons'; 3 +import { FacebookLoginButton } from 'react-social-login-buttons';
4 -
5 -
6 4
7 const SigninPage = (props) => { 5 const SigninPage = (props) => {
8 6
9 -// const [userName, setUserName] = useState(''); 7 + const [userName, setUserName] = useState('');
10 -// const [userPw, setuserPw] = useState(''); 8 + const [userPw, setUserPw] = useState('');
9 +
10 + const signinApi = (user) => {
11 + return fetch('/api/signin', {
12 + method: 'POST',
13 + headers: {
14 + 'Content-Type': 'application/json'
15 + },
16 + body: JSON.stringify(user)
17 + }).then(response => response.json())
18 + }
19 +
20 + const handleSubmit = async (e) => {
21 + e.preventDefault();
22 + if (!userName || !userPw) {
23 + return;
24 + }
25 + try {
26 + const response = await signinApi({
27 + username: userName,
28 + password: userPw
29 + });
30 +
31 + if (response.message === "Token issue") {
32 + localStorage.setItem("user_token", JSON.stringify(response.token));
33 + alert('Login success');
34 + props.history.push('/');
35 + } else if(response.message === "user does not exist"){
36 + alert('User does not exist');
37 + props.history.push('/signin');
38 + setUserName('');
39 + setUserPw('');
40 + } else if(response.message === "invalid password") {
41 + alert('Invalid Password');
42 + props.history.push('/signin');
43 + setUserName('');
44 + setUserPw('');
45 + } else if(response.message === "server error") {
46 + alert('Server Error');
47 + props.history.push('/signin');
48 + setUserName('');
49 + setUserPw('');
50 + }
51 + } catch (err) {
52 + alert('Signin Failed');
53 + setUserName('');
54 + setUserPw('');
55 + props.history.push('/signin');
56 + }
57 + };
58 +
59 + const onChangeUsername = (e) => {
60 + setUserName(e.target.value);
61 + };
62 +
63 + const onChangePassword = (e) => {
64 + setUserPw(e.target.value);
65 + };
11 66
12 -// const signinApi = (user) => {
13 -// return fetch('/api/signin', {
14 -// method: 'POST',
15 -// headers: {
16 -// 'Content-Type': 'application/json'
17 -// },
18 -// body: JSON.stringify(user)
19 -// }).then(response => response.json())
20 -// }
21 67
22 -// const handleSubmit = async (e) => {
23 -// e.preventDefault();
24 -// if (!userId || !userPw) {
25 -// return;
26 -// }
27 -// try {
28 -// const response = await loginApi({
29 -// user_id: userId,
30 -// user_pw: userPw
31 -// });
32 68
33 -// if (response.result === 'ok') {
34 -// setToken();
35 -// } else {
36 -// throw new Error(response.error);
37 -// }
38 -// } catch (err) {
39 -// alert('로그인에 실패했습니다.');
40 -// setUserId('');
41 -// setUserPw('');
42 -// console.error('login error', err);
43 -// }
44 -// };
45 -// };
46 return ( 69 return (
47 <> 70 <>
48 <Form style={{ 71 <Form style={{
...@@ -60,14 +83,14 @@ const SigninPage = (props) => { ...@@ -60,14 +83,14 @@ const SigninPage = (props) => {
60 <h2 className="text-center"><br/>Sign In</h2> 83 <h2 className="text-center"><br/>Sign In</h2>
61 <FormGroup> 84 <FormGroup>
62 <Label>Username</Label> 85 <Label>Username</Label>
63 - <Input required="required" type="name" placeholder="Enter your name"></Input> 86 + <Input required="required" value={userName} onChange={onChangeUsername} type="name" placeholder="Enter your name" ></Input>
64 </FormGroup> 87 </FormGroup>
65 <FormGroup> 88 <FormGroup>
66 <Label>Password</Label> 89 <Label>Password</Label>
67 - <Input required="required" type="password" placeholder="Enter your password"></Input> 90 + <Input required="required" type="password" value={userPw} onChange={onChangePassword} placeholder="Enter your password"></Input>
68 </FormGroup> 91 </FormGroup>
69 <FormGroup> 92 <FormGroup>
70 - <Button className="btn-lg btn-dark btn-block">Sign in</Button> 93 + <Button type="submit" onClick={handleSubmit} className="btn-lg btn-dark btn-block">Sign in</Button>
71 </FormGroup> 94 </FormGroup>
72 <div className="text-center pt-3"> 95 <div className="text-center pt-3">
73 Or continue with your social account 96 Or continue with your social account
...@@ -80,6 +103,6 @@ const SigninPage = (props) => { ...@@ -80,6 +103,6 @@ const SigninPage = (props) => {
80 103
81 </> 104 </>
82 ); 105 );
83 -}
84 106
107 +};
85 export default SigninPage; 108 export default SigninPage;
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -77,85 +77,66 @@ app.post("/api/signup", (req, res) => { ...@@ -77,85 +77,66 @@ app.post("/api/signup", (req, res) => {
77 // jwt_secret_key.value 77 // jwt_secret_key.value
78 // signin 78 // signin
79 app.post("/api/signin", (req, res) => { 79 app.post("/api/signin", (req, res) => {
80 - // ???? 80 +
81 -// res.send('aa');
82 const name = req.body.username; 81 const name = req.body.username;
83 let sql = `SELECT name, pw FROM USER WHERE name='${req.body.username}';`; 82 let sql = `SELECT name, pw FROM USER WHERE name='${req.body.username}';`;
84 - 83 + let sql_usercheck = `SELECT * FROM USER WHERE name='${req.body.username}';`;
85 - connection.query(sql, (err, rows, fields) => { 84 +
86 - 85 + connection.query(sql_usercheck, (err, rows, fields) => {
87 - if (!rows) { 86 + if(rows.length === 0) {
88 - res.send({ 87 + flag = false;
89 - code: 400, 88 + // console.log(flag);
90 - message: "failed", 89 + return res.send({
91 - }); 90 + code: 400,
92 - return ; 91 + message: "user does not exist",
93 - } 92 + });
94 - 93 + } else {
95 - else{ 94 +
96 - 95 + connection.query(sql, (err, rows, fields) => {
97 - bcrypt.compare(req.body.password, rows[0].pw, function (err, result){ 96 + bcrypt.compare(req.body.password, rows[0].pw, function (err, result){
98 - const pw = rows[0].pw; 97 + const pw = rows[0].pw;
99 - if(result) { 98 + if(result) {
100 -
101 - try {
102 - // jwt.sign() ???: ?? ??
103 - const token = jwt.sign(
104 - {
105 - name,
106 - pw,
107 - },
108 - jwt_secret_key.value,
109 - {
110 - expiresIn: "60m", // 60?
111 - issuer: "admin",
112 - }
113 - );
114 99
115 - return res.json({ 100 + try {
116 - code: 200, 101 + const token = jwt.sign(
117 - message: '??? ???????.', 102 + {
118 - token, 103 + name,
119 - }); 104 + pw,
120 - 105 + },
121 - } catch (error) { 106 + jwt_secret_key.value,
122 - console.error(error); 107 + {
123 - return res.status(500).json({ 108 + expiresIn: "60m",
124 - code: 500, 109 + issuer: "admin",
125 - message: '?? ??',
126 - });
127 } 110 }
128 - 111 + );
129 - } else { 112 +
130 - res.send({ 113 + return res.json({
131 - code: 400, 114 + code: 200,
132 - message: "failed", 115 + message: 'Token issue',
133 - }); 116 + token,
134 - } 117 + });
135 - }) 118 +
136 - } 119 + } catch (error) {
120 + console.error(error);
121 + return res.status(500).json({
122 + code: 500,
123 + message: 'server error',
124 + });
125 +
126 + }
127 +
128 + } else {
129 + return res.json({
130 + code: 400,
131 + message: "invalid password",
132 + });
133 + }
134 + })
135 +
137 }) 136 })
137 + }
138 + })
138 }); 139 });
139 -// else {
140 -// bcrypt.compare(req.body.password, rows[0].pw, function (err, res) {
141 -// console.log(res);
142 -// if(!res) {
143 -// res.send({
144 -// code: 400,
145 -// message: "failed",
146 -// });
147 -// }
148 -// else {
149 -// // ???? ??? ?
150 -// const pw = rows[0].pw;
151 -
152 -// }
153 -// });
154 -
155 -// }
156 -
157 -// });
158 -
159 140
160 141
161 app.listen(port, () => console.log(`Listening on port ${port}`)); 142 app.listen(port, () => console.log(`Listening on port ${port}`));
......