WebService.class.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\UserBundle\Entity\User;
  4. /**
  5. * Base class for Web Services.
  6. *
  7. * @author Angel Fernando Quiroz Campos <angel.quiroz@beeznest.com>
  8. *
  9. * @package chamilo.webservices
  10. */
  11. class WebService
  12. {
  13. /**
  14. * @var User
  15. */
  16. protected $user;
  17. /**
  18. * @var string
  19. */
  20. protected $apiKey;
  21. /**
  22. * Class constructor.
  23. *
  24. * @param $username
  25. * @param $apiKey
  26. */
  27. protected function __construct($username, $apiKey)
  28. {
  29. /** @var User user */
  30. $this->user = UserManager::getManager()->findUserByUsername($username);
  31. $this->apiKey = $apiKey;
  32. }
  33. /**
  34. * @param string $username
  35. * @param string $apiKeyToValidate
  36. *
  37. * @return WebService
  38. */
  39. public static function validate($username, $apiKeyToValidate)
  40. {
  41. return new self($username, $apiKeyToValidate);
  42. }
  43. /**
  44. * Find the api key for a user. If the api key does not exists is created.
  45. *
  46. * @param string $username
  47. * @param string $serviceName
  48. *
  49. * @return string
  50. */
  51. public static function findUserApiKey($username, $serviceName)
  52. {
  53. $user = UserManager::getManager()->findUserByUsername($username);
  54. if ($user) {
  55. $apiKeys = UserManager::get_api_keys($user->getId(), $serviceName);
  56. if (empty($apiKeys)) {
  57. UserManager::add_api_key($user->getId(), $serviceName);
  58. }
  59. $apiKeys = UserManager::get_api_keys($user->getId(), $serviceName);
  60. return current($apiKeys);
  61. }
  62. return '';
  63. }
  64. /**
  65. * Check whether the username and password are valid.
  66. *
  67. * @param string $username
  68. * @param string $password
  69. *
  70. * @throws Exception
  71. *
  72. * @return bool Return true if the password belongs to the username. Otherwise return false
  73. */
  74. public static function isValidUser($username, $password)
  75. {
  76. if (empty($username) || empty($password)) {
  77. return false;
  78. }
  79. $user = UserManager::getManager()->findUserByUsername($username);
  80. if (!$user) {
  81. return false;
  82. }
  83. return UserManager::isPasswordValid(
  84. $user->getPassword(),
  85. $password,
  86. $user->getSalt()
  87. );
  88. }
  89. }