88 lines
2.3 KiB
JavaScript
88 lines
2.3 KiB
JavaScript
'use strict';
|
|
/**
|
|
* HASH
|
|
*****************************************************
|
|
* DEPENDENCIES
|
|
*****************************************************
|
|
* Based on Express Framework
|
|
* System
|
|
*****************************************************
|
|
* PUBLIC METHODS
|
|
*****************************************************
|
|
* Auth( req, res, next)
|
|
* Extract JWT or BasicAuth data
|
|
* errorJSON( error , request , response , next )
|
|
* Generate error response on bad JSON format
|
|
* error404( request , response , next )
|
|
* Generate error 404 response
|
|
* apiKey( request , response , next )
|
|
* Generate error on invalid apikey
|
|
**/
|
|
|
|
/// Extract JWT or BasicAuth
|
|
function Auth( req, res , next ){
|
|
///
|
|
/// Try to extract the authorization data from headers
|
|
///
|
|
let auth;
|
|
if( req.headers.hasOwnProperty( "authorization" ) ){
|
|
auth = req.headers.authorization;
|
|
auth = auth.split(" ")[1];
|
|
if( !auth ){ console.log( "NO HEADER AUTH available" ); return next(); }
|
|
//console.log( auth );
|
|
/// Try BasicAuth {
|
|
try{
|
|
let ba = Buffer.from( auth , 'base64' ).toString()
|
|
//const [user,pass] = ba.split(':');
|
|
ba = ba.split(':');
|
|
if( ba.length == 2 ){
|
|
req.basicAuth = { user : ba[0] , password : ba[1] };
|
|
}
|
|
}catch(error){
|
|
console.log("MIDDLEWARE_AUTH_ERR_BA",error);
|
|
}
|
|
/// Try BasicAuth }
|
|
}else if( req.query.access_token ){
|
|
auth = req.query.access_token;
|
|
if( !auth ){ console.log( "NO QUERY AUTH available" ); return next(); }
|
|
}
|
|
if( auth ){
|
|
/// Try JWT {
|
|
try{
|
|
let jwt = auth.split(".");
|
|
if( jwt.length == 3 ){
|
|
req.JWT = {};
|
|
req.JWT.raw = auth;
|
|
}
|
|
}catch( error ){
|
|
console.log("MIDDLEWARE_AUTH_ERR_JWT",error);
|
|
}
|
|
/// Try JWT }
|
|
}
|
|
next();
|
|
}
|
|
|
|
function errorJSON( error , request , response , next ){
|
|
console.log(error);
|
|
if( error !== null ){
|
|
/// For body-parser errors
|
|
if( error instanceof SyntaxError && error.status === 400 && 'body' in error ){
|
|
return response.status(400).json({ error : 'Invalid json' , code : 400 });
|
|
}
|
|
/// For any error
|
|
return response.status(500).send( { error: "Internal server error" , code : 500 } );
|
|
}else{
|
|
return next();
|
|
}
|
|
}
|
|
|
|
function error404( request , response , next ){
|
|
return response.status(404).send( { error : "Page not found", code : 404 } );
|
|
}
|
|
|
|
module.exports = {
|
|
Auth,
|
|
errorJSON,
|
|
error404,
|
|
};
|