index.js
3.03 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
var express = require('express')
var app = express()
var mysql = require('mysql')
var router = express.Router();
var path = require('path')
var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;
var connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'ksmhjh88',
database: 'nodetest'
})
connection.connect()
router.get('/', function (req, res) {
var msg;
var errMsg = req.flash('error')
if (errMsg)
msg = errMsg;
res.render('login/login.ejs', {'message': msg});
})
passport.serializeUser(function(user, done) {
console.log('passport session save : ', user.id)
done(null, user.id)
})
passport.deserializeUser(function(id, done) {
console.log('passport session get id : ', id)
done(null, id)
})
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, function (req, email, password, done) {
var query = connection.query('select * from user where email=? and password=?', [email,password], function (err, rows) {
//console.log(1)
if (err) {
console.log('error')
return done(err)
}
//console.log(req)
console.log(email)
console.log(password)
console.log(rows.length)
if (rows.length) {
console.log('existed user')
console.log(email)
console.log(rows[0].UID)
return done(null,{'email' : email, 'id' : rows[0].uid})
} else {
return done(null, false, {'message' : 'your login info is not found'})
}
})
console.log('local-login callback called');
}
))
// router.post('/',function(req,res) {
// var body = req.body;
// var email = body.email;
// var name = body.name;
// var password = body.password;
//
//
// // var query = connection.query('insert into user (email,name,password) values ("' + email + '","' + name + '","' + password + '")',
// // function(err,rows) {
// // if(err)throw err;
// // console.log('ok db insert');
// // })
//
// var sql = {email : email, name : name , password : password};
// var query = connection.query('insert into user set ?',sql,function(err,rows){
// if(err) throw err;
//
// console.log('ok db insert : ',rows.insertId,name)
// res.render('welcome.ejs', {'email' : req.body.email,'id':rows.insertId})
// })
//
//
// })
router.post('/',function(req,res,next) {
passport.authenticate('local-login',function(err,user,info) {
if(err) res.status(500).join(err);
if(!user) {
return res.status(401).json(info.message);
}
req.logIn(user,function(err) {
if(err) {
return next(err);
}
return res.json(user);
});
}) (req,res,next);
})
module.exports = router;