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

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

https://bitbucket.org/seyar/parshin.local
PHP | 101 lines | 48 code | 13 blank | 40 comment | 4 complexity | 5fb3ad56233971f0e350973842900b77 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1
  1. <?php defined('SYSPATH') or die('No direct access allowed.');
  2. /**
  3. * Default auth user toke
  4. *
  5. * @package Kohana/Auth
  6. * @author Kohana Team
  7. * @copyright (c) 2007-2010 Kohana Team
  8. * @license http://kohanaframework.org/license
  9. */
  10. class Model_Auth_User_Token extends ORM {
  11. // Relationships
  12. protected $_belongs_to = array('user' => array());
  13. // Current timestamp
  14. protected $_now;
  15. /**
  16. * Handles garbage collection and deleting of expired objects.
  17. *
  18. * @return void
  19. */
  20. public function __construct($id = NULL)
  21. {
  22. parent::__construct($id);
  23. // Set the now, we use this a lot
  24. $this->_now = time();
  25. if (mt_rand(1, 100) === 1)
  26. {
  27. // Do garbage collection
  28. $this->delete_expired();
  29. }
  30. if ($this->expires < $this->_now)
  31. {
  32. // This object has expired
  33. $this->delete();
  34. }
  35. }
  36. /**
  37. * Overload saving to set the created time and to create a new token
  38. * when the object is saved.
  39. *
  40. * @return ORM
  41. */
  42. public function save()
  43. {
  44. if ($this->loaded() === FALSE)
  45. {
  46. // Set the created time, token, and hash of the user agent
  47. $this->created = $this->_now;
  48. $this->user_agent = sha1(Request::$user_agent);
  49. }
  50. while (TRUE)
  51. {
  52. // Generate a new token
  53. $this->token = $this->create_token();
  54. try
  55. {
  56. return parent::save();
  57. }
  58. catch (Kohana_Database_Exception $e)
  59. {
  60. // Collision occurred, token is not unique
  61. }
  62. }
  63. }
  64. /**
  65. * Deletes all expired tokens.
  66. *
  67. * @return ORM
  68. */
  69. public function delete_expired()
  70. {
  71. // Delete all expired tokens
  72. DB::delete($this->_table_name)
  73. ->where('expires', '<', $this->_now)
  74. ->execute($this->_db);
  75. return $this;
  76. }
  77. /**
  78. * Generate a new unique token.
  79. *
  80. * @return string
  81. * @uses Text::random
  82. */
  83. protected function create_token()
  84. {
  85. // Create a random token
  86. return Text::random('alnum', 32);
  87. }
  88. } // End Auth User Token Model