WebService.class.php 2.2 KB

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