|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace WPB\App\Http\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Closure; |
|
6
|
|
|
use Illuminate\Http\Request; |
|
7
|
|
|
use CodexShaper\Database\Facades\Schema; |
|
8
|
|
|
use CodexShaper\OAuth2\Server\Http\Requests\ServerRequest; |
|
9
|
|
|
use CodexShaper\OAuth2\Server\Manager; |
|
10
|
|
|
use League\OAuth2\Server\Exception\OAuthServerException; |
|
11
|
|
|
use WPB\App\User; |
|
12
|
|
|
|
|
13
|
|
|
class AuthMiddleware |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* Handle an incoming request. |
|
17
|
|
|
* |
|
18
|
|
|
* @param \Illuminate\Http\Request $request |
|
19
|
|
|
* @param \Closure $next |
|
20
|
|
|
* @param array $guards |
|
21
|
|
|
* @return mixed |
|
22
|
|
|
*/ |
|
23
|
|
|
public function handle(Request $request, Closure $next, ...$guards) |
|
24
|
|
|
{ |
|
25
|
|
|
foreach($guards as $guard) { |
|
26
|
|
|
if($guard == 'api') { |
|
27
|
|
|
if( |
|
28
|
|
|
!Schema::hasTable('oauth_access_tokens') || |
|
29
|
|
|
!Schema::hasTable('oauth_refresh_tokens') || |
|
30
|
|
|
!Schema::hasTable('oauth_personal_access_clients') || |
|
31
|
|
|
!Schema::hasTable('oauth_clients') || |
|
32
|
|
|
!Schema::hasTable('oauth_auth_codes') |
|
33
|
|
|
) { |
|
34
|
|
|
throw new \Exception("Please install OAuth2 Server Plugin (plugin link) or Implement OAuth2 Server from this link (https://github.com/Codexshaper/oauth2)", 1); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$manager = new Manager; |
|
38
|
|
|
$resourceServer = $manager->getResourceServer(); |
|
39
|
|
|
$psrRequest = ServerRequest::getPsrServerRequest(); |
|
40
|
|
|
|
|
41
|
|
|
try { |
|
42
|
|
|
$psr = $resourceServer->validateAuthenticatedRequest($psrRequest); |
|
43
|
|
|
$user_id = $manager->validateUserForRequest($psr); |
|
44
|
|
|
|
|
45
|
|
|
if ($user_id) { |
|
46
|
|
|
$user = User::find($user_id); |
|
47
|
|
|
|
|
48
|
|
|
$request->merge(['user' => $user ]); |
|
49
|
|
|
$request->merge(['scopes' => $psr->getAttribute('oauth_scopes') ]); |
|
50
|
|
|
|
|
51
|
|
|
$request->setUserResolver(function () use ($user) { |
|
52
|
|
|
return $user; |
|
53
|
|
|
}); |
|
54
|
|
|
|
|
55
|
|
|
return $next($request); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
} catch (OAuthServerException $e) { |
|
59
|
|
|
throw new \Exception($e->getMessage()); |
|
60
|
|
|
|
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return $next($request); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
if(\is_user_logged_in()) { |
|
|
|
|
|
|
68
|
|
|
return $next($request); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
header('Location: '.\get_site_url().'/wp-admin'); |
|
|
|
|
|
|
72
|
|
|
die(); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|