-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathOAuthController.php
More file actions
193 lines (148 loc) · 6.54 KB
/
OAuthController.php
File metadata and controls
193 lines (148 loc) · 6.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?php
declare(strict_types=1);
/**
* This file is part of Shield OAuth.
*
* (c) Datamweb <pooya_parsa_dadashi@yahoo.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Datamweb\ShieldOAuth\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\Events\Events;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Models\LoginModel;
use Datamweb\ShieldOAuth\Libraries\Basic\ControllersInterface;
class OAuthController extends BaseController implements ControllersInterface
{
private const ACCESS_DENIED = 'access_denied';
private ?User $userExist = null;
public function redirectOAuth(string $oauthName): RedirectResponse
{
// if user login
if (auth()->loggedIn()) {
return redirect()->to(config('Auth')->loginRedirect());
}
if (setting('ShieldOAuthConfig.oauthConfigs')[$oauthName]['allow_login'] === false) {
$errorText = 'ShieldOAuthLang.' . ucfirst($oauthName) . '.not_allow';
return redirect()->to(config('Auth')->logoutRedirect())->with('error', lang($errorText));
}
session()->set('oauth_name', $oauthName);
// Loading the class according to oauthName choices
$oauthClass = service('ShieldOAuth')::setOAuth($oauthName);
// Run anti forgery
$state = $this->makeAntiForgeryKey();
$redirectLink = $oauthClass->makeGoLink($state);
return redirect()->to($redirectLink);
}
public function callBack(): RedirectResponse
{
// if user after callback request url
if (! $oauth_name = session('oauth_name')) {
return redirect()->to(config('Auth')->logoutRedirect())->with('error', lang('ShieldOAuthLang.Callback.oauth_class_not_set'));
}
$allGet = $this->request->getGet();
// if permission is denied or was cancelled by user.
if (isset($allGet['error']) && $allGet['error'] === self::ACCESS_DENIED) {
$OAuth = ucfirst($oauth_name);
$oauthName = lang("ShieldOAuthLang.{$OAuth}.{$oauth_name}");
return redirect()->to(config('Auth')->logoutRedirect())->with('error', lang('ShieldOAuthLang.Callback.access_denied', [$oauthName]));
}
// if api have error
if (isset($allGet['error'])) {
return redirect()->to(config('Auth')->logoutRedirect())->with('error', lang('ShieldOAuthLang.unknown'));
}
// Loading the class according to oauthName choices
$oauthName = session()->get('oauth_name');
$oauthClass = service('ShieldOAuth')::setOAuth($oauthName);
// check request is Forgery
if ($this->checkAntiForgery($allGet['state']) === false) {
return redirect()->to(config('Auth')->logoutRedirect())->with('error', lang('ShieldOAuthLang.Callback.anti_forgery'));
}
// Delete to prevent reuse
session()->remove(['state', 'oauth_name']);
$userInfo = $oauthClass->getUserInfo($allGet);
$find = ['email' => $userInfo->email];
if ($this->checkExistenceUser($find)) {
$updateFields = $oauthClass->getColumnsName('syncingUserInfo', $userInfo);
$userid = $this->syncingUserInfo($find, $updateFields);
} else {
// Check config setting first to see if it can register automatically or not
if (setting('ShieldOAuthConfig.oauthConfigs')[$oauthName]['allow_register'] === false) {
return redirect()->to(config('Auth')->logoutRedirect())->with('error', lang('ShieldOAuthLang.Callback.account_not_found', [$userInfo->email]));
}
helper('text');
$users = model('ShieldOAuthModel');
// new user
$entitiesUser = new User($oauthClass->getColumnsName('newUser', $userInfo));
$users->save($entitiesUser);
$userid = $users->getInsertID();
// To get the complete user object with ID, we need to get from the database
$user = $users->findById($userid);
$users->save($user);
// Add to default group
$users->addToDefaultGroup($user);
// Trigger the register event defined by Shield to integrate oauth registrations better
Events::trigger('register', $user);
}
if ($this->userExist && $this->userExist->isBanned()) {
return redirect()->to(config('Auth')->logoutRedirect())->with('error', $this->userExist->getBanMessage() ?? lang('Auth.bannedUser'));
}
auth()->loginById($userid);
$this->recordLoginAttempt($oauthName, $userInfo->email);
if (auth()->loggedIn()) {
return redirect()->to(config('Auth')->loginRedirect());
}
return redirect()->to(config('Auth')->logoutRedirect())->with('error', lang('ShieldOAuthLang.unknown'));
}
private function makeAntiForgeryKey(): string
{
helper('text');
$state = random_string('crypto', 40);
session()->set('state', $state);
return $state;
}
private function checkAntiForgery(string $state): bool
{
return $state === session()->get('state');
}
private function checkExistenceUser(array $find = []): bool
{
$users = model('ShieldOAuthModel');
$findUser = $users->findByCredentials($find);
$this->userExist = $findUser;
return $findUser !== null;
}
/**
* Syncs user information based on provided fields.
*
* @param array<string, string> $find Array containing criteria to find the user
* @param array<string, string|null> $updateFields Fields to update for the user
*
* @return int The ID of the user whose information is synced
*/
private function syncingUserInfo(array $find = [], array $updateFields = []): int
{
$users = model('ShieldOAuthModel');
$user = $users->findByCredentials($find);
if (setting('ShieldOAuthConfig.syncingUserInfo') === true) {
$user->fill($updateFields);
}
$users->save($user);
return $user->id;
}
private function recordLoginAttempt(string $oauthName = '', string $identifier = ''): void
{
$loginModel = model(LoginModel::class);
$loginModel->recordLoginAttempt(
$oauthName . '_oauth',
$identifier,
true,
$this->request->getIPAddress(),
(string) $this->request->getUserAgent(),
user_id(),
);
}
}