22
33namespace App \Http \Middleware ;
44
5+ use App \Models \Permission ;
56use Illuminate \Support \Facades \Log ;
67use Symfony \Component \HttpKernel \Exception \UnauthorizedHttpException ;
78use TusPhp \Middleware \TusMiddleware ;
@@ -22,10 +23,20 @@ class TusAuthenticated implements TusMiddleware
2223 */
2324 public function handle (Request $ request , Response $ response )
2425 {
26+ // 1. Check if already authenticated via JWT Authorization header
2527 if (auth ('api ' )->check ()) {
28+ $ this ->checkExtensionPermission ();
2629 return ;
2730 }
2831
32+ // 2. Check session/cookie-based auth (web guard)
33+ if (auth ('web ' )->check ()) {
34+ auth ('api ' )->login (auth ('web ' )->user ());
35+ $ this ->checkExtensionPermission ();
36+ return ;
37+ }
38+
39+ // 3. Try Extension-Token (JWT from sandbox customRequestData['token'])
2940 $ token = "" ;
3041 if (request ()->token ) {
3142 $ token = request ()->token ;
@@ -34,14 +45,52 @@ public function handle(Request $request, Response $response)
3445 }
3546
3647 if (! $ token ) {
37- if (auth ('api ' )->check ()) {
38- return true ;
48+ // 4. Try cookie-based JWT (web middleware group doesn't run CookieJWTAuthenticator)
49+ if (request ()->hasCookie ('token ' )) {
50+ request ()->headers ->set ('Authorization ' , 'Bearer ' . request ()->cookie ('token ' ));
51+ if (auth ('api ' )->check ()) {
52+ $ this ->checkExtensionPermission ();
53+ return ;
54+ }
3955 }
4056
4157 throw new UnauthorizedHttpException ('' , 'Extension-Token header is missing. ' );
4258 }
4359
44- Log::info ('Extension-Token is valid. User ip: ' . request ()->ip );
60+ // Validate the JWT token
61+ try {
62+ request ()->headers ->set ('Authorization ' , 'Bearer ' . $ token );
63+ if (! auth ('api ' )->check ()) {
64+ throw new UnauthorizedHttpException ('' , 'Invalid Extension-Token. ' );
65+ }
66+ } catch (\Exception $ e ) {
67+ throw new UnauthorizedHttpException ('' , 'Invalid Extension-Token. ' );
68+ }
69+
70+ $ this ->checkExtensionPermission ();
71+
72+ Log::info ('Extension-Token validated for user ' . auth ('api ' )->user ()->id . '. IP: ' . request ()->ip ());
4573 return true ;
4674 }
75+
76+ /**
77+ * Check if the authenticated user has permission to upload to the specified extension
78+ */
79+ private function checkExtensionPermission (): void
80+ {
81+ $ extensionId = request ()->headers ->get ('extension-id ' );
82+
83+ if (! $ extensionId ) {
84+ return ;
85+ }
86+
87+ $ user = auth ('api ' )->user ();
88+ if (! $ user ) {
89+ return ;
90+ }
91+
92+ if (! Permission::can ($ user ->id , 'extension ' , 'id ' , $ extensionId )) {
93+ throw new UnauthorizedHttpException ('' , 'You do not have permission to upload to this extension. ' );
94+ }
95+ }
4796}
0 commit comments