-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_passport_mysql.js
304 lines (266 loc) · 8.57 KB
/
app_passport_mysql.js
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
//mysql for session
var MySQLStore = require('express-mysql-session')(session);
//BASIC bkfd2 setting
var bkfd2Password = require("pbkdf2-password");
var hasher = bkfd2Password();
//BASIC passport setting
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// BASIC mysql connection
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'visualmedia',
database: 'o2'
});
connection.connect();
var app = express();
/* this app is going to use bodyparser for post*/
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(session({
secret: '123dfasdf3df3aadfD',
resave: false,
saveUninitialized: true,
store: new MySQLStore({
host: 'localhost',
port: 3306,
user: 'root',
password: 'visualmedia',
database: 'o2'
})
}));
// use for passport
app.use(passport.initialize());
app.use(passport.session());
app.get('/count', function (req, res) {
if (req.session.count) {
req.session.count++;
} else {
req.session.count = 1;
}
res.send('count :' + req.session.count);
})
var users = [
{
username: 'egoing',
password: 'qp0My7BNvunzQ+mRfveNL5Vo21PbwChd6+opJ2AyLlxglS3c1JgvAv3RP1ZSNB7Kw5618BZ2lPCa+tOL7eD6MTXad4aDul+7TTibUKlEh67QUTHuBH3J5GaSEWzmUMkla0Tgvxzo+GbTiDRJ+hAbpuTVV5ZjHLCUfzF5xFoDMsg=',
salt: 'axmryXo0XnyfyiCUi4zYUNqzVv9xktzWKM/LPd4CXCGbjYUa2fQyPI89DTkR3coJGE+ow5AUEHSb/gg9rowLxQ==',
displayName: 'Egoing'
}
];
app.get('/auth/logout', function (req, res) {
// delete req.session.displayName;
// passport의 login
req.logout();
req.session.regenerate(function () {
res.redirect('/welcome');
});
})
app.get('/welcome', function (req, res) {
if (req.user && req.user.displayName) {
res.send(`
<h1>Hello, ${req.user.displayName}</h1>
<a href="/auth/logout">logout</a>
`);
} else {
res.send(`
<h1>Welcome</h1>
<p><a href="/auth/login">Please login</a></p>
<p><a href="/auth/register">Register</a></p>
`)
}
});
app.post('/auth/register', function (req, res) {
hasher({
password: req.body.password
}, function (err, pass, salt, hash) {
var user = {
authId: 'local:'+req.body.username,
username: req.body.username,
password: hash,
salt: salt,
displayName: req.body.displayName
};
var sql = 'INSERT INTO users SET ?';
connection.query(sql, user, function(err, results){
if(err){
console.log(err);
res.status(500);
} else {
req.login(user,function(err){
req.session.save(function(){
res.redirect('/welcome');
})
})
}
});
// users.push(user);
// passport의 login
// req.login(user, function(err){
// req.session.save(function(){
// res.redirect('/welcome');
// })
// })
// req.session.displayName = req.body.displayName;
// req.session.save(function () {
// res.redirect('/welcome');
// })
});
});
// done 이 false가 아니라면 이게 실행
// 맨 처음에 접속시 serialize 시킨다라는 말
passport.serializeUser(function(user, done) {
//session에 이렇게username으로 저장이 된다. 보통 user.id로 하는게 일반적인듯.
done(null, user.authId);
});
// done 이 false라면 이게 실행
// serialize 가 되고 사용자가 접속할때마다 이게 호출된다. 즉 현재 deserialize의 id인 username이 적용되는것이다.
passport.deserializeUser(function(id, done) {
var sql = 'SELECT * FROM users WHERE authId=?';
connection.query(sql, [id], function(err, results){
if(err){
} else {
done(null, results[0]);
}
})
});
// for (var i=0; i<users.length; i++){
// var user = users[i];
// if(user.authId=== id){
// return done(null, user);
// };
// }
//});
// Passport를 사용한다는 것은 session을 직접이 아니라 간접제어한다는 이야기!
// 따라서 req.session이 아니라 req.user를 통해서 모두 제어한다.
passport.use(new LocalStrategy (
function(username, password, done) {
var uname = username;
var pwd = password;
var sql = 'SELECT * FROM users WHERE authId=?';
connection.query(sql, ['local:'+uname], function(err, results){
console.log(results);
if(err){
return done('There is no user.');
}
var user = results[0];
return hasher({password: pwd, salt:user.salt}, function(err, pass, salt, hash){
if(hash === user.password){
// 로그인에 성공
// 여기서 넘기는 user객체가 req.user가 된다.
done(null, user);
} else {
done(null, false);
}
});
})
})
);
// for (var i=0; i<users.length; i++){
// var user = users[i];
// if(uname === user.username) {
// return hasher({password: pwd, salt:user.salt}, function(err, pass, salt, hash){
// if(hash === user.password){
// // 로그인에 성공
// // 여기서 넘기는 user객체가 req.user가 된다.
// done(null, user);
// } else {
// done(null, false);
// }
// });
// }
// }
// done(null, false);
// }
//)
//);
app.post('/auth/login',
// local 전략을 사용한다
passport.authenticate('local', {
successRedirect: '/welcome',
failureRedirect: '/auth/login',
// 요너석은 사용자에게 인증에 실패했다는 정보를 딱한번 주는방법 (복잡도가 살짝 있다)
failureFlash: false
})
);
/*
app.post('/auth/login', function(req,res){
var uname = req.body.username;
var pwd = req.body.password;
// for (user in users) {
// console.log(user);
for (var i=0; i<users.length; i++){
var user = users[i];
if(uname === user.username) {
return hasher({password: pwd, salt:user.salt}, function(err, pass, salt, hash){
if(hash === user.password){
req.session.displayName = user.displayName;
req.session.save(function(){
res.redirect('/welcome');
})
} else {
res.send(`No user or incorrect password
<p><a href="/auth/login">login</a></p>`)
}
});
}
}
res.send(`No user or incorrect password
<p><a href="/auth/login">login</a></p>`)
});*/
/* if(uname === user.username && sha256(pwd+user.salt) === user.password){
req.session.displayName = user.displayName;
return req.session.save(function(){
res.redirect('/welcome');
});
}
}
res.send(`No user or incorrect password
<p><a href="/auth/login">login</a></p>`)
});*/
app.get('/auth/register', function (req, res) {
var output = `
<h1> Login </h1>
<form action="/auth/register" method="post">
<p>
<input type="text" name="username" placeholder="username">
</p>
<p>
<input type="password" name="password" placeholder="password">
</p>
<p>
<input type="text" name="displayName" placeholder="displayName">
</p>
<p>
<input type="submit">
</p>
</form>
`;
res.send(output);
})
app.get('/auth/login', function (req, res) {
var output = `
<h1> Login </h1>
<form action="/auth/login" method="post">
<p>
<input type="text" name="username" placeholder="username">
</p>
<p>
<input type="password" name="password" placeholder="password">
</p>
<p>
<input type="submit">
</p>
</form>
`;
res.send(output);
});
app.listen(3003, function () {
console.log('Connected 3003 port');
})