2
2
declare (strict_types=1 );
3
3
namespace RestJS \Middleware ;
4
4
5
- use Firebase \JWT \JWT ;
6
- use Firebase \JWT \Key ;
7
- use Psr \Http \Message \ResponseInterface ;
8
- use Psr \Http \Message \ServerRequestInterface as Request ;
9
- use Psr \Http \Server \RequestHandlerInterface as RequestHandler ;
10
- use Psr \Http \Server \MiddlewareInterface ;
11
5
use RestJS \Api \User \Model as User ;
12
- use Slim \ Exception \ HttpUnauthorizedException ;
6
+ use RestJS \ Middleware \ AbstractAuthMiddleware ;
13
7
14
8
/** Authorization Middleware */
15
- class Authorization implements MiddlewareInterface {
9
+ class Authorization extends AbstractAuthMiddleware {
16
10
17
- public function __construct (private User $ user ) {}
18
-
19
- public function process (Request $ req , RequestHandler $ handler ): ResponseInterface {
20
-
21
- /** User Access Token */
22
- $ token = $ _COOKIE ['SSID ' ] ?? str_replace ('Bearer ' , '' , $ req ->getHeader ('Authorization ' ))[0 ] ?? $ req ->getQueryParams ()['accessToken ' ] ?? null ;
23
-
24
- if (!$ token )
25
- throw new HttpUnauthorizedException ($ req , 'Unauthorized request ' );
26
-
27
- try {
28
- /** Decode Json Web Token */
29
- $ decodedToken = (array ) JWT ::decode ($ token , new Key ($ _ENV ['ACCESS_TOKEN_SECRET ' ], 'HS256 ' ));
30
- }
31
- catch (\Exception $ e ) {
32
- $ decodedToken = null ;
33
- }
34
-
35
- if (!$ decodedToken )
36
- throw new HttpUnauthorizedException ($ req , "Invalid access token " );
37
-
38
- /** Check User Entity */
39
- $ user = $ this ->user ->findById ($ decodedToken ['id ' ]);
40
-
41
- if (!$ user )
42
- throw new HttpUnauthorizedException ($ req , "Invalid access token " );
43
-
44
- $ req ->user = $ user ;
45
-
46
- return $ handler ->handle ($ req );
11
+ public function __construct (private User $ user ) {
12
+ parent ::__construct ($ user );
47
13
}
48
14
}
0 commit comments