Skip to content

Commit c4dfd74

Browse files
committed
Add Error And Auth Middleware
1 parent 348bd3c commit c4dfd74

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

middleware/auth.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const jwt = require('jsonwebtoken')
2+
const { UnauthenticatedError } = require('../errors')
3+
4+
const authenticationMiddleware = async (req, res, next) => {
5+
const authHeader = req.headers.authorization
6+
7+
if (!authHeader || !authHeader.startsWith('Bearer ')) {
8+
throw new UnauthenticatedError('No token provided')
9+
}
10+
11+
const token = authHeader.split(' ')[1]
12+
13+
try {
14+
const decoded = jwt.verify(token, process.env.JWT_SECRET)
15+
const { id, username } = decoded
16+
req.user = { id, username }
17+
next()
18+
} catch (error) {
19+
throw new UnauthenticatedError('Not authorized to access this route')
20+
}
21+
}
22+
23+
module.exports = authenticationMiddleware

middleware/error-handler.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const { CustomAPIError } = require('../errors')
2+
const { StatusCodes } = require('http-status-codes')
3+
const errorHandlerMiddleware = (err, req, res, next) => {
4+
if (err instanceof CustomAPIError) {
5+
return res.status(err.statusCode).json({ msg: err.message })
6+
}
7+
return res
8+
.status(StatusCodes.INTERNAL_SERVER_ERROR)
9+
.send('Something went wrong try again later')
10+
}
11+
12+
module.exports = errorHandlerMiddleware

middleware/not-found.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const notFound = (req, res) => res.status(404).send('Route does not exist')
2+
3+
module.exports = notFound

0 commit comments

Comments
 (0)