Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 1x 2x 2x 2x 2x 2x 2x | 'use strict';
const debug=require('debug')('koajs-toolkit:apiKeyCheckLib');
module.exports = class apiKeyCheckMib {
constructor(config) {
config=config || {};
let apikeys=config.keys;
Eif(apikeys && typeof config.header=== 'string'){
//if apikeys is string then we transform into array
Eif(typeof apikeys === 'string'){
apikeys=[apikeys];
}
Eif(Array.isArray(apikeys) && apikeys.length>0){
return async (ctx, next) => {
//if apikey in header is valid, then we continue
if(ctx.headers[config.header]){
for(let i=0, end=apikeys.length; i<end; i++){
if(ctx.headers[config.header] === apikeys[i]){
return await next();
}
}
}
let msg='"' + config.header + '" is "' + ctx.headers[config.header] + '". so this is not ok!';
Iif(ctx.logger && ctx.logger.silly){
ctx.logger.silly(msg);
}else{
debug('%s', msg);
}
const e = new Error('Unauthorized');
e.status=401;
throw e;
// return {status:500, message:"Unauthorized"};
};
}
}
return async (ctx, next) =>{
await next();
}
}
}; |