1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | var TraceUtils = require('@themost/common/utils').TraceUtils;
|
11 | var _ = require('lodash');
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function BasicAuthHandler() {
|
18 |
|
19 | }
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | BasicAuthHandler.parseBasicAuthorization = function(s)
|
26 | {
|
27 | try {
|
28 | if (typeof s !== 'string')
|
29 | return;
|
30 |
|
31 | var re = /\s?(Basic)\s+(.*)\s?/ig;
|
32 | var match = re.exec(s.replace(/^\s+/g,''));
|
33 | if (match) {
|
34 |
|
35 | var token = match[2];
|
36 |
|
37 | var buffer = new Buffer(token, 'base64');
|
38 |
|
39 | var matched = /(.*):(.*)/ig.exec(buffer.toString());
|
40 | if (matched) {
|
41 | return { userName:matched[1], userPassword:matched[2] };
|
42 | }
|
43 | }
|
44 | }
|
45 | catch(err) {
|
46 | TraceUtils.log(err);
|
47 | }
|
48 | };
|
49 |
|
50 | BasicAuthHandler.USERNAME_REGEXP = /^[a-zA-Z0-9.@_-]{1,255}$/;
|
51 |
|
52 | BasicAuthHandler.prototype.authenticateRequest = function (context, callback) {
|
53 | callback = callback || function() {};
|
54 | try {
|
55 | if (context.request && context.request.headers && context.request.headers.hasOwnProperty('authorization')) {
|
56 | |
57 |
|
58 |
|
59 | var authorizationArgs = BasicAuthHandler.parseBasicAuthorization(context.request.headers['authorization']);
|
60 | if (_.isNil(authorizationArgs)) {
|
61 | return callback();
|
62 | }
|
63 | let authStrategy = context.getApplication().getAuthStrategy();
|
64 | return authStrategy.login(context, authorizationArgs.userName, authorizationArgs.userPassword).then(function() {
|
65 | return callback();
|
66 | }).catch(function(err) {
|
67 | return callback(err);
|
68 | });
|
69 | }
|
70 | return callback();
|
71 | }
|
72 | catch(err) {
|
73 | return callback(err);
|
74 | }
|
75 | };
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | BasicAuthHandler.createInstance = function() {
|
82 | return new BasicAuthHandler();
|
83 | };
|
84 |
|
85 | if (typeof exports !== 'undefined') {
|
86 | module.exports.BasicAuthHandler = BasicAuthHandler;
|
87 | module.exports.createInstance = BasicAuthHandler.createInstance;
|
88 | }
|
89 |
|