-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_session_mysql.js
94 lines (85 loc) · 2.42 KB
/
app_session_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
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
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'
})
}));
app.get('/count', function(req, res){
if(req.session.count) {
req.session.count++;
} else {
req.session.count = 1;
}
res.send('count :' +req.session.count);
})
app.get('/auth/logout', function(req, res){
delete req.session.displayName;
/* req.session.save는 req.session의 값이 save가 되고나서 실행이 되는 콜백함수이다. 데이터베이스에 저장할 시간을 확실히 확보하여 준다 */
req.session.save(function(){
res.redirect('/welcome');
})
})
app.get('/welcome', function(req, res){
if(req.session.displayName){
res.send(`
<h1>Hello, ${req.session.displayName}</h1>
<a href="/auth/logout">logout</a>
`);
} else {
res.send(`
<h1>Welcome</h1>
<a href="/auth/login">Please login</a>
`)
}
})
app.post('/auth/login', function(req,res){
var user = {
username: 'egoing',
password:'111',
displayName: 'Jundong'
};
var uname = req.body.username;
var pwd = req.body.password;
if(uname === user.username && pwd === user.password){
req.session.displayName = user.displayName;
res.redirect('/welcome');
} else {
res.send(`No user or incorrect password
<p><a href="/auth/login">login</a></p>`)
}
});
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');
})