This repository was archived by the owner on Aug 13, 2024. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathusers.obj.php
More file actions
566 lines (442 loc) · 15.3 KB
/
Copy pathusers.obj.php
File metadata and controls
566 lines (442 loc) · 15.3 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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
<?php
/**
* This file is part of SimpleUsers.
*
*/
/**
* SimpleUsers is a small-scale and flexible way of adding
* user management to your website or web applications.
*/
class SimpleUsers
{
private $mysqli, $stmt;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
/**
* Object construct verifies that a session has been started and that a MySQL connection can be established.
* It takes no parameters.
*
* @throws Exception
*/
public function __construct()
{
$sessionId = session_id();
if (strlen($sessionId) == 0) {
throw new Exception("No session has been started.\n<br />Please add `session_start();` initially in your file before any output.");
}
$this->mysqli = new mysqli($GLOBALS["mysql_hostname"], $GLOBALS["mysql_username"], $GLOBALS["mysql_password"], $GLOBALS["mysql_database"]);
if ($this->mysqli->connect_error) {
throw new Exception("MySQL connection could not be established: " . $this->mysqli->connect_error);
}
$this->_validateUser();
$this->_populateUserdata();
$this->_updateActivity();
}
/**
* Returns a (int)user id, if the user was created succesfully.
* If not, it returns (bool)false.
*
* @param $username
* @param $password
* @return bool|int
* @throws Exception
*/
public function createUser($username, $password)
{
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users VALUES (NULL, ?, ?, NOW(), NOW())";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("ss", $username, $password);
if ($this->stmt->execute()) {
return $this->stmt->insert_id;
}
return false;
}
/**
* Pairs up username and password as registrered in the database.
* If the username and password is correct, it will return (int)user id of
* the user which credentials has been passed and set the session, for
* use by the user validating.
*
* @param $username
* @param $password
* @return bool
* @throws Exception
*/
public function loginUser($username, $password)
{
$sql = "SELECT userId, uPassword FROM users WHERE uUsername=? LIMIT 1";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("s", $username);
$this->stmt->execute();
$this->stmt->store_result();
if ($this->stmt->num_rows == 0) {
return false;
}
$this->stmt->bind_result($userId, $userPassword);
$this->stmt->fetch();
if(!password_verify($password, $userPassword)) {
return false;
}
$_SESSION[$this->sessionName]["userId"] = $userId;
$this->logged_in = true;
return $userId;
}
/**
* Sets an information pair, consisting of a key name and that keys value.
* The information can be retrieved with this objects getInfo() method.
*
* @param $key
* @param $value
* @param null $userId Can be used if administrative control is needed
* @return bool
* @throws Exception
*/
public function setInfo($key, $value, $userId = null)
{
if ($userId == null) {
if (!$this->logged_in)
return false;
}
$reservedKeys = array("userId", "uUsername", "uActivity", "uCreated", "uLevel");
if (in_array($key, $reservedKeys))
throw new Exception("User information key \"" . $key . "\" is reserved for internal use!");
if ($userId == null)
$userId = $_SESSION[$this->sessionName]["userId"];
if ($this->getInfo($key, $userId)) {
$sql = "UPDATE users_information SET infoValue=? WHERE infoKey=? AND userId=? LIMIT 1";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("ssi", $value, $key, $userId);
$this->stmt->execute();
} else {
$sql = "INSERT INTO users_information VALUES (?, ?, ?)";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("iss", $userId, $key, $value);
$this->stmt->execute();
}
return true;
}
/**
* Use this function to retrieve user information attached to a certain user
* that has been set by using this objects setInfo() method.
*
* @param $key
* @param null $userId Can be used if administrative control is needed
* @return bool|string
* @throws Exception
*/
public function getInfo($key, $userId = null)
{
if ($userId == null) {
if (!$this->logged_in)
return false;
$userId = $_SESSION[$this->sessionName]["userId"];
}
$sql = "SELECT infoValue FROM users_information WHERE userId=? AND infoKey=? LIMIT 1";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("is", $userId, $key);
$this->stmt->execute();
$this->stmt->store_result();
if ($this->stmt->num_rows == 0) {
return "";
}
$this->stmt->bind_result($value);
$this->stmt->fetch();
return $value;
}
/**
* Use this function to permanently remove information attached to a certain user
* that has been set by using this objects setInfo() method.
*
* @param $key
* @param null $userId Can be used if administrative control is needed
* @return bool
* @throws Exception
*/
public function removeInfo($key, $userId = null)
{
if ($userId == null) {
if (!$this->logged_in) {
return false;
}
$userId = $_SESSION[$this->sessionName]["userId"];
}
$sql = "DELETE FROM users_information WHERE userId=? AND infoKey=? LIMIT 1";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("is", $userId, $key);
$this->stmt->execute();
if ($this->stmt->affected_rows > 0) {
return true;
}
return false;
}
/**
* Use this function to retrieve all user information attached to a certain user
* that has been set by using this objects setInfo() method into an array.
*
* @param null $userId
* @return array|bool
* @throws Exception
*/
public function getInfoArray($userId = null)
{
if ($userId == null) {
if (!$this->logged_in) {
return false;
}
$userId = $_SESSION[$this->sessionName]["userId"];
}
$sql = "SELECT infoKey, infoValue FROM users_information WHERE userId=? ORDER BY infoKey ASC";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("i", $userId);
$this->stmt->execute();
$this->stmt->store_result();
$userInfo = array();
if ($this->stmt->num_rows > 0) {
$this->stmt->bind_result($key, $value);
while ($this->stmt->fetch()) {
$userInfo[$key] = $value;
}
}
$user = $this->getSingleUser($userId);
$userInfo = array_merge($userInfo, $user);
asort($userInfo);
return $userInfo;
}
/**
* Logout the active user, unsetting the userId session.
* This is a void function
*/
public function logoutUser()
{
if (isset($_SESSION[$this->sessionName])) {
unset($_SESSION[$this->sessionName]);
}
$this->logged_in = false;
}
/**
* Update the users password with this function.
* Generates a new salt and a sets the users password with the given parameter
*
* @param $password
* @param null $userId Can be used if administrative control is needed
* @return bool
* @throws Exception
*/
public function setPassword($password, $userId = null)
{
if ($userId == null) {
$userId = $_SESSION[$this->sessionName]["userId"];
}
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = "UPDATE users SET uPassword=? WHERE userId=? LIMIT 1";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("si", $password,$userId);
return $this->stmt->execute();
}
/**
* Returns an array with each user in the database.
*
* @return array
*/
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->execute();
$this->stmt->store_result();
if ($this->stmt->num_rows == 0) {
return array();
}
$this->stmt->bind_result($userId, $username, $activity, $created);
$users = array();
$i = 0;
while ($this->stmt->fetch()) {
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
return $users;
}
/**
* Gets the basic info for a single user based on the userId
*
* @param null $userId Can be used if administrative control is needed
* @return bool
* @throws Exception
*/
public function getSingleUser($userId = null)
{
if ($userId == null) {
$userId = $_SESSION[$this->sessionName]["userId"];
}
$sql = "SELECT userId, uUsername, uActivity, uCreated FROM users WHERE userId=? LIMIT 1";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("i", $userId);
$this->stmt->execute();
$this->stmt->store_result();
if ($this->stmt->num_rows == 0) {
return false;
}
$this->stmt->bind_result($userId, $username, $activity, $created);
$this->stmt->fetch();
$user["userId"] = $userId;
$user["uUsername"] = $username;
$user["uActivity"] = $activity;
$user["uCreated"] = $created;
return $user;
}
/**
* Deletes all information regarding a user.
* This is a void function.
*
* @param $userId
* @throws Exception
*/
public function deleteUser($userId)
{
$sql = "DELETE FROM users WHERE userId=?";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("i", $userId);
$this->stmt->execute();
$sql = "DELETE FROM users_information WHERE userId=?";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("i", $userId);
$this->stmt->execute();
}
/**
* Returns a hidden input field with a unique token value
* for CSRF to be used with post data.
* The token is saved in a session for later validation.
*
* @param bool $xhtml
* @return string
*/
public function getToken($xhtml = true)
{
$token = uniqid($this->sessionName, true);
$name = "token_" . md5($token);
$_SESSION[$this->sessionName]["csrf_name"] = $name;
$_SESSION[$this->sessionName]["csrf_token"] = $token;
$string = "<input type=\"hidden\" name=\"" . $name . "\" value=\"" . $token . "\"";
if ($xhtml)
$string .= " />";
else
$string .= ">";
return $string;
}
/**
* Use this method when you wish to validate the CSRF token from your post data.
* The method returns true upon validation, otherwise false.
*
* @return bool
*/
public function validateToken()
{
$name = $_SESSION[$this->sessionName]["csrf_name"];
$token = $_SESSION[$this->sessionName]["csrf_token"];
unset($_SESSION[$this->sessionName]["csrf_token"]);
unset($_SESSION[$this->sessionName]["csrf_name"]);
if ($_POST[$name] == $token)
return true;
return false;
}
/**
* This function updates the users last activity time
* This is a void function.
*/
private function _updateActivity()
{
if (!$this->logged_in) {
return;
}
$userId = $_SESSION[$this->sessionName]["userId"];
$sql = "UPDATE users SET uActivity=NOW() WHERE userId=? LIMIT 1";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("i", $userId);
$this->stmt->execute();
}
/**
* Validates if the user is logged in or not.
* This is a void function.
*/
private function _validateUser()
{
if (!isset($_SESSION[$this->sessionName]["userId"])) {
return;
}
if (!$this->_validateUserId()) {
return;
}
$this->logged_in = true;
}
/**
* Validates if the user id, in the session is still valid.
*
* @return bool
* @throws Exception
*/
private function _validateUserId()
{
$userId = $_SESSION[$this->sessionName]["userId"];
$sql = "SELECT userId FROM users WHERE userId=? LIMIT 1";
if (!$this->stmt = $this->mysqli->prepare($sql)) {
throw new Exception("MySQL Prepare statement failed: " . $this->mysqli->error);
}
$this->stmt->bind_param("i", $userId);
$this->stmt->execute();
$this->stmt->store_result();
if ($this->stmt->num_rows == 1) {
return true;
}
$this->logoutUser();
return false;
}
/**
* Populates the current users data information for
* quick access as an object.
*
* @return void
* @throws Exception
*/
private function _populateUserdata()
{
$this->userdata = array();
if ($this->logged_in) {
$data = $this->getInfoArray();
foreach ($data as $key => $value) {
$this->userdata[$key] = $value;
}
}
}
}
?>