EMongoAuthManager.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * EMongoAuthManager
  4. *
  5. * Represents an authorization manager that stores authorization information in terms of a mongodb document.
  6. * The authorization hierarchy is stored in a collection named "acl" by default.
  7. *
  8. * Usage:
  9. *
  10. * Add the following to your config/main.php
  11. *
  12. * 'components' => array(
  13. * ...
  14. * 'authManager' => array(
  15. * 'class' => 'EMongoAuthManager'
  16. * )
  17. * )
  18. *
  19. */
  20. class EMongoAuthManager extends CPhpAuthManager
  21. {
  22. /**
  23. *
  24. * @var string the name of the mongodb collection that contains the authorization data.
  25. * If not set, it will be using 'acl' as the collection.
  26. * @see loadFromFile
  27. * @see saveToFile
  28. */
  29. public $collectionName = 'acl';
  30. /**
  31. *
  32. * @var string the connectionId of the EMongoClient component
  33. */
  34. public $connectionId = 'mongodb';
  35. /**
  36. *
  37. * @var string the MongoId of the current auth record
  38. */
  39. private $_id;
  40. /**
  41. * Get a MongoCollection object
  42. *
  43. * @return Instance of MongoCollection
  44. */
  45. public function getMongoConnection($collection = null)
  46. {
  47. return Yii::app()->{$this->connectionId}->{$collection === null ? $this->collectionName : $collection};
  48. }
  49. /**
  50. * Initializes the application component.
  51. * This method overrides parent implementation by loading the authorization data
  52. * from mongodb collection.
  53. */
  54. public function init()
  55. {
  56. // For compatibility reasons, collection name must be stored in "authFile"
  57. $this->authFile = $this->collectionName;
  58. $this->load();
  59. }
  60. /**
  61. * Loads the authorization data from mongodb collection.
  62. * @param string $collection the collection name.
  63. * @return array the authorization data
  64. * @see saveToFile
  65. */
  66. protected function loadFromFile($collection)
  67. {
  68. $mongoCollection = $this->getMongoConnection($collection);
  69. $data = $mongoCollection->findOne();
  70. if($data === null){
  71. return array();
  72. }
  73. $this->_id = $data['_id'];
  74. unset($data['_id']);
  75. return $data;
  76. }
  77. /**
  78. * Saves the authorization data to a mongodb collection.
  79. * @param array $data the authorization data
  80. * @param string $collection the collection name
  81. * @see loadFromFile
  82. */
  83. protected function saveToFile($data, $collection)
  84. {
  85. if($this->_id !== null){
  86. $data['_id'] = $this->_id;
  87. }
  88. $this->getMongoConnection($collection)->save($data);
  89. }
  90. }