-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsession.php
714 lines (601 loc) · 18.7 KB
/
session.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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
<?php
session_cache_limiter(false);
session_start();
$current_user = false;
if (!config('auth.salt')) {
throw new Exception("Please set auth.salt config var to a strong key");
}
class Role extends Model {
static function getOrCreate($name) {
$factory = Model::factory(get_called_class());
if (!$role = $factory->where('name', $name)->find_one()) {
$role = $factory->create();
$role->name = $name;
$role->save();
}
return $roll;
}
}
class RoleUser extends Model {}
class User extends Model {
protected $_roles = false;
protected $_prefs = false;
protected $_settings = false;
static function load($id, $fields) {
$mem = "user:{$id}";
if ($user = memget($mem)) {
return $user;
}
$user = Model::factory(get_called_class())
->where('id', $id)
->find_one();
if ($user) {
memset($mem, $user);
}
return $user;
}
/**
* @public
*/
static function startLoginSession($userdata) {
try {
unset($userdata->password);
$user = self::_register($userdata, true);
} catch (EmailAddressAlreadyRegisteredException $e) {
$user = Model::factory('User')->where('email_address', $userdata->email_address)->find_one();
if (!$user) {
// hmm... double exception: we found an user, and then
// we couldn't find the user
throw new Exception("Oops! Something strange happened. Please try again.");
}
}
return $user->startUserLoginSession();
}
/**
* Generate a key suitable for authentication with a timeout
* specified in minutes, then e-mail that key to this user.
* @param int Number of minutes user has to login with key
*/
function startUserLoginSession($window = 5) {
if ($window < 1) {
throw new Exception("Invalid window size: must be greater than 0 minutes.");
}
// start with random unique string
$random = md5(uniqid());
// capture the current time
$time = time();
$key = $this->getHash($random, $time, $window)->key;
Mail::send(array(
'to' => $this->email_address,
'from' => 'yo@pickfourhq.com',
'subject' => sprintf("Here's the link for accessing your account today, %s", date('F j')),
'text' => 'slim:login.php'
), array(
'link' => 'https://'.$_SERVER['SERVER_NAME'].'/auth/'.$key
));
}
function getHash($random, $time, $window) {
$seed = "{$this->id},{$random},{$time},{$window}";
$hash = md5(config('auth.salt').$seed);
return (object) array(
'seed' => $seed,
'hash' => $hash,
'key' => "{$hash},{$seed}"
);
}
static function getBySessionKey($key) {
list($hash, $id, $random, $time, $window) = explode(',', $key);
if (!$id) {
throw new AccessException("Invalid login: ID is missing");
}
if (!$user = self::getBy('id', $id)) {
throw new AccessException("Invalid login: User does not exist by ID [{$id}]");
}
if (!$user->isSessionKeyValid($key)) {
throw new AccessException("Invalid login: Bad session key");
}
return $user;
}
function isSessionKeyValid($key) {
list($hash, $id, $random, $time, $window) = explode(',', $key);
if ($this->id != $id) {
return false;
}
if (!($hash && $random && $time && $window)) {
return false;
}
if ( (time() - $time)/60 > $window ) {
return false;
}
if ($hash != $this->getHash($random, $time, $window)->hash) {
return false;
}
return true;
}
/**
* @public
*/
static function register($userdata, $generate_password = false) {
$userdata = (object) $userdata;
// validation
if (!isset($userdata->email_address)) {
throw new Exception("E-mail address is required");
}
if (!isset($userdata->password)) {
if ($generate_password) {
$userdata->password = md5(uniqid().config('auth.salt'));
} else {
throw new Exception("Password is required");
}
}
if (strlen($userdata->password) < 8) {
throw new Exception("Password is too short: please use at least 8 characters");
}
// is email_address available?
if (self::isEmailAddressRegistered($userdata->email_address)) {
throw new EmailAddressAlreadyRegisteredException("That e-mail address is already registered");
}
$newUser = Model::factory(get_called_class())->create();
$newUser->name = trim($userdata->name);
$newUser->email_address = trim($userdata->email_address);
$newUser->password = self::hashPassword($userdata->password);
$newUser->utc_date_registered = date('c', time());
$newUser->utc_date_confirmed = null;
$newUser->save();
set_session($newUser, isset($userdata->remember) ? $userdata->remember : false);
// null out password
$newUser->password = null;
return $newUser;
}
function as_array() {
$data = parent::as_array();
unset($data['password']);
unset($data['email_address']);
$data['roles'] = $this->getRoles(true);
$data['prefs'] = $this->getPrefs(true);
return $data;
}
/**
* @public
*/
static function login($userdata) {
global $current_user;
$userdata = (object) $userdata;
// validation
if (!isset($userdata->email_address)) {
throw new Exception("E-mail address is required");
}
if (!isset($userdata->password)) {
throw new Exception("Password is required");
}
$user = Model::factory(get_called_class())->where('email_address', $userdata->email_address)->find_one();
if (!$user) {
throw new Exception("Oops! No user is registered for that e-mail address.");
}
if (!self::verifyPassword($userdata->password, $user->password)) {
throw new Exception("Oops! That password is incorrect.");
}
$user->utc_date_last_login = date('c', true);
$user->save();
set_session($user, isset($userdata->remember) ? $userdata->remember : false);
return $user;
}
function getPrefs($flush = false) {
if ($this->_prefs === false || $flush) {
$this->_prefs = array();
foreach($this->getSettings() as $setting) {
if (strpos($setting->name, 'pref_') === 0) {
$this->_prefs[substr($setting->name, 5)] = $setting->value;
}
}
}
return $this->_prefs;
}
function __wakeup() {
$this->_prefs = false;
$this->_settings = false;
$this->_roles = false;
}
function getSettings($flush = false) {
if ($this->_settings === false || $flush) {
$this->_settings = array();
foreach($this->settings()->find_many() as $setting) {
$this->_settings[] = (object) array(
'name' => $setting->name,
'value' => maybe_unserialize($setting->value)
);
}
}
return $this->_settings;
}
function settings() {
return $this->has_many('UserSetting');
}
/**
* @public
*/
static function prefs($prefs) {
global $app;
$req = $app->request();
if (!has_session()) {
throw new AccessException();
}
if ($req->isGet()) {
return current_user()->getPrefs(true);
}
if ($req->isPost()) {
// preferences are set by the client, so we allow pretty much
// anything to be stored there - don't forget this!
// it's really designed for storing flags, like whether or not
// a particular screen or message has been seen before
foreach($prefs as $pname => $value) {
$name = 'pref_'.trim($pname);
if (strlen($name) > UserSetting::MAX_NAME_LENGTH) {
throw new Exception("Preference name [{$pname}] is too long");
}
if (!preg_match('/^[\w_-]+$/', $name)) {
throw new Exception("Invalid preference name [{$pname}] is too long");
}
ORM::raw_execute("
INSERT INTO user_setting (
`user_id`,
`name`,
`value`
) VALUES (
?, ?, ?
) ON DUPLICATE KEY UPDATE
`user_id` = VALUES(`user_id`),
`name` = VALUES(`name`),
`value` = VALUES(`value`)
", array(
current_user()->id,
$name,
maybe_serialize($value)
));
}
}
if ($req->isDelete()) {
foreach($prefs as $pname => $value) {
$name = 'pref_'.trim($pname);
ORM::raw_execute("
DELETE FROM user_setting
WHERE
`user_id` = ?
AND `name` = ?
LIMIT 1
", array(
current_user()->id,
$name
));
}
}
}
/**
* Given a cleartext password and a hash, determine if the
* given password and hash match.
* @param String cleartext password
* @param String a previously-generated hash of that password
* @return bool true if the password and the has are paired
* @see ApplicationHelper::hashPassword
*/
public static function verifyPassword($cleartext, $storedHash) {
$bcrypt = new Bcrypt(12);
return $bcrypt->verify($cleartext.config('auth.salt'), $storedHash);
}
/**
* Given a cleartext password, generate a hash that can later
* be used to verify the content of the password used to create it.
* @param String cleartext password
* @return String a hash of the password
*/
public static function hashPassword($cleartext) {
$bcrypt = new Bcrypt(12);
return $bcrypt->hash($cleartext.config('auth.salt'));
}
function isEmailAddressRegistered($email_address) {
return (bool) Model::factory(get_called_class())->where('email_address', $email_address)->find_one();
}
function roles() {
return $this->has_many_through('Role');
}
function getRoles($flush = false) {
if ($this->_roles === false || $flush) {
$this->_roles = array_unique(array_map(function($role) {
return $role->name;
}, $this->roles()->find_many()));
}
return $this->_roles;
}
function can($role_name, $bool = null) {
// getter:
if (is_null($bool)) {
return in_array($role_name, $this->getRoles());
// setter:
} else {
$role = Role::getOrCreate($role_name);
if (true === (bool) $bool) {
if (!$this->id()) {
throw new Exception("Cannot add roles to an unsaved User");
}
$rel = Model::factory('RoleUser');
$rel->role_id = $role->id;
$rel->user_id = $this->id();
$rel->save();
$this->getRoles(true);
} else {
return Model::factory('RoleUser')->where('user_id', $this->id())->where('role_id', $role->id)->delete_many();
}
}
}
/*
function in($group, $bool = null) {
// getter:
if (is_null($bool)) {
return (bool) $this->groups()->where('group', $group)->find_one();
// setter:
} else {
if (true === (bool) $bool) {
if (!$this->id()) {
throw new Exception("Cannot put an unsaved User into groups");
}
$group = Model::factory('Group');
$group->group = $group;
$group->user_id = $this->id();
$group->save(); // might dupe up here, but we don't care...
} else {
return $this->groups()->where('group', $group)->delete();
}
}
}
*/
}
class UserSetting extends Model implements PrivateModel {
const MAX_NAME_LENGTH = 64;
}
/**
* Bcrypt hashing package.
* Usage:
* $bcrypt = new Bcrypt($rounds = 12);
* $hash = $bcrypt->hash('password');
* $bool = $bcrypt->verify('password', $hash) // == true
* The value of $rounds will affect both the $hash result, as
* well as the total time it takes to generate $hash.
* @see http://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php
*/
class Bcrypt {
private $rounds;
public function __construct($rounds = 12) {
if (CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}
$this->rounds = $rounds;
}
public function hash($input) {
$hash = crypt($input, $this->getSalt());
if(strlen($hash) > 13)
return $hash;
return false;
}
public function verify($input, $existingHash) {
$hash = crypt($input, $existingHash);
return $hash === $existingHash;
}
private function getSalt() {
$salt = sprintf('$2a$%02d$', $this->rounds);
$bytes = $this->getRandomBytes(16);
$salt .= $this->encodeBytes($bytes);
return $salt;
}
private $randomState;
private function getRandomBytes($count) {
$bytes = '';
if(function_exists('openssl_random_pseudo_bytes') &&
(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL slow on Win
$bytes = openssl_random_pseudo_bytes($count);
}
if($bytes === '' && is_readable('/dev/urandom') &&
($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}
if(strlen($bytes) < $count) {
$bytes = '';
if($this->randomState === null) {
$this->randomState = microtime();
if(function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}
for($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);
if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}
$bytes = substr($bytes, 0, $count);
}
return $bytes;
}
private function encodeBytes($input) {
// The following is code from the PHP Password Hashing Framework
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (1);
return $output;
}
}
/**
* @param boolean Pass true to force regeneration; a new key will be generated if it does not exist
* @return String CSRF nonce
*/
function csrf($regenerate = false) {
if ($regenerate || empty($_SESSION['csrf']) || !verify_csrf($_SESSION['csrf'])) {
$_SESSION['csrf'] = nonce('csrf');
}
$_SESSION['csrf'];
}
/**
* @param String (optional) Test a specific token; default will be taken from $_REQUEST['csrf']
* @return boolean
*/
function verify_csrf($token = null) {
if (!$token && !empty($_SERVER['HTTP_X_CSRF'])) {
$token = $_SERVER['HTTP_X_CSRF'];
}
if (!$token) {
$token = $_REQUEST['csrf'];
}
return verify_nonce('csrf', $token);
}
function assert_verified_csrf($token = null) {
if (!verify_csrf($token)) {
throw new Exception("Invalid CSRF token");
}
}
function assert_can_edit($data, $msg = null, $code = null) {
assert_logged_in();
if ($data instanceof Model) {
$arr = $data->as_array();
} else {
$arr = (array) $data;
}
$not_current_user = empty($arr['user_id']) || $arr['user_id'] !== current_user()->id;
if ( $not_current_user && !current_user_can('super') ) {
throw new AccessException($msg, $code);
}
}
/**
* Produce a unique identifier verifiable for a limited time only.
* If the user is logged in, include the user's member ID in the
* generation of the key, thus making it more unique.
* @param string $seed (Optional) Additional seed data makes the nonce
* unique to a specific request; must be reproducible for subsequent
* verification.
* @param boolean $onetime (Optional)
*/
function nonce($seed = null, $onetime = false) {
if ($onetime) {
$random = md5(uniqid());
setcookie(nonce($seed), $random);
$seed .= $random;
}
$seed .= session_id();
// hash the seed with our auth cookie salt, for extra special uniqueness
return substr(hash_hmac('md5', $seed . _nonce_tick(), config('auth.salt')), -12, 10);
}
/**
* Generate a nonce tick - a continuiously increasing integer that
* advanced by 1 NONCE_SPLIT times for every NONCE_LIFESPAN period. This value is
* used by nonce() and verify_nonce().
*/
function _nonce_tick() {
return ceil(time() / ( config('nonce.lifespan', 86400) / config('nonce.split', 24) ));
}
/**
* Verify a nonce, given the seed that was used to produce it.
* @param string $seed
* @param string $nonce
* @return int the number of nonce splits ago that the nonce was generated, up to NONCE_LIFESPAN / NONCE_SPLIT;
* use verify_nonce($seed, $nonce) === 1 for the shortest period, use verify_nonce($seed, $nonce) == true
* to validate the nonce within the entire NONCE_LIFESPAN (e.g., 24 hours)
*/
function verify_nonce($seed = null, $nonce, $onetime = false) {
if ($onetime) {
if (!isset($_COOKIE[nonce($seed)])) {
return false;
} else {
$seed .= $_COOKIE[nonce($seed)];
}
}
$seed .= session_id();
// get the current nonce tick
$tick = _nonce_tick();
for($i=0; $i<config('nonce.split', 24); $i++) {
if ( substr(hash_hmac('md5', $seed . ( $tick - $i ), config('auth.salt')), -12, 10) == $nonce ) {
return $i+1;
}
}
// Invalid nonce
return false;
}
function set_session($user, $remember = false) {
global $current_user;
$_SESSION['current_user'] = $current_user = $user;
// TODO: put user and pass hashes into login cookie
}
function has_session() {
global $current_user;
if ($current_user !== false) {
return $current_user;
}
if (empty($_SESSION['current_user'])) {
return false;
}
if (is_object($_SESSION['current_user'])) {
$current_user = $_SESSION['current_user'];
return $current_user;
}
$current_user = ORM::for_table('users')->where('id', $_SESSION['current_user'])->find_one();
if (!$current_user) {
unset($_SESSION['current_user']);
return false;
}
return $current_user;
}
/**
* Alias for has_session()
* @return User object or false if not an authenticated session
*/
function current_user() {
return has_session();
}
function assert_logged_in($message = null, $code = null) {
if (!has_session()) {
throw new AccessException($message, $code);
}
}
/**
* Alias for User::can()
* @return bool
*/
function current_user_can($role_name) {
return ( ($user = has_session()) && ( $user->can('super') || $user->can($role_name) ));
}
function response_die($app, $msg, $status = 500) {
// TODO: log errors
$response = $app->response();
$response->status($status);
$response['Content-Type'] = 'text/plain';
echo $msg;
}
class AccessException extends Exception {
function __construct($message = null, $code = null) {
if (is_null($message)) {
$message = 'Forbidden';
}
if (is_null($code)) {
$code = 403;
}
parent::__construct($message, $code);
}
}
class EmailAddressAlreadyRegisteredException extends Exception {}