-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhapi-auth-basic.js
66 lines (53 loc) · 1.49 KB
/
hapi-auth-basic.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
// Load modules
var Hapi = require('hapi');
var Basic = require('hapi-auth-basic');
// User database
var users = {
leet: {
password: 'haxor',
name: 'Leet Haxor'
}
};
// Function used to validate a user
var validate = function (username, password, callback) {
var user = users[username];
var isValid = user && user.password === password;
var credentials = { name: user.name } // Will be accessible in request.auth.credentials
return callback(null, isValid, credentials);
};
// Handlers
var publicHandler = function (request, reply) {
console.log(request.route)
reply('Everyone can see this...');
};
var privateHandler = function (request, reply) {
reply('Welcome ' + request.auth.credentials.name);
};
// Create server
var server = new Hapi.Server();
server.connection({ port: 8187 });
// Load plugins
server.register(Basic, function (err) {
// Configure auth scheme
var authOptions = {
validateFunc: validate
};
server.auth.strategy('YourSimpleAuth', 'basic', 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: 'YourSimpleAuth'
}
});
// Start server
server.start(function () { console.log('Started...'); });
});