UNPKG

2.69 kBJavaScriptView Raw
1/**
2 * @license
3 * MOST Web Framework 2.0 Codename Blueshift
4 * Copyright (c) 2017, THEMOST LP All rights reserved
5 *
6 * Use of this source code is governed by an BSD-3-Clause license that can be
7 * found in the LICENSE file at https://themost.io/license
8 */
9///
10var TraceUtils = require('@themost/common/utils').TraceUtils;
11var _ = require('lodash');
12/**
13 * @class
14 * @constructor
15 * @implements AuthenticateRequestHandler
16 */
17function BasicAuthHandler() {
18 //
19}
20
21/**
22 * @param {string|*} s
23 * @returns {{userName:string, userPassword:string}|undefined}
24 */
25BasicAuthHandler.parseBasicAuthorization = function(s)
26{
27 try {
28 if (typeof s !== 'string')
29 return;
30 //get authorization type (basic)
31 var re = /\s?(Basic)\s+(.*)\s?/ig;
32 var match = re.exec(s.replace(/^\s+/g,''));
33 if (match) {
34 //get authorization token
35 var token = match[2];
36 //decode token
37 var buffer = new Buffer(token, 'base64');
38 //get args e.g. username:password
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
50BasicAuthHandler.USERNAME_REGEXP = /^[a-zA-Z0-9.@_-]{1,255}$/;
51
52BasicAuthHandler.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 * @type {{userName: string, userPassword: string}|*}
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 * Creates a new instance of BasicAuthHandler class
79 * @returns {BasicAuthHandler}
80 */
81BasicAuthHandler.createInstance = function() {
82 return new BasicAuthHandler();
83};
84
85if (typeof exports !== 'undefined') {
86 module.exports.BasicAuthHandler = BasicAuthHandler;
87 module.exports.createInstance = BasicAuthHandler.createInstance;
88}
89