Commit 94464e75 authored by Ha YeaJin's avatar Ha YeaJin
Browse files

merge 끝~

parents 03f3cef8 e67fdeae
JWT_SECRET=jwtSecret
\ No newline at end of file
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
node_modules
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
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;
var app = express();
require('dotenv').config();
connect();
const port = 3030;
app.listen(port, () => console.log(port));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
......@@ -24,6 +30,8 @@ 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) {
......@@ -38,7 +46,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;
This diff is collapsed.
......@@ -7,8 +7,11 @@
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.20.0",
"bcrypt": "^5.0.0",
"bootstrap": "^4.5.2",
"formik": "^2.1.5",
"jquery": "^3.5.1",
"popper.js": "^1.16.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
......@@ -22,7 +25,6 @@
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:3030",
"eslintConfig": {
"extends": "react-app"
},
......@@ -37,5 +39,6 @@
"last 1 firefox version",
"last 1 safari version"
]
}
},
"proxy": "http://localhost:3030"
}
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Link, Redirect } from 'react-router-dom';
import styled from 'styled-components';
const Nav = styled.nav`
......@@ -7,13 +7,23 @@ const Nav = styled.nav`
`
function Menu() {
const [state, setState] = useState()
if (state) return <Redirect to="/" />;
function logout() {
localStorage.removeItem('token');
alert("로그아웃 되었습니다.");
setState(true);
}
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">
<div className="collapse navbar-collapse justify-content-between" id="collapsibleNavbar">
<ul className="navbar-nav">
<li className="nav-item">
<Link to="/home" className="nav-link">대관 현황</Link>
......@@ -27,8 +37,11 @@ function Menu() {
<li className="nav-item">
<Link to="/notice" className="nav-link">공지사항</Link>
</li>
</ul>
<div>
<button onClick={logout} type="button">로그아웃</button>
<button><Link to="/signup">회원가입</Link></button>
</div>
</div>
</Nav>
)
......
import React from 'react';
import { Redirect, Route } from "react-router-dom";
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
(localStorage.getItem("token") !==null) ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: "/login",
state: {match: props.location}
}} />
)
}
/>
)
\ 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 (
......@@ -7,6 +8,8 @@ function Home() {
<Menu />
<div className="container">
home
<button><Link to="/login">로그인</Link></button>
<button><Link to="/signup">회원가입</Link></button>
</div>
</div>
)
......
import React, { } from 'react';
import React, { useState } from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
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;
......@@ -13,6 +15,11 @@ const Logo = styled.div`
function Login() {
const [state, setState]= useState(false);
if (state) {
return <Redirect to="/home" />;
}
return (
<div className="container-fluid">
<div className="row">
......@@ -22,31 +29,30 @@ function Login() {
</Logo>
<Log className="col-md-7 col-12">
<Formik
initialValues={{ email: '', password: '' }}
initialValues={{ id: '', password: '' }}
validationSchema={Yup.object({
email: Yup.string()
.email('이메일형식이 유효하지 않습니다.')
.required('이메일을 입력해주세요.'),
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)
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)
// });
localStorage.setItem('token', res.data.token);
localStorage.setItem('id', res.data.users._id);
setState(true);
})
.catch(err => {
alert(err.error)
});
setTimeout(() => {
setSubmitting(false);
......@@ -64,14 +70,14 @@ function Login() {
<form onSubmit={handleSubmit} className="col-sm-3">
<div className="form-group mb-4">
<input
className={(touched.email && errors.email ? 'form-control is-invalid' : "form-control")}
type="email"
name="email"
{...getFieldProps('email')}
placeholder="Input Email"
className={(touched.id && errors.id ? 'form-control is-invalid' : "form-control")}
type="number"
name="id"
{...getFieldProps('id')}
placeholder="Input Student Id"
/>
{touched.email && errors.email ? (
<div className="invalid-feedback text-left">{errors.email}</div>
{touched.id && errors.id ? (
<div className="invalid-feedback text-left">{errors.id}</div>
) : null}
</div>
<div className="form-group mb-4">
......@@ -89,8 +95,8 @@ function Login() {
<button type="submit" className="btn btn-dark" disabled={isSubmitting}>
Login
</button>
<button>
<Link to="/home">gha</Link></button>
<button><Link to="/home"></Link></button>
<div></div>
<Link to="/signup">비밀번호를 잊으셨나요?</Link>
<div></div>
<Link to="/signup">회원이 아니신가요?</Link>
......
......@@ -6,22 +6,21 @@ import 'bootstrap/dist/css/bootstrap.css';
import { Link, Redirect } from 'react-router-dom';
function Signup() {
// const [state, setState] = useState(false);
const [state, setState] = useState(false);
// if (state) {
// return <Redirect to="/login" />;
// }
if (state) {
return <Redirect to="/login" />;
}
return (
<div className="d-flex flex-column justify-content-between vh-100">
<Formik
initialValues={{ name: '', email: '', password: '', password2: '', address: '', }}
initialValues={{ name: '', id: '', password: '', password2: ''}}
validationSchema={Yup.object({
name: Yup.string()
.required('이름을 입력해주세요.'),
email: Yup.string()
.email('이메일형식이 유효하지 않습니다.')
.required('이메일을 입력해주세요.'),
id: Yup.string()
.required('학번을 입력해주세요.'),
password: Yup.string()
.required('비밀번호를 입력해주세요.')
.min(8, '8자 이상 입력해주세요.'),
......@@ -29,23 +28,21 @@ function Signup() {
.required('비밀번호를 다시 입력해주세요.')
.min(8, '8자 이상 입력해주세요.')
.oneOf([Yup.ref("password"), null], '비밀번호가 일치하지 않습니다.'),
address: Yup.string()
.required('주소를 입력해주세요.')
})}
onSubmit={(values, { setSubmitting }) => {
// axios({
// method: 'post',
// url: '/users',
// data: values,
// }).then(res => {
// if (res.status === 404) return alert(res.data.error)
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)
// });
setState(true);
})
.catch(err => {
alert(err.error)
});
setTimeout(() => {
setSubmitting(false);
......@@ -74,25 +71,14 @@ function Signup() {
</div>
<div className="form-group mb-4">
<input
className={(touched.email && errors.email ? 'form-control is-invalid' : "form-control")}
type="email"
name="email"
{...getFieldProps('email')}
placeholder="Input Email"
className={(touched.id && errors.id ? 'form-control is-invalid' : "form-control")}
type="number"
name="id"
{...getFieldProps('id')}
placeholder="Input Student Id"
/>
{touched.email && errors.email ? (
<div className="invalid-feedback text-left">{errors.email}</div>
) : null}
</div>
<div className="form-group mb-4">
<input
className={(touched.address && errors.address ? 'form-control is-invalid' : "form-control")}
type="text"
name="address"
{...getFieldProps('address')}
placeholder="Input Address" />
{touched.address && errors.address ? (
<div className="invalid-feedback text-left">{errors.address}</div>
{touched.id && errors.id ? (
<div className="invalid-feedback text-left">{errors.id}</div>
) : null}
</div>
<div className="form-group mb-4">
......@@ -122,8 +108,8 @@ function Signup() {
<button type="submit" className="btn btn-dark" disabled={isSubmitting}>
Sign Up
</button>
<button>
<Link to="/">gha</Link></button>
<button><Link to="/login">로그인</Link></button>
<button><Link to="/"></Link></button>
</form>
</div>
)}
......
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
......@@ -2,7 +2,10 @@ import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.css';
// import 'bootstrap';
// import 'bootstrap/dist/css/bootstrap.css';
import axios from 'axios';
import { PrivateRoute } from './Components/PrivateRoute';
import Login from './Pages/LoginPage';
import Home from './Pages/HomePage';
......@@ -11,15 +14,22 @@ 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(
<Router>
<Switch>
<Route exact path="/" component={Login} />
<PrivateRoute exact path="/" component={Home} />
<Route path="/login" 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')
......
......@@ -864,9 +864,9 @@
}
},
"mongoose": {
"version": "5.10.5",
"resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.10.5.tgz",
"integrity": "sha512-BOQZsZn9Y79f3rWZFLD1gvOLNN5gOiGvGr5raqQ5v/T4fdAmnjXGCVynpW4SRnQLtrcCeLXyaaXVRT75863Q0w==",
"version": "5.10.6",
"resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.10.6.tgz",
"integrity": "sha512-p32oja2ydzFMS0K4P7G408Kagju6Qz/LmiAFAcP6BqnIi1McLTd6VZ3+ZQtQmaHM7w8iNupLLambCrsPKNJpYw==",
"requires": {
"bson": "^1.1.4",
"kareem": "2.3.1",
......@@ -966,9 +966,9 @@
"integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
},
"node-addon-api": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.0.0.tgz",
"integrity": "sha512-sSHCgWfJ+Lui/u+0msF3oyCgvdkhxDbkCS6Q8uiJquzOimkJBvX6hl5aSSA7DR1XbMpdM8r7phjcF63sF4rkKg=="
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.0.2.tgz",
"integrity": "sha512-+D4s2HCnxPd5PjjI0STKwncjXTUKKqm74MDMz9OPXavjsGmjkvwgLtA5yoxJUdmpj52+2u+RrXgPipahKczMKg=="
},
"node-pre-gyp": {
"version": "0.15.0",
......
......@@ -10,11 +10,11 @@
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"dotenv": "^8.2.0",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"express": "^4.17.1",
"http-errors": "^1.6.3",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.10.5",
"mongoose": "^5.10.6",
"morgan": "~1.9.1",
"pug": "2.0.0-beta11"
"pug": "^3.0.0"
}
}
var express = require('express');
var router = express.Router();
const express = require('express');
const User = require('../schemas/user');
const router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
// router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
// });
module.exports = router;
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: '1m',
});
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: '유효하지 않은 토큰입니다. 다시 로그인 해주세요.',
});
}
};
var express = require('express');
var router = express.Router();
const express = require('express');
const User = require('../schemas/user');
const bcrypt = require("bcrypt");
const { verifyToken } = require('./middlewares');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
const router = express.Router();
router.post('/', function (req, res, next) {
console.log('/users post req.body', req.body)
User.findOne({ id: req.body.id }, function (err, users) {
if (err) return res.status(500).json({ error: err });
if (users) {
return res.status(404).json({ error: '이미 존재하는 아이디입니다.' })
};
const user = new User({
name: req.body.name,
id: req.body.id,
password: req.body.password,
});
user.save()
.then((result) => {
console.log(result);
res.status(201).json(result);
})
.catch((err) => {
console.error(err);
next(err);
});
})
});
module.exports = router;
......@@ -5,8 +5,8 @@ module.exports = () => {
if (process.env.NODE_ENV !== 'production') {
mongoose.set('debug', true);
}
mongoose.connect('mongodb://rkyoung7:rkdud127@localhost:27017/admin', {
dbName: 'KU_Rental',
mongoose.connect('mongodb://hyj:hyj3657@localhost:27017/admin', {
dbName: 'ku_rental', useNewUrlParser: true, useUnifiedTopology: true,
}, (error) => {
if (error) {
console.log('몽고디비 연결 에러', error);
......@@ -20,10 +20,10 @@ module.exports = () => {
console.error('몽고디비 연결 에러', error);
});
mongoose.connection.on('disconnected', () => {
console.error('몽고디비 연결이 끊겼습니다. 연결을재시도합니다.');
console.error('몽고디비 연결이 끊겼습니다. 연결을 재시도합니다.');
connect();
});
require('./user');
require('./reserve');
};
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