Qlogin.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. //TODO: later Auth Plugin
  3. App::uses('ToolsAppModel', 'Tools.Model');
  4. App::uses('CakeSession', 'Model/Datasource');
  5. /**
  6. * Manage Quick Logins
  7. *
  8. * @author Mark Scherer
  9. * @cakephp 2.x
  10. * @license MIT
  11. */
  12. class Qlogin extends ToolsAppModel {
  13. public $useTable = false;
  14. public $validate = array(
  15. 'url' => array(
  16. 'notEmpty' => array(
  17. 'rule' => array('notEmpty'),
  18. 'message' => 'valErrMandatoryField',
  19. 'last' => true
  20. ),
  21. 'validateUrl' => array(
  22. 'rule' => array('validateUrl', array('deep'=>false, 'sameDomain'=>true, 'autoComplete'=>true)),
  23. 'message' => 'valErrInvalidQloginUrl',
  24. 'last' => true
  25. )
  26. ),
  27. 'user_id' => array(
  28. 'notEmpty' => array(
  29. 'rule' => array('notEmpty'),
  30. 'message' => 'valErrMandatoryField',
  31. 'last' => true
  32. ),
  33. /*
  34. 'validateUnique' => array(
  35. 'rule' => array('validateUnique', array('url')),
  36. 'message' => 'key already exists',
  37. ),
  38. */
  39. ),
  40. );
  41. protected function _useKey($key) {
  42. if (!isset($this->CodeKey)) {
  43. $this->CodeKey = ClassRegistry::init('Tools.CodeKey');
  44. }
  45. return $this->CodeKey->useKey('qlogin', $key);
  46. }
  47. protected function _newKey($uid, $content) {
  48. if (!isset($this->CodeKey)) {
  49. $this->CodeKey = ClassRegistry::init('Tools.CodeKey');
  50. }
  51. return $this->CodeKey->newKey('qlogin', null, $uid, $content);
  52. }
  53. public function translate($key) {
  54. $res = $this->_useKey($key);
  55. if (!$res) {
  56. return false;
  57. }
  58. $res['CodeKey']['content'] = unserialize($res['CodeKey']['content']);
  59. $res['CodeKey']['url'] = Router::url($res['CodeKey']['content'], true);
  60. return $res;
  61. }
  62. /**
  63. * Generates a qlogin key
  64. * @param mixed $url
  65. * @param string $uid
  66. * @return string key
  67. */
  68. public function generate($url, $uid) {
  69. $content = serialize($url);
  70. return $this->_newKey($uid, $content);
  71. }
  72. public static function urlByKey($key) {
  73. return Router::url(array('admin' => false, 'plugin'=>'tools', 'controller'=>'qlogin', 'action'=>'go', $key), true);
  74. }
  75. /**
  76. * Makes an absolute url string ready to input anywhere
  77. * uses generate() internally to get the key
  78. * @param mixed $url
  79. * @return string url (absolute)
  80. */
  81. public function url($url, $uid = null) {
  82. if ($uid === null) {
  83. $uid = CakeSession::read('Auth.User.id');
  84. }
  85. $key = $this->generate($url, $uid);
  86. return $this->urlByKey($key);
  87. }
  88. }