This repository has been archived by the owner on Jun 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPasswordReset.module
286 lines (234 loc) · 11.5 KB
/
PasswordReset.module
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
<?php
class PasswordReset extends WireData implements Module
{
private $field = [];
private $errorMessage;
private $userEmail;
public static function getModuleInfo() {
return array(
'title' => 'Password Reset',
'summary' => 'Customizable frontend password reset',
'version' => 6,
'autoload' => false,
'singular' => true
);
}
public function init() {
$this->errorMessage = $this->session->errorMessage;
$this->session->remove('errorMessage');
}
private function setField() {
if ($this->fieldname == 'name') {
$this->field['name'] = 'name';
$this->field['label'] = __('Username'); // Label for 'name' field
} else {
$field = wire('fields')->get($this->fieldname);
$localizedLabel = "label" . $this->user->language->id;
$localizedLabel = $field->{$localizedLabel};
$this->field['name'] = $field->name;
$this->field['label'] = (!empty($localizedLabel)) ? $localizedLabel : $field->label;
}
}
public function getScripts() {
return "{$this->config->urls->siteModules}{$this->className}/js/password-reset.js";
}
private function getRequestForm() {
// TODO : Probably implement urlSlashes check next line
$form = "<form class='password-reset' action='request-key/' method='post'>" . PHP_EOL;
if (!empty($this->errorMessage)) $form .= "<div class='error'>{$this->errorMessage}</div>";
$form .= "<label for='{$this->field['name']}-input'>{$this->field['label']}</label>" . PHP_EOL;
$form .= "<input id='{$this->field['name']}-input' type='text' name='{$this->field['name']}' value=''>" . PHP_EOL;
if(class_exists('LanguageSupport',false)) {
// TODO : Fallback to default ?
$langId = $this->user->language->id;
$instructions = $this->{'instructions' . $langId};
if (!empty($instructions)) $form .= "<div class='instructions'>{$instructions}</div>";
} else {
if (!empty($this->instructions)) $form .= "<div class='instructions'>{$this->instructions}</div>";
}
$form .= "<input type='submit' value='" . __("Reset my password") . "'>"; // Button on first step form
$form .= "</form>";
return $form;
}
private function sendRequestEmail() {
$email = wireMail();
$email->from($this->emailAddress, $this->emailName);
$email->to($this->userEmail);
$email->subject(__('Password reset')); // Email subject
$body1 = __('To reset your password, please click the following link:'); // Email body first line
$body2 = __('If you did not request a password change, you can safely ignore this email.'); // Email body last line (after link)
$email->bodyHTML("<p>{$body1}</p><p><a href='{$this->page->httpUrl}key/{$this->key}/'>{$this->page->httpUrl}key/{$this->key}/</a></p><p>{$body2}</p>");
$email->send();
}
private function generateKey() {
// generate key
$this->key = hash('sha256', openssl_random_pseudo_bytes(64));
// set expiration time
$date = new DateTime('now');
$date->add(new DateInterval('PT24H'));
$expiration = $date->getTimestamp();
// get user or redirect back to form is user doesn't exist
$credentials = $this->sanitizer->text($this->input->post($this->field['name']));
if (!empty($credentials)) {
$user = wire('users')->get("{$this->field['name']}={$this->input->post($this->field['name'])}");
if (is_a($user, 'NullPage')) {
$this->session->errorMessage = __('No user found matching those credentials.'); // Error
$this->session->redirect($this->page->url);
}
} else {
$this->session->errorMessage = __('The form must be filled.'); // Error
$this->session->redirect($this->page->url);
}
$this->userEmail = $user->email;
$keyPage = new Page();
$keyPage->template = 'password-reset-request';
$keyPage->parent_id = $this->page->id;
$keyPage->title = $this->key;
$keyPage->name = $this->key;
$keyPage->passwordResetExpiration = $expiration;
$keyPage->passwordResetUser = $user;
$keyPage->save();
}
private function requestKeyIsValid() {
if ($this->page->children('name='.$this->getKey())->count() !== 1) {
$this->errorMessage = "<p class='error invalid'>".__('Invalid password reset key.')."</p>"; // Error
} else if ($this->page->get('name='.$this->getKey())->passwordResetExpiration < time()) {
$this->errorMessage = "<p class='error expired'>".__('Your password reset key expired.')."</p>"; // Error
$this->deleteRequestKey();
} else {
return true;
}
}
private function deleteRequestKey() {
$key = $this->page->get('name='.$this->getKey())->delete();
}
private function getRequestKeyMessage() {
$message = "<div class='password-reset request'><p>".__('An email containing a link allowing you to reset your password was sent to you.')."</p>"; // Message step 2
$message .= "<p>".__('This reset link will expire in 24 hours.')."</p></div>"; // Message step 2, second line
return $message;
}
private function getKey() {
if ($this->input->post('request-key') !== null) {
$this->key = $this->input->post('request-key');
} else {
$this->key = $this->input->urlSegment2;
}
return $this->key;
}
private function getKeyPage() {
return $this->page->get('name='.$this->getKey());
}
private function getResetForm() {
if ($this->requestKeyIsValid() === true) {
$form = "<form class='password-reset reset-form' action='{$this->page->url}reset/' method='post'>" . PHP_EOL;
if (!empty($this->errorMessage)) $form .= "<div class='error'>{$this->errorMessage}</div>";
$form .= "<label for='new-password'>".__('Please choose a new password')."</label>" . PHP_EOL; // Label on reset form, after email is received
$form .= "<input id='new-password' type='password' name='new-password' value=''>" . PHP_EOL;
$form .= "<label class='display-password'><input id='display-password' type='checkbox' name='display-password' value=''>".__('Show password')."</label>" . PHP_EOL; // JS password reveal
if(class_exists('LanguageSupport',false)) {
// TODO : Fallback to default ?
$langId = $this->user->language->id;
$instructions = $this->{'passwordInstructions' . $langId};
if (!empty($instructions)) $form .= "<div class='instructions'>{$instructions}</div>";
} else {
if (!empty($this->passwordInstructions)) $form .= "<div class='instructions'>{$this->ipasswordInstructions}</div>";
}
$form .= "<input id='request-key' type='hidden' name='request-key' value='".$this->getKey()."'>" . PHP_EOL;
$form .= "<input type='submit' value='" . __("Reset my password") . "'>"; // Submit new password button
$form .= "</form>";
return $form;
} else {
// get returned error message
return $this->errorMessage;
}
}
private function resetPassword() {
if ($this->requestKeyIsValid() === true) {
if (mb_strlen($this->input->post('new-password')) < $this->passwordLength) {
$this->session->errorMessage = sprintf(__("Your password must contain at least %d characters."),$this->passwordLength); // Error
$this->session->redirect($this->page->url . "/key/" . $this->getKey() . "/");
}
$user = $this->getKeyPage()->passwordResetUser;
$user->of(false);
$user->pass = $this->sanitizer->text($this->input->post('new-password'));
$user->save();
$this->deleteRequestKey();
return "<p>".__("Your password was successfully reset.")."</p>"; // Last screen success message
} else {
return $this->errorMessage;
}
}
private function deleteAllExpiredKeys() {
$time = new DateTime('now');
$time = $time->getTimestamp();
$expiredKeys = $this->pages->find("parent={$this->page->id}, passwordResetExpiration<{$time}");
foreach ($expiredKeys as $key) {
$key->delete();
}
}
public function controller() {
$this->setField();
$segment1 = ($this->input->urlSegment1);
$segment2 = ($this->input->urlSegment2);
$this->deleteAllExpiredKeys();
if (empty($segment1)) {
$this->session->requestKeySent = false;
return $this->getRequestForm();
} else if ($segment1 === 'request-key') {
// generate key, send message and prevent requesting another key by accident or on refresh
if ($this->session->requestKeySent !== true) {
$this->generateKey();
$this->sendRequestEmail();
$this->session->requestKeySent = true;
return $this->getRequestKeyMessage();
} else {
return $this->getRequestKeyMessage();
}
} else if ($segment1 === 'key' and empty($segment2)) {
wire('session')->redirect($this->page->url);
} else if ($segment1 === 'key' and !empty($segment2)) {
return $this->getResetForm();
} else if ($segment1 === 'reset') {
return $this->resetPassword();
}
}
public function ___install() {
// password reset request template (the child storing requests)
$expirationField = new Field();
$expirationField->type = $this->modules->get('FieldtypeInteger');
$expirationField->name = 'passwordResetExpiration';
$expirationField->save();
$userField = new Field();
$userField->type = $this->modules->get('FieldtypePage');
$userTemplateId = $this->templates->get('user')->id;
$userField->data('derefAsPage', 1);
$userField->data('template_id', $userTemplateId);
$userField->name = 'passwordResetUser';
$userField->save();
$requestFieldgroup = new Fieldgroup();
$requestFieldgroup->name = 'password-reset-request';
$requestFieldgroup->add($this->fields->get('title'));
$requestFieldgroup->add($expirationField);
$requestFieldgroup->add($userField);
$requestFieldgroup->save();
$requestTemplate = new Template();
$requestTemplate->name = 'password-reset-request';
$requestTemplate->fieldgroup = $requestFieldgroup;
$requestTemplate->noChildren = true;
$requestTemplate->save();
// password reset template (the parent under which individual requests are stored)
$fg = new Fieldgroup();
$fg->name = 'password-reset';
$fg->add($this->fields->get('title'));
$fg->save();
$passwordResetTemplate = new Template();
$passwordResetTemplate->name = 'password-reset';
$passwordResetTemplate->urlSegments(true);
$passwordResetTemplate->fieldgroup = $fg;
$passwordResetTemplate->childTemplates = [$requestFieldgroup->id];
$passwordResetTemplate->childrenTemplatesID;
$passwordResetTemplate->save();
$requestTemplate->parentTemplates = [$passwordResetTemplate->id];
$requestTemplate->save();
}
}