-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathEmail2FA.php
More file actions
201 lines (164 loc) · 6.04 KB
/
Email2FA.php
File metadata and controls
201 lines (164 loc) · 6.04 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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Shield\Authentication\Actions;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Entities\UserIdentity;
use CodeIgniter\Shield\Exceptions\RuntimeException;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Traits\Viewable;
/**
* Class Email2FA
*
* Sends an email to the user with a code to verify their account.
*/
class Email2FA implements ActionInterface
{
use Viewable;
private string $type = Session::ID_TYPE_EMAIL_2FA;
/**
* Displays the "Hey we're going to send you a number to your email"
* message to the user with a prompt to continue.
*/
public function show(): string
{
/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$user = $authenticator->getPendingUser();
if ($user === null) {
throw new RuntimeException('Cannot get the pending login User.');
}
$this->createIdentity($user);
return $this->view(setting('Auth.views')['action_email_2fa'], ['user' => $user]);
}
/**
* Generates the random number, saves it as a temp identity
* with the user, and fires off an email to the user with the code,
* then displays the form to accept the 6 digits
*
* @return RedirectResponse|string
*/
public function handle(IncomingRequest $request)
{
$email = $request->getPost('email');
/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$user = $authenticator->getPendingUser();
if ($user === null) {
throw new RuntimeException('Cannot get the pending login User.');
}
if (empty($email) || $email !== $user->email) {
return redirect()->route('auth-action-show')->with('error', lang('Auth.invalidEmail', [$email]));
}
$identity = $this->getIdentity($user);
if (! $identity instanceof UserIdentity) {
return redirect()->route('auth-action-show')->with('error', lang('Auth.need2FA'));
}
$ipAddress = $request->getIPAddress();
$userAgent = (string) $request->getUserAgent();
$date = Time::now()->toDateTimeString();
// Send the user an email with the code
helper('email');
$email = emailer(['mailType' => 'html'])
->setFrom(setting('Email.fromEmail'), setting('Email.fromName') ?? '');
$email->setTo($user->email);
$email->setSubject(lang('Auth.email2FASubject'));
$email->setMessage($this->view(
setting('Auth.views')['action_email_2fa_email'],
['code' => $identity->secret, 'user' => $user, 'ipAddress' => $ipAddress, 'userAgent' => $userAgent, 'date' => $date],
['debug' => false],
));
if ($email->send(false) === false) {
throw new RuntimeException('Cannot send email for user: ' . $user->email . "\n" . $email->printDebugger(['headers']));
}
// Clear the email
$email->clear();
return $this->view(setting('Auth.views')['action_email_2fa_verify']);
}
/**
* Attempts to verify the code the user entered.
*
* @return RedirectResponse|string
*/
public function verify(IncomingRequest $request)
{
/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$postedToken = $request->getPost('token');
$user = $authenticator->getPendingUser();
if ($user === null) {
throw new RuntimeException('Cannot get the pending login User.');
}
$identity = $this->getIdentity($user);
// Token mismatch? Let them try again...
if (! $authenticator->checkAction($identity, $postedToken)) {
session()->setFlashdata('error', lang('Auth.invalid2FAToken'));
return $this->view(setting('Auth.views')['action_email_2fa_verify']);
}
// Get our login redirect url
return redirect()->to(config('Auth')->loginRedirect());
}
/**
* Creates an identity for the action of the user.
*
* @return string secret
*/
public function createIdentity(User $user): string
{
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);
// Delete any previous identities for action
$identityModel->deleteIdentitiesByType($user, $this->type);
$generator = static fn (): string => random_string('nozero', 6);
return $identityModel->createCodeIdentity(
$user,
[
'type' => $this->type,
'name' => 'login',
'extra' => lang('Auth.need2FA'),
],
$generator,
);
}
/**
* Returns an identity for the action of the user.
*/
private function getIdentity(User $user): ?UserIdentity
{
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);
return $identityModel->getIdentityByType(
$user,
$this->type,
);
}
/**
* Returns the string type of the action class.
*/
public function getType(): string
{
return $this->type;
}
/**
* Retrieves the action message for the user (e.g. extra)
*/
public function getActionMessage(): string
{
/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
$user = $authenticator->getPendingUser();
$identity = $this->getIdentity($user);
return $identity->extra;
}
}