-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathMagicLinkController.php
More file actions
233 lines (186 loc) · 7.18 KB
/
MagicLinkController.php
File metadata and controls
233 lines (186 loc) · 7.18 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
<?php
declare(strict_types=1);
namespace CodeIgniter\Shield\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\Events\Events;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Config\AuthSession;
use CodeIgniter\Shield\Models\LoginModel;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Shield\Traits\Viewable;
/**
* Handles "Magic Link" logins - an email-based
* no-password login protocol. This works much
* like password reset would, but Shield provides
* this in place of password reset. It can also
* be used on it's own without an email/password
* login strategy.
*/
class MagicLinkController extends BaseController
{
use Viewable;
/**
* @var UserModel
*/
protected $provider;
public function __construct()
{
helper('setting');
/** @var class-string<UserModel> $providerClass */
$providerClass = setting('Auth.userProvider');
$this->provider = new $providerClass();
}
/**
* Displays the view to enter their email address
* so an email can be sent to them.
*
* @return RedirectResponse|string
*/
public function loginView()
{
if (auth()->loggedIn()) {
return redirect()->to(config(Auth::class)->loginRedirect());
}
return $this->view(setting('Auth.views')['magic-link-login']);
}
/**
* Receives the email from the user, creates the hash
* to a user identity, and sends an email to the given
* email address.
*
* @return RedirectResponse|string
*/
public function loginAction()
{
// Validate email format
$rules = $this->getValidationRules();
if (! $this->validateData($this->request->getPost(), $rules, [], config('Auth')->DBGroup)) {
return redirect()->route('magic-link')->with('errors', $this->validator->getErrors());
}
// Check if the user exists
$email = $this->request->getPost('email');
$user = $this->provider->findByCredentials(['email' => $email]);
if ($user === null) {
return redirect()->route('magic-link')->with('error', lang('Auth.invalidEmail'));
}
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);
// Delete any previous magic-link identities
$identityModel->deleteIdentitiesByType($user, Session::ID_TYPE_MAGIC_LINK);
// Generate the code and save it as an identity
helper('text');
$token = random_string('crypto', 20);
$identityModel->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_MAGIC_LINK,
'secret' => $token,
'expires' => Time::now()->addSeconds(setting('Auth.magicLinkLifetime'))->format('Y-m-d H:i:s'),
]);
/** @var IncomingRequest $request */
$request = service('request');
$ipAddress = $request->getIPAddress();
$userAgent = (string) $request->getUserAgent();
$date = Time::now()->toDateTimeString();
// Send the user an email with the code
$email = emailer()->setFrom(setting('Email.fromEmail'), setting('Email.fromName') ?? '');
$email->setTo($user->email);
$email->setSubject(lang('Auth.magicLinkSubject'));
$email->setMessage($this->view(setting('Auth.views')['magic-link-email'], ['token' => $token, 'ipAddress' => $ipAddress, 'userAgent' => $userAgent, 'date' => $date]));
if ($email->send(false) === false) {
log_message('error', $email->printDebugger(['headers']));
return redirect()->route('magic-link')->with('error', lang('Auth.unableSendEmailToUser', [$user->email]));
}
// Clear the email
$email->clear();
return $this->displayMessage();
}
/**
* Display the "What's happening/next" message to the user.
*/
protected function displayMessage(): string
{
return $this->view(setting('Auth.views')['magic-link-message']);
}
/**
* Handles the GET request from the email
*/
public function verify(): RedirectResponse
{
$token = $this->request->getGet('token');
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);
$identity = $identityModel->getIdentityBySecret(Session::ID_TYPE_MAGIC_LINK, $token);
$identifier = $token ?? '';
// No token found?
if ($identity === null) {
$this->recordLoginAttempt($identifier, false);
$credentials = ['magicLinkToken' => $token];
Events::trigger('failedLogin', $credentials);
return redirect()->route('magic-link')->with('error', lang('Auth.magicTokenNotFound'));
}
// Delete the db entry so it cannot be used again.
$identityModel->delete($identity->id);
// Token expired?
if (Time::now()->isAfter($identity->expires)) {
$this->recordLoginAttempt($identifier, false);
$credentials = ['magicLinkToken' => $token];
Events::trigger('failedLogin', $credentials);
return redirect()->route('magic-link')->with('error', lang('Auth.magicLinkExpired'));
}
/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
// If an action has been defined
if ($authenticator->hasAction($identity->user_id)) {
return redirect()->route('auth-action-show')->with('error', lang('Auth.needActivate'));
}
// Log the user in
$authenticator->loginById($identity->user_id);
$user = $authenticator->getUser();
$this->recordLoginAttempt($identifier, true, $user->id);
// Give the developer a way to know the user
// logged in via a magic link.
session()->setTempdata('magicLogin', true);
Events::trigger('magicLogin');
// Get our login redirect url
return redirect()->to(config(Auth::class)->loginRedirect());
}
/**
* @param int|string|null $userId
*/
private function recordLoginAttempt(
string $identifier,
bool $success,
$userId = null
): void {
/** @var LoginModel $loginModel */
$loginModel = model(LoginModel::class);
$loginModel->recordLoginAttempt(
Session::ID_TYPE_MAGIC_LINK,
$identifier,
$success,
$this->request->getIPAddress(),
(string) $this->request->getUserAgent(),
$userId
);
}
/**
* Returns the rules that should be used for validation.
*
* @return array<string, array<string, array<string>|string>>
* @phpstan-return array<string, array<string, string|list<string>>>
*/
protected function getValidationRules(): array
{
return [
'email' => [
'label' => 'Auth.email',
'rules' => config(AuthSession::class)->emailValidationRules,
],
];
}
}