swa07016

'/api/signin' 백엔드 구현

......@@ -3,4 +3,5 @@ json_datas.json
client/public/images
client/node_modules
client/src/config
database.json
\ No newline at end of file
database.json
jwt_key.json
\ No newline at end of file
......
import React from 'react';
import React, { useState } from 'react';
import { Button, Form, FormGroup, Label, Input} from 'reactstrap';
import {FacebookLoginButton} from 'react-social-login-buttons';
const SigninPage = (props) => {
// const [userName, setUserName] = useState('');
// const [userPw, setuserPw] = useState('');
// const signinApi = (user) => {
// return fetch('/api/signin', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(user)
// }).then(response => response.json())
// }
// const handleSubmit = async (e) => {
// e.preventDefault();
// if (!userId || !userPw) {
// return;
// }
// try {
// const response = await loginApi({
// user_id: userId,
// user_pw: userPw
// });
// if (response.result === 'ok') {
// setToken();
// } else {
// throw new Error(response.error);
// }
// } catch (err) {
// alert('로그인에 실패했습니다.');
// setUserId('');
// setUserPw('');
// console.error('login error', err);
// }
// };
// };
return (
<>
<Form style={{
......
......@@ -105,6 +105,11 @@
"concat-map": "0.0.1"
}
},
"buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk="
},
"bytes": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
......@@ -265,6 +270,14 @@
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz",
"integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups="
},
"ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"requires": {
"safe-buffer": "^5.0.1"
}
},
"ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
......@@ -545,6 +558,49 @@
"resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz",
"integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw=="
},
"jsonwebtoken": {
"version": "8.5.1",
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz",
"integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==",
"requires": {
"jws": "^3.2.2",
"lodash.includes": "^4.3.0",
"lodash.isboolean": "^3.0.3",
"lodash.isinteger": "^4.0.4",
"lodash.isnumber": "^3.0.3",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"lodash.once": "^4.0.0",
"ms": "^2.1.1",
"semver": "^5.6.0"
},
"dependencies": {
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}
}
},
"jwa": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
"integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
"requires": {
"buffer-equal-constant-time": "1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"jws": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
"integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
"requires": {
"jwa": "^1.4.1",
"safe-buffer": "^5.0.1"
}
},
"locate-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz",
......@@ -559,6 +615,41 @@
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
"integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A=="
},
"lodash.includes": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
"integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8="
},
"lodash.isboolean": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
"integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY="
},
"lodash.isinteger": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
"integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M="
},
"lodash.isnumber": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
"integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w="
},
"lodash.isplainobject": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
"integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs="
},
"lodash.isstring": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
"integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE="
},
"lodash.once": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w="
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
......
......@@ -20,6 +20,7 @@
"concurrently": "^5.2.0",
"express": "^4.17.1",
"iconv-lite": "^0.5.1",
"jsonwebtoken": "^8.5.1",
"mysql": "^2.18.1"
}
}
......
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const mysql = require('mysql');
const iconv = require('iconv-lite');
const express = require("express");
const bodyParser = require("body-parser");
const fs = require("fs");
const mysql = require("mysql");
const iconv = require("iconv-lite");
const jwt = require("jsonwebtoken");
const bcrypt = require('bcrypt');
const saltRounds = 10;
const bcrypt = require("bcrypt");
const saltRounds = 10;
const app = express();
const port = process.env.PORT || 5000;
const dataBuffer = fs.readFileSync('json_datas.json')
const dataBuffer = fs.readFileSync("json_datas.json");
const jwt_key = fs.readFileSync("./jwt_key.json");
const jwt_secret_key = JSON.parse(jwt_key);
// db connection
const data = fs.readFileSync('./database.json');
const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);
const connection = mysql.createConnection({
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.database
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.database,
});
connection.connect();
......@@ -30,40 +33,129 @@ connection.connect();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/hello', (req, res) => {
res.send('Hello skrrrr!');
app.get("/api/hello", (req, res) => {
res.send("Hello skrrrr!");
});
// datas 전달
app.get('/api/datas', (req, res) => {
iconv.extendNodeEncodings();
res.header("Access-Control-Allow-Origin", "*");
res.send(iconv.decode(dataBuffer, 'EUC-KR').toString());
})
app.get("/api/datas", (req, res) => {
iconv.extendNodeEncodings();
res.header("Access-Control-Allow-Origin", "*");
res.send(iconv.decode(dataBuffer, "EUC-KR").toString());
});
// ???? ???? ??
// signup
app.post('/api/signup', (req, res) => {
let sql = 'INSERT INTO USER (name, pw) VALUES(?, ?)';
let plainPassword = req.body.password;
bcrypt.hash(plainPassword, saltRounds, function(err, hash) {
app.post("/api/signup", (req, res) => {
let sql = "INSERT INTO USER (name, pw) VALUES(?, ?)";
let plainPassword = req.body.password;
bcrypt.hash(plainPassword, saltRounds, function (err, hash) {
const params = [req.body.username, hash];
connection.query(sql, params, (err, rows, fields) => {
if (err) {
console.log(err);
res.send({
code: 400,
message: "error",
});
} else {
res.send({
code: 200,
message: "success",
});
}
});
});
});
// ????
// res.send({
// "code":200,
// "message": "success"
// })
// ????
// jwt_secret_key.value
// signin
app.post("/api/signin", (req, res) => {
// ????
// res.send('aa');
const name = req.body.username;
let sql = `SELECT name, pw FROM USER WHERE name='${req.body.username}';`;
connection.query(sql, (err, rows, fields) => {
if (!rows) {
res.send({
code: 400,
message: "failed",
});
return ;
}
const params = [req.body.username, hash];
connection.query(sql, params, (err, rows, fields) => {
if(err){
console.log(err);
res.send({
"code":400,
"message": "error"
})
}
else {
res.send({
"code":200,
"message": "success"
})
}
})
else{
bcrypt.compare(req.body.password, rows[0].pw, function (err, result){
const pw = rows[0].pw;
if(result) {
try {
// jwt.sign() ???: ?? ??
const token = jwt.sign(
{
name,
pw,
},
jwt_secret_key.value,
{
expiresIn: "60m", // 60?
issuer: "admin",
}
);
return res.json({
code: 200,
message: '??? ???????.',
token,
});
} catch (error) {
console.error(error);
return res.status(500).json({
code: 500,
message: '?? ??',
});
}
} else {
res.send({
code: 400,
message: "failed",
});
}
})
}
})
})
});
// else {
// bcrypt.compare(req.body.password, rows[0].pw, function (err, res) {
// console.log(res);
// if(!res) {
// res.send({
// code: 400,
// message: "failed",
// });
// }
// else {
// // ???? ??? ?
// const pw = rows[0].pw;
// }
// });
// }
// });
app.listen(port, () => console.log(`Listening on port ${port}`));
\ No newline at end of file
app.listen(port, () => console.log(`Listening on port ${port}`));
......