This repository was archived by the owner on Jul 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.js
More file actions
265 lines (237 loc) · 7.88 KB
/
Copy pathstrategy.js
File metadata and controls
265 lines (237 loc) · 7.88 KB
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
/**
* Module dependencies.
*/
var passport = require('passport'),
https = require('https'),
http = require('http'),
URL = require('url'),
util = require('util'),
BadRequestError = require('./errors/badrequesterror');
/**
* `Strategy` constructor.
*
* The local authentication strategy authenticates requests based on the
* credentials submitted through an HTML-based login form.
*
* Applications must supply a `verify` callback which accepts `username` and
* `password` credentials, and then calls the `done` callback supplying a
* `user`, which should be set to `false` if the credentials are not valid.
* If an exception occured, `err` should be set.
*
* Optionally, `options` can be used to change the fields in which the
* credentials are found.
*
* Options:
* - `usernameField` field name where the username is found, defaults to _username_
* - `passwordField` field name where the password is found, defaults to _password_
* - `passReqToCallback` when `true`, `req` is the first argument to the verify callback (default: `false`)
*
* Examples:
*
* passport.use(new LocalStrategy(
* function(username, password, done) {
* User.findOne({ username: username, password: password }, function (err, user) {
* done(err, user);
* });
* }
* ));
*
* @param {Object} options
* @param {Function} verify
* @api public
*/
function Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = {};
}
if (!verify) throw new Error('atlassian-crowd authentication strategy requires a verify function');
if (!options.crowdServer) {
throw new Error("atlassian-crowd strategy requires a crowd server url");
}
this._crowdServer = options.crowdServer;
this._crowdApplication = options.crowdApplication;
this._crowdApplicationPassword = options.crowdApplicationPassword;
this._usernameField = options.usernameField || 'username';
this._passwordField = options.passwordField || 'password';
passport.Strategy.call(this);
this.name = 'atlassian-crowd';
this._verify = verify;
this._retrieveGroupMemberships = options.retrieveGroupMemberships || false;
}
/**
* Inherit from `passport.Strategy`.
*/
util.inherits(Strategy, passport.Strategy);
function _parseProfile(crowdUser) {
return {
provider:'atlassian-crowd',
id:crowdUser.name,
username:crowdUser.name,
displayName:crowdUser["display-name"],
name:{
familyName:crowdUser["last-name"],
givenName:crowdUser["first-name"]
},
email:crowdUser.email,
emails:[
{value:crowdUser.email}
],
_json:crowdUser
};
}
function _lookup(obj, field) {
if (!obj) {
return null;
}
var chain = field.split(']').join('').split('[');
for (var i = 0, len = chain.length; i < len; i++) {
var prop = obj[chain[i]];
if (typeof(prop) === 'undefined') {
return null;
}
if (typeof(prop) !== 'object') {
return prop;
}
obj = prop;
}
return null;
}
function _handleResponse(response, callback) {
var result = "";
response.on("data", function (chunk) {
result += chunk;
});
response.on("close", function (err) {
callback(response, result);
});
response.addListener("end", function () {
callback(response, result);
});
}
/**
* Authenticate request based on the contents of a form submission.
*
* @param {Object} req
* @api protected
*/
Strategy.prototype.authenticate = function (req, options) {
options = options || {};
var username = _lookup(req.body, this._usernameField) || _lookup(req.query, this._usernameField);
var password = _lookup(req.body, this._passwordField) || _lookup(req.query, this._passwordField);
if (!username || !password) {
return this.fail(new BadRequestError(options.badRequestMessage || 'Missing credentials'));
}
var self = this;
var http_library = https;
var parsedUrl = URL.parse(this._crowdServer, true);
if (parsedUrl.protocol == "https:" && !parsedUrl.port) {
parsedUrl.port = 443;
}
// As this is OAUth2, we *assume* https unless told explicitly otherwise.
if (parsedUrl.protocol != "https:") {
http_library = http;
}
var postData = JSON.stringify({ "value":password });
var applicationAuth = 'Basic ' + new Buffer(this._crowdApplication + ':' + this._crowdApplicationPassword).toString('base64');
function verified(err, user, info) {
if (err) {
return self.error(err);
}
if (!user) {
return self.fail(info);
}
self.success(user, info);
}
function handleGroupResponse(response, result) {
if (response.statusCode === 200) {
var resultObject = JSON.parse(result);
var groups = [];
resultObject.groups.forEach(function (group) {
// JIRA uses an older version of the Crowd REST API
if (group.GroupEntity) {
groups.push(group.GroupEntity.name);
}
else {
groups.push(group.name);
}
});
return groups;
} else if (response.statusCode >= 400 && response.statusCode < 500) {
var error = JSON.parse(result);
console.log("Error retrieving groups for user '" + username + "': " + error.message + " [" + error.reason + "]");
return self.fail(error);
} else {
return self.error(new Error("Invalid response from Crowd Server '" + self._crowdServer +
"' [" + response.statusCode + "]: " + result));
}
}
function handleAuthenticationResponse(response, result) {
if (response.statusCode === 200) {
var crowdUser = JSON.parse(result);
var userprofile = _parseProfile(crowdUser);
userprofile._raw = result;
if (self._retrieveGroupMemberships) {
var groupResult = "";
var groupRequest = http_library.get({
host:parsedUrl.hostname,
port:parsedUrl.port,
path:parsedUrl.pathname + "rest/usermanagement/latest/user/group/nested?username=" + username.replace(/\s/g,"%20"),
headers:{
"Content-Type":"application/json",
"Accept":"application/json",
"Authorization":applicationAuth
}
}, function (response) {
_handleResponse(response, function (response, groupResult) {
userprofile.groups = handleGroupResponse(response, groupResult);
return self._verify(userprofile, verified);
});
});
groupRequest.on('error', function (err) {
self.error(new Error("Error connecting to Crowd Server '" + self._crowdServer + "': " + err));
});
} else {
return self._verify(userprofile, verified);
}
} else if (response.statusCode >= 400 && response.statusCode < 500) {
var error = {"message":result};
try {
error = JSON.parse(result);
} catch (err) {
}
var logMsg = "Error authenticating user '" + username + "' on '" + self._crowdServer + "': " + error.message;
if (error.reason) {
logMsg += " [" + error.reason + "]";
}
console.log(logMsg);
return self.fail(error);
} else {
return self.error(new Error("Invalid response from Crowd Server '" + self._crowdServer +
"' [" + response.statusCode + "]: " + result));
}
}
var crowdRequest = http_library.request({
host:parsedUrl.hostname,
port:parsedUrl.port,
path:parsedUrl.pathname + "rest/usermanagement/latest/authentication?expand=attributes&username=" + username.replace(/\s/g,"%20"),
method:"POST",
headers:{
"Content-Type":"application/json",
"Accept":"application/json",
"Content-Length":postData.length,
"Authorization":applicationAuth
}
}, function (response) {
_handleResponse(response, handleAuthenticationResponse);
});
crowdRequest.on('error', function (err) {
self.error(new Error("Error connecting to Crowd Server '" + self._crowdServer + "': " + err));
});
crowdRequest.write(postData);
crowdRequest.end();
};
/**
* Expose `Strategy`.
*/
module.exports = Strategy;