PageRenderTime 90ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/auth/models/auth_user_token.php

https://github.com/Toushi/flow
PHP | 102 lines | 52 code | 17 blank | 33 comment | 6 complexity | 864caac6d2139ec14842f470473e0f57 MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. class Auth_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 = NULL)
  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->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->loaded === FALSE)
  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. $this->db->where('expires <', $this->now)->delete($this->table_name);
  51. return $this;
  52. }
  53. /**
  54. * Finds a new unique token, using a loop to make sure that the token does
  55. * not already exist in the database. This could potentially become an
  56. * infinite loop, but the chances of that happening are very unlikely.
  57. *
  58. * @return string
  59. */
  60. protected function create_token()
  61. {
  62. while (TRUE)
  63. {
  64. // Create a random token
  65. $token = text::random('alnum', 32);
  66. // Make sure the token does not already exist
  67. if ($this->db->select('id')->where('token', $token)->get($this->table_name)->count() === 0)
  68. {
  69. // A unique token has been found
  70. return $token;
  71. }
  72. }
  73. }
  74. /**
  75. * Allows loading by token string.
  76. */
  77. public function unique_key($id)
  78. {
  79. if ( ! empty($id) AND is_string($id) AND ! ctype_digit($id))
  80. {
  81. return 'token';
  82. }
  83. return parent::unique_key($id);
  84. }
  85. } // End Auth User Token Model