Commit 0ffaebc2 authored by CHAERIN KIM's avatar CHAERIN KIM
Browse files

로그인 회원가입 완료

parents 5ac3a10f 694af28b
JWT_SECRET=jwtSecret
\ No newline at end of file
node_modules
\ No newline at end of file
node_modules
......@@ -6,11 +6,18 @@ const logger = require('morgan');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const loginRouter = require('./routes/login');
const connect = require('./schemas');
const app = express();
const port = 3030;
require('dotenv').config();
connect();
app.listen(port, () => console.log(port));
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug');
......@@ -23,6 +30,7 @@ app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
......@@ -37,7 +45,7 @@ app.use(function(err, req, res, next) {
// render the error page
res.status(err.status || 500);
res.render('error');
// res.render('error');
});
module.exports = app;
......@@ -5,7 +5,7 @@
*/
var app = require('../app');
var debug = require('debug')('learn-express:server');
var debug = require('debug')('server:server');
var http = require('http');
/**
......
......@@ -1756,9 +1756,15 @@
"integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA=="
},
"@types/node": {
<<<<<<< HEAD
"version": "14.11.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-14.11.1.tgz",
"integrity": "sha512-oTQgnd0hblfLsJ6BvJzzSL+Inogp3lq9fGgqRkMB/ziKMgEUaFl801OncOzUmalfzt14N0oPHMK47ipl+wbTIw=="
=======
"version": "14.10.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-14.10.3.tgz",
"integrity": "sha512-zdN0hor7TLkjAdKTnYW+Y22oIhUUpil5ZD1V1OFq0CR0CLKw+NdR6dkziTfkWRLo6sKzisayoj/GNpNbe4LY9Q=="
>>>>>>> origin/NewMaster
},
"@types/parse-json": {
"version": "4.0.0",
......@@ -3448,9 +3454,15 @@
}
},
"caniuse-lite": {
<<<<<<< HEAD
"version": "1.0.30001133",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001133.tgz",
"integrity": "sha512-s3XAUFaC/ntDb1O3lcw9K8MPeOW7KO3z9+GzAoBxfz1B0VdacXPMKgFUtG4KIsgmnbexmi013s9miVu4h+qMHw=="
=======
"version": "1.0.30001131",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001131.tgz",
"integrity": "sha512-4QYi6Mal4MMfQMSqGIRPGbKIbZygeN83QsWq1ixpUwvtfgAZot5BrCKzGygvZaV+CnELdTwD0S4cqUNozq7/Cw=="
>>>>>>> origin/NewMaster
},
"capture-exit": {
"version": "2.0.0",
......@@ -4372,11 +4384,19 @@
}
},
"debug": {
<<<<<<< HEAD
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.2.0.tgz",
"integrity": "sha512-IX2ncY78vDTjZMFUdmsvIRFY2Cf4FnD0wRs+nQwJU8Lu99/tPFdb0VybiiMTPe3I6rQmwsqQqRBvxU+bZ/I8sg==",
"requires": {
"ms": "2.1.2"
=======
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
"integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
"requires": {
"ms": "^2.1.1"
>>>>>>> origin/NewMaster
}
},
"decamelize": {
......@@ -7791,11 +7811,14 @@
}
}
},
<<<<<<< HEAD
"jquery": {
"version": "3.5.1",
"resolved": "https://registry.npmjs.org/jquery/-/jquery-3.5.1.tgz",
"integrity": "sha512-XwIBPqcMn57FxfT+Go5pzySnm4KWkT1Tv7gjrpT1srtf8Weynl6R273VJ5GjkRb51IzMp5nbaPjJXMWeju2MKg=="
},
=======
>>>>>>> origin/NewMaster
"js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
......@@ -9430,11 +9453,14 @@
"ts-pnp": "^1.1.6"
}
},
<<<<<<< HEAD
"popper.js": {
"version": "1.16.1",
"resolved": "https://registry.npmjs.org/popper.js/-/popper.js-1.16.1.tgz",
"integrity": "sha512-Wb4p1J4zyFTbM+u6WuO4XstYx4Ky9Cewe4DWrel7B0w6VVICvPwdOpotjzcf6eD8TsckVnIMNONQyPIUFOUbCQ=="
},
=======
>>>>>>> origin/NewMaster
"portfinder": {
"version": "1.0.28",
"resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.28.tgz",
......@@ -9782,9 +9808,15 @@
}
},
"postcss-load-config": {
<<<<<<< HEAD
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-2.1.1.tgz",
"integrity": "sha512-D2ENobdoZsW0+BHy4x1CAkXtbXtYWYRIxL/JbtRBqrRGOPtJ2zoga/bEZWhV/ShWB5saVxJMzbMdSyA/vv4tXw==",
=======
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-2.1.0.tgz",
"integrity": "sha512-4pV3JJVPLd5+RueiVVB+gFOAa7GWc25XQcMp86Zexzke69mKf6Nx9LRcQywdz7yZI9n1udOxmLuAwTBypypF8Q==",
>>>>>>> origin/NewMaster
"requires": {
"cosmiconfig": "^5.0.0",
"import-cwd": "^2.0.0"
......@@ -10333,6 +10365,7 @@
}
},
"postcss-selector-parser": {
<<<<<<< HEAD
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.3.tgz",
"integrity": "sha512-0ClFaY4X1ra21LRqbW6y3rUbWcxnSVkDFG57R7Nxus9J9myPFlv+jYDMohzpkBx0RrjjiqjtycpchQ+PLGmZ9w==",
......@@ -10341,6 +10374,15 @@
"indexes-of": "^1.0.1",
"uniq": "^1.0.1",
"util-deprecate": "^1.0.2"
=======
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.2.tgz",
"integrity": "sha512-36P2QR59jDTOAiIkqEprfJDsoNrvwFei3eCqKd1Y0tUsBimsq39BLp7RD+JWny3WgB1zGhJX8XVePwm9k4wdBg==",
"requires": {
"cssesc": "^3.0.0",
"indexes-of": "^1.0.1",
"uniq": "^1.0.1"
>>>>>>> origin/NewMaster
}
},
"postcss-svgo": {
......@@ -11129,9 +11171,15 @@
"integrity": "sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q=="
},
"regexpu-core": {
<<<<<<< HEAD
"version": "4.7.1",
"resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.7.1.tgz",
"integrity": "sha512-ywH2VUraA44DZQuRKzARmw6S66mr48pQVva4LBeRhcOltJ6hExvWly5ZjFLYo67xbIxb6W1q4bAGtgfEl20zfQ==",
=======
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.7.0.tgz",
"integrity": "sha512-TQ4KXRnIn6tz6tjnrXEkD/sshygKH/j5KzK86X8MkeHyZ8qst/LZ89j3X4/8HEIfHANTFIP/AbXakeRhWIl5YQ==",
>>>>>>> origin/NewMaster
"requires": {
"regenerate": "^1.4.0",
"regenerate-unicode-properties": "^8.2.0",
......
......@@ -24,6 +24,7 @@
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:3030",
"eslintConfig": {
"extends": "react-app"
},
......
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
const Nav = styled.nav`
background-color: #981e1e;
`
function Menu() {
return (
<Nav className="navbar sticky-top navbar-expand-md">
<Link to="/home" className="navbar-brand">대관 서비스</Link>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar" aria-controls="collapsibleNavbar">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="collapsibleNavbar">
<ul className="navbar-nav">
<li className="nav-item">
<Link to="/home" className="nav-link">대관 현황</Link>
</li>
<li className="nav-item">
<Link to="/apply" className="nav-link">대관 신청</Link>
</li>
<li className="nav-item">
<Link to="/check" className="nav-link">대관 확인/취소</Link>
</li>
<li className="nav-item">
<Link to="/notice" className="nav-link">공지사항</Link>
</li>
</ul>
</div>
</Nav>
)
}
export default Menu
\ No newline at end of file
import React, { useState, useEffect } from 'react';
import Menu from '../Components/Menu';
function Apply() {
return (
<div>
<Menu />
<div className="container">apply
</div>
</div>
)
}
export default Apply
\ No newline at end of file
import React, { useState, useEffect } from 'react';
import Menu from '../Components/Menu';
function Check() {
return (
<div>
<Menu />
<div className="container">check
</div>
</div>
)
}
export default Check
\ No newline at end of file
import React, { useState, useEffect } from 'react';
import Menu from '../Components/Menu';
import { Link, Redirect } from 'react-router-dom';
function Home() {
return (
<div>
<Menu />
<div className="container">
home
<button><Link to="/">로그인</Link></button>
<button><Link to="/signup">회원가입</Link></button>
</div>
</div>
)
}
export default Home
\ No newline at end of file
import React, { useState } from 'react';
import styled from 'styled-components';
import { Link, Redirect } from 'react-router-dom';
import { Formik } from 'formik';
import * as Yup from 'yup';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.css';
const Log = styled.div`
background-color: #981e1e;
`
const Logo = styled.div`
background-color: #E76A6A;
`
function Login() {
const [state, setState]= useState(false);
if (state) {
return <Redirect to="/home" />;
}
return (
<div className="container-fluid">
<div className="row">
<Logo className="col-md-5 col-12">
<h2>고려대학교</h2>
<h4>대관 시스템</h4>
</Logo>
<Log className="col-md-7 col-12">
<Formik
initialValues={{ id: '', password: '' }}
validationSchema={Yup.object({
id: Yup.string()
.required('아이디를 입력해주세요.'),
password: Yup.string()
.required('비밀번호를 입력해주세요.')
.min(8, '8자 이상 입력해주세요.'),
})}
onSubmit={(values, { setSubmitting }) => {
axios({
method: 'post',
url: '/login',
data: values,
}).then(res => {
if (res.status === 404) return alert(res.data.error)
alert("로그인이 완료되었습니다!")
localStorage.setItem('token', res.data.token);
localStorage.setItem('id', res.data.users._id);
setState(true);
})
.catch(err => {
alert(err.error)
});
setTimeout(() => {
setSubmitting(false);
}, 400); // finish the cycle in handler
}}
>
{({
errors,
touched,
handleSubmit,
getFieldProps, // contain values, handleChange, handleBlur
isSubmitting,
}) => (
<div className="row justify-content-center align-items-center">
<form onSubmit={handleSubmit} className="col-sm-3">
<div className="form-group mb-4">
<input
className={(touched.id && errors.id ? 'form-control is-invalid' : "form-control")}
type="text"
name="id"
{...getFieldProps('id')}
placeholder="Input id"
/>
{touched.id && errors.id ? (
<div className="invalid-feedback text-left">{errors.id}</div>
) : null}
</div>
<div className="form-group mb-4">
<input
className={(touched.password && errors.password ? 'form-control is-invalid' : "form-control")}
type="password"
name="password"
{...getFieldProps('password')}
placeholder="Input Password"
/>
{touched.password && errors.password ? (
<div className="invalid-feedback text-left">{errors.password}</div>
) : null}
</div>
<button type="submit" className="btn btn-dark" disabled={isSubmitting}>
Login
</button>
<button><Link to="/home"></Link></button>
<Link to="/signup">비밀번호를 잊으셨나요?</Link>
<div></div>
<Link to="/signup">회원이 아니신가요?</Link>
</form>
</div>
)}
</Formik>
</Log>
</div>
</div>
)
}
export default Login
\ No newline at end of file
import React, { useState, useEffect } from 'react';
import Menu from '../Components/Menu';
function Notice() {
return (
<div>
<Menu />
<div className="container">notice
</div>
</div>
)
}
export default Notice
\ No newline at end of file
import React, { useState } from 'react';
import { Formik } from 'formik';
import * as Yup from 'yup';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.css';
import { Link, Redirect } from 'react-router-dom';
function Signup() {
const [state, setState] = useState(false);
if (state) {
return <Redirect to="/login" />;
}
return (
<div className="d-flex flex-column justify-content-between vh-100">
<Formik
initialValues={{ name: '', id: '', password: '', password2: ''}}
validationSchema={Yup.object({
name: Yup.string()
.required('이름을 입력해주세요.'),
id: Yup.string()
.required('아이디를 입력해주세요.'),
password: Yup.string()
.required('비밀번호를 입력해주세요.')
.min(8, '8자 이상 입력해주세요.'),
password2: Yup.string()
.required('비밀번호를 다시 입력해주세요.')
.min(8, '8자 이상 입력해주세요.')
.oneOf([Yup.ref("password"), null], '비밀번호가 일치하지 않습니다.'),
})}
onSubmit={(values, { setSubmitting }) => {
axios({
method: 'post',
url: '/users',
data: values,
}).then(res => {
if (res.status === 404) return alert(res.data.error)
alert("회원가입이 완료되었습니다!")
setState(true);
})
.catch(err => {
alert(err.error)
});
setTimeout(() => {
setSubmitting(false);
}, 400); // finish the cycle in handler
}}
>
{({
errors,
touched,
handleSubmit,
getFieldProps, // contain values, handleChange, handleBlur
isSubmitting,
}) => (
<div className="row justify-content-center align-items-center">
<form onSubmit={handleSubmit} className="col-sm-3">
<div className="form-group mb-4">
<input
className={(touched.name && errors.name ? 'form-control is-invalid' : "form-control")}
type="text"
name="name"
{...getFieldProps('name')}
placeholder="Input Name" />
{touched.name && errors.name ? (
<div className="invalid-feedback text-left">{errors.name}</div>
) : null}
</div>
<div className="form-group mb-4">
<input
className={(touched.id && errors.id ? 'form-control is-invalid' : "form-control")}
type="text"
name="id"
{...getFieldProps('id')}
placeholder="Input id"
/>
{touched.id && errors.id ? (
<div className="invalid-feedback text-left">{errors.id}</div>
) : null}
</div>
<div className="form-group mb-4">
<input
className={(touched.password && errors.password ? 'form-control is-invalid' : "form-control")}
type="password"
name="password"
{...getFieldProps('password')}
placeholder="Input Password"
/>
{touched.password && errors.password ? (
<div className="invalid-feedback text-left">{errors.password}</div>
) : null}
</div>
<div className="form-group mb-4">
<input
className={(touched.password2 && errors.password2 ? 'form-control is-invalid' : "form-control")}
type="password"
name="password2"
{...getFieldProps('password2')}
placeholder="Input Confirm Password"
/>
{touched.password2 && errors.password2 ? (
<div className="invalid-feedback text-left">{errors.password2}</div>
) : null}
</div>
<button type="submit" className="btn btn-dark" disabled={isSubmitting}>
Sign Up
</button>
<button><Link to="/">로그인</Link></button>
<button><Link to="/home"></Link></button>
</form>
</div>
)}
</Formik>
</div>
);
}
export default Signup;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.css';
import axios from 'axios';
//import { PrivateRoute } from './PrivateRoute';
import Login from './Pages/LoginPage';
import Home from './Pages/HomePage';
import Signup from './Pages/SignupPage';
import Apply from './Pages/ApplyPage';
import Check from './Pages/CheckPage';
import Notice from './Pages/NoticePage';
axios.defaults.validateStatus = function (status) {
return status < 500; // default
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
<Router>
<Switch>
<Route exact path="/" component={Login} />
<Route path="/home" component={Home} />
<Route path="/signup" component={Signup} />
<Route path="/apply" component={Apply} />
<Route path="/check" component={Check} />
<Route path="/notice" component={Notice} />
<Redirect path="/login" to="/" />
<Redirect path="/home" to="/" />
</Switch>
</Router>,
document.getElementById('root')
);
......
This diff is collapsed.
{
"name": "learn-express",
"name": "server",
"version": "0.0.0",
"private": true,
"scripts": {
......@@ -15,8 +15,9 @@
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.10.6",
"morgan": "~1.9.1",
"pug": "2.0.0-beta11",
"pug": "^3.0.0",
"react": "^16.13.1"
}
}
const express = require('express');
const User = require('../schemas/user');
const bcrypt = require("bcrypt");
const jwt = require('jsonwebtoken');
const router = express.Router();
router.get('/', function (req, res, next) {
console.log('/login get request', req.body)
User.find({})
.then((signups) => {
res.json(signups);
})
.catch((err) => {
console.error(err);
next(err);
});
});
router.post('/', function (req, res, next) {
console.log('/login post request', req.body)
User.findOne({ id: req.body.id }, 'id password', function (err, users) {
if (err) return res.status(500).json({ error: err });
if (!users) {
return res.status(404).json({ error: '해당 아이디가 존재하지 않습니다.' });
}
bcrypt.compare(req.body.password, users.password, function (err, result) {
if (err) {
console.log(err)
return res.status(500).json({ error: err });
}
if (result) {
const token = jwt.sign({
id:users.id,
}, process.env.JWT_SECRET, {
expiresIn: '10m', // 12시간
});
return res.status(201).json({
token,
users,
});
}
res.status(404).json({ error: '비밀번호를 다시 입력해주세요.' });
});
})
});
module.exports = router;
const jwt = require('jsonwebtoken');
exports.isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
next();
} else {
res.status(403).send('로그인 필요');
}
};
exports.isNotLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
next();
} else {
res.redirect('/');
}
};
exports.verifyToken = (req, res, next) => {
try {
req.decoded = jwt.verify(req.headers.authorization, process.env.JWT_SECRET);
console.log('decode', req.decoded)
return next();
} catch (error) {
if (error.name === 'TokenExpiredError') { // 유효기간 초과
return res.status(419).json({
code: 419,
error: '토큰이 만료되었습니다. 다시 로그인 해주세요.',
});
}
return res.status(401).json({
code: 401,
error: '유효하지 않은 토큰입니다. 다시 로그인 해주세요.',
});
}
};
......@@ -6,7 +6,7 @@ module.exports = () => {
mongoose.set('debug', true);
}
mongoose.connect('mongodb://cherry:1q2w3e4r@localhost:27017/admin', {
dbName: 'ku_rental',
dbName: 'ku_rental', useNewUrlParser: true, useUnifiedTopology: true,
}, (error) => {
if (error) {
console.log('몽고디비 연결 에러', error);
......
extends layout
block content
h1= message
h2= error.status
pre #{error.stack}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment