-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth-catconf.js
121 lines (79 loc) · 2.71 KB
/
auth-catconf.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
/** @module auth-catconf */
var conf = require('./conf');
var catconf = require('./catconf');
var atob = require('atob');
var log = require('./logging').log;
var authorizeAgainstNode = catconf.authorizeAgainstNode;
var storage = require('./' + conf.storageModule);
/**
* Catconf authentication middleware
*
* After this is executed req.user is set to the nodeId of a user or
* undefined for unauthenticated requests.
* This either calls next() or doesn't and responds 401 instead.
*
*/
function authentication(req, res, next) {
var auth = req.headers.authorization;
var user,pass,clearText,i;
delete req.user; // Remove if anything here.
if (auth) {
// First check if there is a HTTP Authorization header and set
// user based on that.
log('auth', "Start HTTP authentication");
clearText = atob(auth.substring("Basic ".length));
i = clearText.indexOf(":");
if (i == -1) {
log('auth', "Invalid authorization header " + auth);
unauthorized('Invalid authorization header');
} else {
user = clearText.substring(0,i);
pass = clearText.substring(i+1);
log('auth', "Basic auth of: " + user + "/" + pass);
if (!user) {
log('auth', "Authentication failed, no user");
unauthorized('No user in authorization header');
} else {
storage.getNode(user,user)
.done (nodeLoaded)
.fail (nodeLoadFailed);
}
}
} else if (req.session && req.session.user) {
// No authorization header, set user from session
req.user = req.session.user;
log('auth', "Set user from session. " + req.user);
next();
} else {
// No authorization header, nor session.
log('auth', "No session or authorization header, " +
"proceeding as unauthenticated");
delete req.user;
next();
}
function nodeLoaded (node) {
authorizeAgainstNode(node,user,pass).
done(compareOk).
fail(compareFail);
}
function nodeLoadFailed (err) {
log('auth', "Cannot load user node");
unauthorized();
}
function compareOk () {
log('auth', "Password comparison succeeded");
req.user = user;
next();
}
function compareFail (err) {
log('auth', "Error: " + err);
unauthorized(err);
}
function unauthorized (msg) {
res.statusCode = 401;
if (msg === undefined) msg = 'Unauthorized';
res.end(msg);
// don't call next here, request handling stops.
}
}
module.exports = authentication;