Skip to content

Commit ff315c6

Browse files
committed
feat: add authorization middleware
1 parent 11cd51f commit ff315c6

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { NextFunction, Request, Response } from 'express'
2+
import { env } from '~/config/env'
3+
import { asyncHandler } from '~/lib/async-handler'
4+
import JwtToken from '~/lib/token/jwt'
5+
import SessionService from '../service/session'
6+
import _ from 'lodash'
7+
8+
const jwt = new JwtToken({ secret: env.JWT_SECRET, expires: env.JWT_EXPIRES })
9+
const sessionService = new SessionService()
10+
11+
export default function authorization() {
12+
return asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
13+
const token = jwt.extract(req)
14+
if (!token) {
15+
return res.status(401).json({
16+
statusCode: 401,
17+
error: 'Unauthorized',
18+
message: 'Unauthorized, cannot extract token from request',
19+
})
20+
}
21+
22+
const decoded = jwt.verify(token)
23+
if (!decoded.data) {
24+
return res.status(401).json({
25+
statusCode: 401,
26+
error: 'Unauthorized',
27+
message: 'Unauthorized, invalid jwt',
28+
})
29+
}
30+
31+
const session = await sessionService.findByUserToken({
32+
user_id: _.get(decoded, 'data.uid', ''),
33+
token,
34+
})
35+
36+
req.setState({ userLoginState: decoded.data, session })
37+
next()
38+
})
39+
}

0 commit comments

Comments
 (0)