Commit 23ea3f58 authored by Choi Ga Young's avatar Choi Ga Young
Browse files

Merge remote-tracking branch 'origin/signup' into rkyoung7

parents 91d343d5 90beadc9
# 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
......@@ -3,18 +3,25 @@ const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const port =3030;
require('dotenv').config();
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');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
......@@ -23,6 +30,7 @@ app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.listen(port, () => console.log(port));
......@@ -39,7 +47,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;
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">
......@@ -88,9 +94,9 @@ function Login() {
</div>
<button type="submit" className="btn btn-dark" disabled={isSubmitting}>
Login
</button>
<button>
<Link to="/home">gha</Link></button>
</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">
......@@ -121,9 +107,9 @@ function Signup() {
</div>
<button type="submit" className="btn btn-dark" disabled={isSubmitting}>
Sign Up
</button>
<button>
<Link to="/">gha</Link></button>
</button>
<button><Link to="/login">로그인</Link></button>
<button><Link to="/"></Link></button>
</form>
</div>
)}
......
......@@ -4,6 +4,8 @@ import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
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';
......@@ -12,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')
......
This diff is collapsed.
......@@ -18,3 +18,4 @@
"pug": "2.0.0-beta11"
}
}
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;
......@@ -6,7 +6,7 @@ module.exports = () => {
mongoose.set('debug', true);
}
mongoose.connect('mongodb://rkyoung7:rkdud127@localhost:27017/admin', {
dbName: 'KU_Rental',
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');
};
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