PageRenderTime 42ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/auth/classes/model/_auth_nodelete/user/token.php

https://bitbucket.org/seyar/startech.local
PHP | 96 lines | 51 code | 15 blank | 30 comment | 5 complexity | b451bcf906a6c23846376d7346399f24 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1
  1. <?php defined('SYSPATH') OR die('No direct access allowed.');
  2. class Model_Auth_User_Token extends ORM {
  3. // Relationships
  4. protected $_belongs_to = array('user' => array());
  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(Request::$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. DB::delete($this->_table_name)
  51. ->where('expires', '<', $this->_now)
  52. ->execute($this->_db);
  53. return $this;
  54. }
  55. /**
  56. * Finds a new unique token, using a loop to make sure that the token does
  57. * not already exist in the database. This could potentially become an
  58. * infinite loop, but the chances of that happening are very unlikely.
  59. *
  60. * @return string
  61. */
  62. protected function create_token()
  63. {
  64. while (TRUE)
  65. {
  66. // Create a random token
  67. $token = text::random('alnum', 32);
  68. // Make sure the token does not already exist
  69. $count = DB::select('id')
  70. ->where('token', '=', $token)
  71. ->from($this->_table_name)
  72. ->execute($this->_db)
  73. ->count();
  74. if ($count === 0)
  75. {
  76. // A unique token has been found
  77. return $token;
  78. }
  79. }
  80. }
  81. } // End Auth User Token Model