/app/Auth/Gitlab.php

https://gitlab.com/x33n/kanboard · PHP · 122 lines · 57 code · 14 blank · 51 comment · 2 complexity · 84ae2ddbb6d3f438f516e44ada54622a MD5 · raw file

  1. <?php
  2. namespace Auth;
  3. use Event\AuthEvent;
  4. /**
  5. * Gitlab backend
  6. *
  7. * @package auth
  8. */
  9. class Gitlab extends Base
  10. {
  11. /**
  12. * Backend name
  13. *
  14. * @var string
  15. */
  16. const AUTH_NAME = 'Gitlab';
  17. /**
  18. * OAuth2 instance
  19. *
  20. * @access private
  21. * @var \Core\OAuth2
  22. */
  23. private $service;
  24. /**
  25. * Authenticate a Gitlab user
  26. *
  27. * @access public
  28. * @param string $gitlab_id Gitlab user id
  29. * @return boolean
  30. */
  31. public function authenticate($gitlab_id)
  32. {
  33. $user = $this->user->getByGitlabId($gitlab_id);
  34. if (! empty($user)) {
  35. $this->userSession->refresh($user);
  36. $this->container['dispatcher']->dispatch('auth.success', new AuthEvent(self::AUTH_NAME, $user['id']));
  37. return true;
  38. }
  39. return false;
  40. }
  41. /**
  42. * Unlink a Gitlab account for a given user
  43. *
  44. * @access public
  45. * @param integer $user_id User id
  46. * @return boolean
  47. */
  48. public function unlink($user_id)
  49. {
  50. return $this->user->update(array(
  51. 'id' => $user_id,
  52. 'gitlab_id' => '',
  53. ));
  54. }
  55. /**
  56. * Update the user table based on the Gitlab profile information
  57. *
  58. * @access public
  59. * @param integer $user_id User id
  60. * @param array $profile Gitlab profile
  61. * @return boolean
  62. */
  63. public function updateUser($user_id, array $profile)
  64. {
  65. $user = $this->user->getById($user_id);
  66. return $this->user->update(array(
  67. 'id' => $user_id,
  68. 'gitlab_id' => $profile['id'],
  69. 'email' => empty($user['email']) ? $profile['email'] : $user['email'],
  70. 'name' => empty($user['name']) ? $profile['name'] : $user['name'],
  71. ));
  72. }
  73. /**
  74. * Get OAuth2 configured service
  75. *
  76. * @access public
  77. * @return \Core\OAuth2
  78. */
  79. public function getService()
  80. {
  81. if (empty($this->service)) {
  82. $this->service = $this->oauth->createService(
  83. GITLAB_CLIENT_ID,
  84. GITLAB_CLIENT_SECRET,
  85. $this->helper->url->to('oauth', 'gitlab', array(), '', true),
  86. GITLAB_OAUTH_AUTHORIZE_URL,
  87. GITLAB_OAUTH_TOKEN_URL,
  88. array()
  89. );
  90. }
  91. return $this->service;
  92. }
  93. /**
  94. * Get Gitlab profile
  95. *
  96. * @access public
  97. * @param string $code
  98. * @return array
  99. */
  100. public function getProfile($code)
  101. {
  102. $this->getService()->getAccessToken($code);
  103. return $this->httpClient->getJson(
  104. GITLAB_API_URL.'user',
  105. array($this->getService()->getAuthorizationHeader())
  106. );
  107. }
  108. }