diff --git a/.env.example b/.env.example index 9f7bcc4..3ea75ee 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,4 @@ -HTTP_PORT=3000 +HTTP_PORT=3001 MONGO_DB_URL=MONGO_DB_URL BCRYPT_SALT=10 JWT_SESSION_PASS=password \ No newline at end of file diff --git a/http/index.js b/http/index.js index 1dcf41a..fa5f67e 100644 --- a/http/index.js +++ b/http/index.js @@ -9,10 +9,11 @@ const app = express() // Start the server app.listen(port, function (err) { - if (!err) + if (!err) { logger.info(`HTTP server hosted on port ${port}`) - else + } else { logger.error(err) + } }) // Export the app diff --git a/http/middleware/index.js b/http/middleware/index.js index 67a7626..c537d41 100644 --- a/http/middleware/index.js +++ b/http/middleware/index.js @@ -1,19 +1,16 @@ const jwt = require('../../utils/jsonwebtoken') -isAuthenticated = async function (req, res, next) { - const authHeader = req.headers.authorization - - if (authHeader && authHeader.startsWith('Bearer ')) { - - const token = authHeader.substring(7) - const { id } = await jwt.decodeSessionToken(token) - req.user = { id: id } - return next() - } else { - return res.status(401).json({ error: 'Unauthorized' }) +async function isAuthenticated(req, res, next) { + try { + const { id } = await jwt.decodeSessionToken(jwt.getTokenFromBearer(req.headers.authorization)) + req.user = { id } + next() + } catch (err) { + logger.error(err) + res.status(401).json({ message: 'Unauthorized' }) } } module.exports = { isAuthenticated -} \ No newline at end of file +} diff --git a/utils/jsonwebtoken.js b/utils/jsonwebtoken.js index 6a6b9f1..346bf97 100644 --- a/utils/jsonwebtoken.js +++ b/utils/jsonwebtoken.js @@ -1,5 +1,13 @@ const jwt = require('jsonwebtoken') +function getTokenFromBearer(bearerToken) { + const PREFIX = 'Bearer ' + if (bearerToken && bearerToken.startsWith('Bearer ')) { + return bearerToken.replace(PREFIX, '') + } + return '' +} + async function generateSessionToken(string) { return new Promise(async (resolve, reject) => { try { @@ -23,6 +31,7 @@ async function decodeSessionToken(token) { } module.exports = { - generateSessionToken: generateSessionToken, - decodeSessionToken: decodeSessionToken + getTokenFromBearer, + generateSessionToken, + decodeSessionToken } \ No newline at end of file