From 4bfd08a982e8d9b7404ba0a8ea5422c1dc89ebf8 Mon Sep 17 00:00:00 2001 From: Anass Daoudi Date: Thu, 18 Jul 2019 21:11:03 +0100 Subject: [PATCH] Add checks and enhance getTokenFromHeader function definition --- routes/auth.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/routes/auth.js b/routes/auth.js index e44a21508..4e77f2bba 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -1,10 +1,18 @@ var jwt = require('express-jwt'); var secret = require('../config').secret; -function getTokenFromHeader(req){ - if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Token' || - req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { - return req.headers.authorization.split(' ')[1]; +function getTokenFromHeader(req) { + if (req && req.headers && typeof req.headers.authorization === 'string') { + const authorizationParts = req.headers.authorization.trim().split(' '); + + + if (authorizationParts.length === 2) { + const isAuthFirstPartEqualTo = value => authorizationParts[0] === value; + + if (isAuthFirstPartEqualTo('Token') || isAuthFirstPartEqualTo('Bearer')) { + return authorizationParts[1]; + } + } } return null;