-
Notifications
You must be signed in to change notification settings - Fork 1
/
user_management.class.php
executable file
·523 lines (442 loc) · 18.1 KB
/
user_management.class.php
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
<?php
include('includes/Swift/lib/swift_required.php');
include('configuration.php');
include('includes/klogger.class.php');
class User_Management
{
//The database settings and table structures are inherited from the Configuration.php file.
private $db_host = DB_HOST;
private $db_username = DB_USERNAME;
private $db_password = DB_PASSWORD;
private $db_name = DB_NAME;
private $db_port = DB_PORT;
private $user_table = TABLE_WITH_USERS;
private $email_col = COLUMN_WITH_EMAILS;
private $password_col = COLUMN_WITH_PASSWORD_HASHES;
private $activated_col = COLUMN_CONFIRMING_ACCOUNT_ACTIVATION;
private $emailed_hash_col = COLUMN_WITH_EMAILED_HASHES;
private $encryption_rounds = ENCRYPTION_ROUNDS;
private $mysqli;
private $log;
//Start a database connection.
public function __construct()
{
$this->log = new Klogger(LOG_DIRECTORY, 7);
$this->mysqli = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name, $this->db_port);
if($this->mysqli->connect_error)
{
$this->log->logCrit('The database connection failed', $this->mysqli->connect_error);
}
}
public function create_user($email, $password)
{
if(!($email && $password))
{
return FALSE;
}
if($this->is_registered($email))
{
return FALSE;
}
else
{
$password = $this->encrypt_password($password);
//To be sent in the email confirmation link.
$random_hash = $this->generate_random_hash();
//Add the email, password, and random hash to the database. The $activated_col should be 0 by default, and 1 once the emailed link is clicked.
$stmt = $this->mysqli->prepare("INSERT INTO `$this->user_table`(`$this->email_col`, `$this->password_col`, `$this->emailed_hash_col`, `$this->activated_col`) VALUES(?, ?, ?, 0)");
$stmt->bind_param('sss', $email, $password, $random_hash);
$stmt->execute();
}
if($this->mysqli->error)
{
$this->log->logCrit('Failed to create user', $this->mysqli->error);
return FALSE;
}
//Generate the email.
$mail = $this->send_email($email, 'registration', $random_hash);
//Send the email.
if($mail)
{
return TRUE;
}
else
{
//Rollback the database insertion.
//The 3rd parameter indicates that the password is encrypted
$this->delete_user($email, $password, TRUE);
return FALSE;
}
}
//This function will check if a user exists in the database.
public function is_registered($email)
{
if(!$email)
{
return FALSE;
}
$stmt = $this->mysqli->prepare("SELECT `$this->email_col` FROM `$this->user_table` WHERE `$this->email_col` = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->bind_result($email_in_database);
$stmt->fetch();
if($this->mysqli->error)
{
$this->log->logCrit('Failed to check if the user is_registered', $this->mysqli->error);
return FALSE;
}
if($email_in_database == $email)
{
return TRUE;
}
else
{
return FALSE;
}
}
public function resend_activation_email($email)
{
$stmt = $this->mysqli->prepare("SELECT `$this->emailed_hash_col`, `$this->activated_col` FROM `$this->user_table` WHERE `$this->email_col` = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->bind_result($random_hash, $activated);
$stmt->fetch();
if($this->mysqli->error)
{
$this->log->logCrit('Failed to resend activation email', $this->mysqli->error);
return FALSE;
}
//If the user has already managed to activate their account, they don't need an account activation link
if($activated)
{
return FALSE;
}
//Generate the email.
$mail = $this->send_email($email, 'registration', $random_hash);
if($mail)
{
return TRUE;
}
else
{
return FALSE;
}
}
//This function will check if a registered user has activated their account.
public function is_activated($email)
{
if(!$email)
{
return FALSE;
}
$stmt = $this->mysqli->prepare("SELECT `$this->activated_col` FROM `$this->user_table` WHERE `$this->email_col` = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->bind_result($activated);
$stmt->fetch();
if($this->mysqli->error)
{
$this->log->logCrit('Failed to check if the user is_activated', $this->mysqli->error);
return FALSE;
}
if($activated == 1)
{
return TRUE;
}
else
{
return FALSE;
}
}
public function login($email, $password)
{
if(!($email && $password))
{
return FALSE;
}
//Fetch the password from database by matching the email. If there is no result, the $email does not exist.
//Also fetch the account activation flag, because we don't allow someone to login if they haven't activated their account.
$stmt = $this->mysqli->prepare("SELECT `$this->password_col`, `$this->activated_col` FROM `$this->user_table` WHERE `$this->email_col` = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->bind_result($stored_password, $activated);
$stmt->fetch();
if($this->mysqli->error)
{
$this->log->logCrit('Login failed', $this->mysqli->error);
return FALSE;
}
//Check if the password hashes match
if(!password_verify($password, $stored_password))
{
return FALSE;
}
//Check that the account has been activated through the emailed link.
if($activated === 0)
{
return FALSE;
}
return TRUE;
}
public function change_password($email, $old_password, $new_password)
{
if(!($email && $old_password && $new_password))
{
return FALSE;
}
//Validate the $email/$password combination provided.
if(!$this->login($email, $old_password))
{
return FALSE;
}
$new_password = $this->encrypt_password($new_password);
$stmt = $this->mysqli->prepare("UPDATE `$this->user_table` SET `$this->password_col` = ? WHERE `$this->email_col` = ?");
$stmt->bind_param('ss', $new_password, $email);
$stmt->execute();
if($this->mysqli->error)
{
$this->log->logCrit('Failed to change password', $this->mysqli->error);
return FALSE;
}
return TRUE;
}
//Email a password reset link embedded with a unique hash.
public function reset_password($email)
{
if(!$email)
{
return FALSE;
}
//Why would the user try to reset their password before activating their account?
if(!$this->is_activated($email))
{
return FALSE;
}
//If the user accidentally or impatiently clicks the Submit button in a password reset form thinking it might not have worked the
//first time, because emails sometimes take a few minutes to send, they might trigger this function twice.
//An issue with that is a new $random_hash will be generated, inserted into the database, and emailed. This renders the previous
//$emailed_hash useless, so the user might click on the first email they received and wonder why it's not working. To prevent a new
//$random_hash being calculated, we check for an existing one first.
$stmt = $this->mysqli->prepare("SELECT `$this->emailed_hash_col` FROM `$this->user_table` WHERE `$this->email_col` = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->bind_result($random_hash);
$stmt->fetch();
if($this->mysqli->error)
{
$this->log->logCrit('Error checking for existing $random_hash in reset_password', $this->mysqli->error);
return FALSE;
}
if(!$random_hash)
{
$stmt->store_result();
$random_hash = $this->generate_random_hash();
//Insert the $random_hash into the database.
$stmt = $this->mysqli->prepare("UPDATE `$this->user_table` SET `$this->emailed_hash_col` = ? WHERE `$this->email_col` = ?");
$stmt->bind_param('ss', $random_hash, $email);
$stmt->execute();
if($this->mysqli->error)
{
$this->log->logCrit('Error inserting $random_hash', $this->mysqli->error);
return FALSE;
}
}
//Generate and send email.
$mail = $this->send_email($email, 'reset', $random_hash);
if(!$mail)
{
//Rollback changes to database.
$this->mysqli->query("UPDATE `$this->user_table` SET `$this->emailed_hash_col` = '' WHERE `$this->emailed_hash_col` = '$random_hash'");
return FALSE;
}
return TRUE;
}
private function hash_exists($hash)
{
if(!$hash)
{
return FALSE;
}
$stmt = $this->mysqli->prepare("SELECT `$this->emailed_hash_col` FROM `$this->user_table` WHERE `$this->emailed_hash_col` = ?");
$stmt->bind_param('s', $hash);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if($this->mysqli->error)
{
$this->log->logCrit('Failed to check if hash exists', $this->mysqli->error);
return FALSE;
}
if($hash == $result)
{
return TRUE;
}
}
//Delete a user from the database after verifying that the user is authorised to delete the account
public function delete_user($email, $password, $is_password_encrypted = FALSE)
{
if(!($email && $password))
{
return FALSE;
}
//The login() function requires an unencrypted password to validate the user
if($is_password_encrypted == FALSE)
{
//Check if the supplied credentials match
if($this->login($email, $password))
{
$stmt = $this->mysqli->prepare("DELETE FROM `$this->user_table` WHERE `$this->email_col` = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
return TRUE;
}
}
//If this function was called from inside this class (for example, to rollback user changes), then the supplied password may already be encrypted
//If the password is already encrypted, then we don't need to use the login() function
else
{
//Delete the user if the supplied credentials match
$stmt = $this->mysqli->prepare("DELETE FROM `$this->user_table` WHERE `$this->email_col` = ? AND `$this->password_col` = ?");
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
return TRUE;
}
}
public function logout()
{
session_start();
$_SESSION = array();
session_destroy();
return TRUE;
}
public function set_password($new_password, $emailed_hash)
{
if(!($new_password && $emailed_hash))
{
return FALSE;
}
if(!$this->hash_exists($emailed_hash))
{
return FALSE;
}
$new_password = $this->encrypt_password($new_password);
//Insert the password, and delete the emailed_hash column since we want the link containing the hash to be dead after 1 use.
$stmt = $this->mysqli->prepare("UPDATE `$this->user_table` SET `$this->password_col` = ?, `$this->emailed_hash_col` = '' WHERE `$this->emailed_hash_col` = ?");
$stmt->bind_param('ss', $new_password, $emailed_hash);
$stmt->execute();
if($this->mysqli->error)
{
$this->log->logCrit('Error setting new password', $this->mysqli->error);
return FALSE;
}
return TRUE;
}
public function activate_account($hash)
{
if(!$hash)
{
return FALSE;
}
$empty = '';
//Update the 'Activated' field to TRUE, and delete the emailed_hash_column.
$stmt = $this->mysqli->prepare("UPDATE `$this->user_table` SET `$this->activated_col` = '1', `$this->emailed_hash_col` = ? WHERE `$this->emailed_hash_col` = ?");
$stmt->bind_param('ss', $empty, $hash);
$stmt->execute();
if(!$this->mysqli->error)
{
return TRUE;
}
else
{
$this->log->logCrit('Error setting Account Activated to true', $this->mysqli->error);
return FALSE;
}
}
private function encrypt_password($password)
{
$encrypted_password = password_hash($password, PASSWORD_BCRYPT, ["cost" => $this->encryption_rounds]);
return $encrypted_password;
}
//Generate a unique 32 character long hash. Called by create_user() and reset_password().
private function generate_random_hash()
{
//Create a $random_hash and check if it already exists in the database, and if yes, then generate another one until a unique hash is found.
$stmt = $this->mysqli->prepare("SELECT `$this->emailed_hash_col` FROM `$this->user_table` WHERE `$this->emailed_hash_col` = ? LIMIT 1");
do
{
$random_hash = md5(uniqid(rand(), true));
$stmt->bind_param('s', $random_hash);
$stmt->execute();
$stmt->bind_result($emailed_hash_col);
$stmt->fetch();
}
while($emailed_hash_col == $random_hash);
if(!$this->mysqli->error)
{
return $random_hash;
}
}
//Generate email, inheriting the values of constants from Configuration.php. The $type of email generated is either a registration confirmation or a password reset.
private function send_email($email, $type, $random_hash)
{
$transport = Swift_SmtpTransport::newInstance(SMTP_SERVER, PORT, SECURITY)
->setUsername(SMTP_USERNAME)
->setPassword(SMTP_PASSWORD);
$swift = Swift_Mailer::newInstance($transport);
//This try/catch block only exists because there is no way to turn off exception handling in SwiftMailer. Therefore we have to catch any exception SwiftMailer throws
//to prevent the user seeing an Uncaught Exception error.
try
{
if($type == 'registration')
{
$message = Swift_Message::newInstance()
->setFrom(SENDER_ADDRESS)
->setTo($email)
->setSubject(REGISTRATION_SUBJECT)
->setBody(REGISTRATION_BODY, 'text/html')
->setReplyTo(REPLY_TO);
}
elseif($type == 'reset')
{
$message = Swift_Message::newInstance()
->setFrom(SENDER_ADDRESS)
->setTo($email)
->setSubject(RESET_SUBJECT)
->setBody(RESET_BODY, 'text/html')
->setReplyTo(REPLY_TO);
}
else
{
return FALSE;
}
}
catch(Exception $e)
{
return FALSE;
}
//Replace the $random_hash placeholder in the Body's URL with the actual hash.
$message->setBody(str_replace('$random_hash', $random_hash, $message->getBody(), $counter));
if(($counter) != 1)
{
$this->log->logCrit('The $random_hash variable from the URL in the email bodies was modified/removed');
}
if(!$swift->send($message))
{
if($type == 'reset')
{
$this->log->logCrit('A password reset email failed to send');
return FALSE;
}
elseif($type == 'registration')
{
$this->log->logCrit('An account activation email failed to send');
return FALSE;
}
}
else
{
return TRUE;
}
}
}
?>