1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace FMCSSOClient\Http\Controllers; |
4
|
|
|
|
5
|
|
|
use FMCSSOClient\Exceptions\CodeErrorException; |
6
|
|
|
use FMCSSOClient\Facades\SSOClient; |
7
|
|
|
use FMCSSOClient\SSOUser; |
8
|
|
|
use Illuminate\Http\RedirectResponse; |
9
|
|
|
use Illuminate\Support\Facades\Redirect; |
10
|
|
|
use Illuminate\Support\Facades\Route; |
11
|
|
|
|
12
|
|
|
abstract class SSORouter |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Create default routes. |
16
|
|
|
* |
17
|
|
|
* @param string $prefix |
18
|
|
|
* @param string $namePrefix |
19
|
|
|
*/ |
20
|
1 |
|
public static function routes(string $prefix = 'fmc-sso', string $namePrefix = 'fmc-sso') |
21
|
|
|
{ |
22
|
1 |
|
Route::prefix($prefix)->group(function () use ($namePrefix) { |
23
|
1 |
|
Route::get('/', [ |
24
|
|
|
static::class, |
25
|
|
|
'redirectAction', |
26
|
1 |
|
])->name("{$namePrefix}.redirect"); |
27
|
1 |
|
Route::get('/callback', [ |
28
|
|
|
static::class, |
29
|
|
|
'callbackAction', |
30
|
1 |
|
])->name("{$namePrefix}.callback"); |
31
|
|
|
}); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Step 1: redirect to authorize url. |
36
|
|
|
* |
37
|
|
|
* @return RedirectResponse |
38
|
|
|
*/ |
39
|
1 |
|
public function redirectAction() |
40
|
|
|
{ |
41
|
1 |
|
return SSOClient::setScopes($this->scopes()) |
|
|
|
|
42
|
1 |
|
->redirect(); |
|
|
|
|
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Step 2: get token and then user data. |
47
|
|
|
* |
48
|
|
|
* @return mixed |
49
|
|
|
*/ |
50
|
2 |
|
public function callbackAction(): mixed |
51
|
|
|
{ |
52
|
|
|
try { |
53
|
2 |
|
return $this->successUserCallback(SSOClient::ssoUser()) ?? Redirect::back(); |
|
|
|
|
54
|
1 |
|
} catch (CodeErrorException $e) { |
55
|
1 |
|
return $this->errorCodeCallback($e) ?? Redirect::back(); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* List of scopes. |
61
|
|
|
* |
62
|
|
|
* @return array |
63
|
|
|
*/ |
64
|
1 |
|
public function scopes(): array |
65
|
|
|
{ |
66
|
1 |
|
return []; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Callback to hand error response from code receiving. |
71
|
|
|
* |
72
|
|
|
* @param CodeErrorException $e |
73
|
|
|
* |
74
|
|
|
* @return mixed |
75
|
|
|
*/ |
76
|
1 |
|
protected function errorCodeCallback(CodeErrorException $e): mixed |
77
|
|
|
{ |
78
|
1 |
|
throw $e; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* Callback to hand response with used data. |
83
|
|
|
* |
84
|
|
|
* @param SSOUser $user |
85
|
|
|
* |
86
|
|
|
* @return mixed |
87
|
|
|
*/ |
88
|
|
|
abstract protected function successUserCallback(SSOUser $user): mixed; |
89
|
|
|
} |
90
|
|
|
|