auth.js
1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//로그인을 위한 라우터
const express = require('express');
const passport = require('passport');
const bcrypt = require('bcrypt');
const { isLoggedIn, isNotLoggedIn } = require('./middlewares');
const { User } = require('../models');
const router = express.Router();
router.post('/join', isNotLoggedIn, async (req, res, next) => {
const { email, nick, password, money } = req.body;
try {
const exUser = await User.find({ where: { email } });
const exNick = await User.find({where: {nick}});
if (exUser) {
req.flash('joinError', '이미 가입된 이메일입니다.');
return res.redirect('/join');
}
if(exNick){
req.flash('joinError', '이미 존재하는 닉네임입니다.');
return res.redirect('/join');
}
const hash = await bcrypt.hash(password, 12);
await User.create({
email,
nick,
password: hash,
money,
});
return res.redirect('/');
} catch (error) {
console.error(error);
return next(error);
}
});
router.post('/login', isNotLoggedIn, (req, res, next) => {
passport.authenticate('local', (authError, user, info) => {
if (authError) {
console.error(authError);
return next(authError);
}
if (!user) {
req.flash('loginError', info.message);
return res.redirect('/');
}
return req.login(user, (loginError) => {
if (loginError) {
console.error(loginError);
return next(loginError);
}
return res.redirect('/');
});
})(req, res, next);
});
router.get('/logout', isLoggedIn, (req, res) => {
req.logout();
req.session.destroy();
res.redirect('/');
});
module.exports = router;