File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments