@@ -2,8 +2,8 @@ import {isString} from "@aicore/libcommonutils";
22
33let key = null ;
44const customAuthAPIPath = { } ,
5- API_AUTH_NONE = 1 ;
6- // API_AUTH_CUSTOM = 2; maybe give a callback function here?
5+ API_AUTH_NONE = 1 ,
6+ API_AUTH_CUSTOM = 2 ;
77
88export function init ( authKey ) {
99 if ( ! isString ( authKey ) ) {
@@ -13,6 +13,9 @@ export function init(authKey) {
1313}
1414
1515function _isBasicAuthPass ( request ) {
16+ if ( ! request . headers ) {
17+ return false ;
18+ }
1619 const authHeader = request . headers . authorization ;
1720 console . log ( authHeader ) ;
1821 if ( ! authHeader ) {
@@ -42,14 +45,18 @@ function _getBaseURL(url = "") {
4245}
4346
4447export function isAuthenticated ( request ) {
45- let customAuth = customAuthAPIPath [ _getBaseURL ( request . raw . url ) ] || { } ;
48+ let customAuth = customAuthAPIPath [ _getBaseURL ( request . raw . url ) ] ;
49+ if ( ! customAuth ) {
50+ return _isBasicAuthPass ( request ) ;
51+ }
4652 if ( customAuth . authType === API_AUTH_NONE ) {
4753 return true ;
4854 }
49- if ( ! request . headers ) {
50- return false ;
55+ if ( customAuth . authType === API_AUTH_CUSTOM && customAuth . authCallback ) {
56+ return customAuth . authCallback ( request ) ;
5157 }
52- return _isBasicAuthPass ( request ) ;
58+ // should never reach here, but future protect.
59+ return false ;
5360}
5461
5562/**
@@ -63,6 +70,19 @@ export function addUnAuthenticatedAPI(apiPath) {
6370 } ;
6471}
6572
73+ /**
74+ * There would be certain APIs that you have to provide your own custom auth logic. Use this API for that.
75+ * @param {string } apiPath of the form "/path/to/api" , The route must exactly match the api name in `server.get` call.
76+ * @param {function } authCallback will be called with the request and should return true if the request is authorised
77+ * and able to continue, else return false.
78+ */
79+ export function addCustomAuthorizer ( apiPath , authCallback ) {
80+ customAuthAPIPath [ apiPath ] = {
81+ authType : API_AUTH_CUSTOM ,
82+ authCallback
83+ } ;
84+ }
85+
6686export function getAuthKey ( ) {
6787 return key ;
6888}
0 commit comments