-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhapi-auth-cookie.js
130 lines (104 loc) · 2.9 KB
/
hapi-auth-cookie.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
// Load modules
var Hapi = require('hapi');
var AuthCookie = require('hapi-auth-cookie');
var Joi = require('joi');
// User database
var users = {
leet: {
password: 'haxor',
name: 'Leet Haxor'
}
};
// Handlers
var validate = function (request, reply) {
var username = request.payload.username;
var password = request.payload.password;
var user = users[username];
var isValid = user && user.password === password;
if (!isValid) {
return reply().redirect('/login');
}
var credentials = { name: user.name } // Will be accessible in request.auth.credentials
request.auth.session.set(credentials);
return reply('Logged In');
};
var publicHandler = function (request, reply) {
reply('Everyone can see this...');
};
var privateHandler = function (request, reply) {
reply('Welcome ' + request.auth.credentials.name);
};
var loginPage = function (request, reply) {
var htmlForm = '<form method="post">' +
' <p>' +
' Username: <input type="text" name="username" /><br />' +
' Password: <input type="password" name="password" />' +
' </p>' +
' <p><input type="submit" value="login" /></p>' +
'</form>';
reply(htmlForm);
};
var logout = function (request, reply) {
request.auth.session.clear();
reply('Logged out');
};
// Create server
var server = new Hapi.Server();
server.connection({ port: 8188 })
// Load plugins
server.register(AuthCookie, function (err) {
// Configure auth scheme
var authOptions = {
password: 'PasswordUsedToEncryptCookie',
cookie: 'NameOfCookie',
redirectTo: '/login',
isSecure: false
};
server.auth.strategy('YourCookieAuth', 'cookie', authOptions);
// Configure routes after plugins are loaded
server.route({
method: 'GET',
path: '/public',
handler: publicHandler
});
// Configure protected routes by setting auth
server.route({
method: 'GET',
path: '/private',
handler: privateHandler,
config: {
auth: 'YourCookieAuth'
}
});
// Login page
server.route({
method: 'GET',
path: '/login',
handler: loginPage
});
// Logout
server.route({
method: 'GET',
path: '/logout',
handler: logout,
config: {
auth: 'YourCookieAuth'
}
});
// Login form post
server.route({
method: 'POST',
path: '/login',
handler: validate,
config: {
validate: {
payload: {
username: Joi.string().required(),
password: Joi.string().required()
}
}
}
});
// Start server
server.start(function () { console.log('Started...'); });
});