Skip to content

Commit

Permalink
Merge pull request #1 from ABI-Deployment-Thesis/ruigo/update-jwt
Browse files Browse the repository at this point in the history
update(jwt): update jwt algorithm
  • Loading branch information
ruigomes99 authored Jun 24, 2024
2 parents a9c873f + dcb4c4b commit 50769f8
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 17 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
HTTP_PORT=3000
HTTP_PORT=3001
MONGO_DB_URL=MONGO_DB_URL
BCRYPT_SALT=10
JWT_SESSION_PASS=password
5 changes: 3 additions & 2 deletions http/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 9 additions & 12 deletions http/middleware/index.js
Original file line number Diff line number Diff line change
@@ -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
}
}
13 changes: 11 additions & 2 deletions utils/jsonwebtoken.js
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -23,6 +31,7 @@ async function decodeSessionToken(token) {
}

module.exports = {
generateSessionToken: generateSessionToken,
decodeSessionToken: decodeSessionToken
getTokenFromBearer,
generateSessionToken,
decodeSessionToken
}

0 comments on commit 50769f8

Please sign in to comment.