PageRenderTime 47ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/auth/models/user_token.php

https://github.com/MHordecki/milionkostek
PHP | 100 lines | 51 code | 16 blank | 33 comment | 8 complexity | 65a27505f87ea208a30c98c5d36b5526 MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. class User_Token_Model extends ORM {
  3. // Relationships
  4. protected $belongs_to = array('user');
  5. // Current timestamp
  6. protected $now;
  7. /**
  8. * Handles garbage collection and deleting of expired objects.
  9. */
  10. public function __construct($id = FALSE)
  11. {
  12. parent::__construct($id);
  13. // Set the now, we use this a lot
  14. $this->now = time();
  15. if (mt_rand(1, 100) === 1)
  16. {
  17. // Do garbage collection
  18. $this->delete_expired();
  19. }
  20. if ($this->object->id != 0 AND $this->object->expires < $this->now)
  21. {
  22. // This object has expired
  23. $this->delete();
  24. }
  25. }
  26. /**
  27. * Overload saving to set the created time and to create a new token
  28. * when the object is saved.
  29. */
  30. public function save()
  31. {
  32. if ($this->object->id == 0)
  33. {
  34. // Set the created time, token, and hash of the user agent
  35. $this->created = $this->now;
  36. $this->user_agent = sha1(Kohana::$user_agent);
  37. }
  38. // Create a new token each time the token is saved
  39. $this->token = $this->create_token();
  40. return parent::save();
  41. }
  42. /**
  43. * Deletes all expired tokens.
  44. *
  45. * @return void
  46. */
  47. public function delete_expired()
  48. {
  49. // Delete all expired tokens
  50. self::$db->where('expires <', $this->now)->delete($this->table);
  51. }
  52. /**
  53. * Allows loading by token string.
  54. */
  55. protected function where_key($id)
  56. {
  57. if ( ! empty($id) AND is_string($id) AND ! ctype_digit($id))
  58. {
  59. return 'token';
  60. }
  61. return parent::where_key($id);
  62. }
  63. /**
  64. * Finds a new unique token, using a loop to make sure that the token does
  65. * not already exist in the database. This could potentially become an
  66. * infinite loop, but the chances of that happening are very unlikely.
  67. *
  68. * @return string
  69. */
  70. protected function create_token()
  71. {
  72. while (TRUE)
  73. {
  74. // Create a random token
  75. $token = text::random('alnum', 32);
  76. // Make sure the token does not already exist
  77. if (count(self::$db->select('id')->where('token', $token)->get($this->table)) === 0)
  78. {
  79. // A unique token has been found
  80. return $token;
  81. }
  82. }
  83. }
  84. } // End User Token