github_oauth.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package social
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "regexp"
  8. "github.com/grafana/grafana/pkg/models"
  9. "golang.org/x/oauth2"
  10. )
  11. type SocialGithub struct {
  12. *SocialBase
  13. allowedDomains []string
  14. allowedOrganizations []string
  15. apiUrl string
  16. allowSignup bool
  17. teamIds []int
  18. }
  19. type GithubTeam struct {
  20. Id int `json:"id"`
  21. Slug string `json:"slug"`
  22. URL string `json:"html_url"`
  23. Organization struct {
  24. Login string `json:"login"`
  25. } `json:"organization"`
  26. }
  27. var (
  28. ErrMissingTeamMembership = &Error{"User not a member of one of the required teams"}
  29. ErrMissingOrganizationMembership = &Error{"User not a member of one of the required organizations"}
  30. )
  31. func (s *SocialGithub) Type() int {
  32. return int(models.GITHUB)
  33. }
  34. func (s *SocialGithub) IsEmailAllowed(email string) bool {
  35. return isEmailAllowed(email, s.allowedDomains)
  36. }
  37. func (s *SocialGithub) IsSignupAllowed() bool {
  38. return s.allowSignup
  39. }
  40. func (s *SocialGithub) IsTeamMember(client *http.Client) bool {
  41. if len(s.teamIds) == 0 {
  42. return true
  43. }
  44. teamMemberships, err := s.FetchTeamMemberships(client)
  45. if err != nil {
  46. return false
  47. }
  48. for _, teamId := range s.teamIds {
  49. for _, membership := range teamMemberships {
  50. if teamId == membership.Id {
  51. return true
  52. }
  53. }
  54. }
  55. return false
  56. }
  57. func (s *SocialGithub) IsOrganizationMember(client *http.Client, organizationsUrl string) bool {
  58. if len(s.allowedOrganizations) == 0 {
  59. return true
  60. }
  61. organizations, err := s.FetchOrganizations(client, organizationsUrl)
  62. if err != nil {
  63. return false
  64. }
  65. for _, allowedOrganization := range s.allowedOrganizations {
  66. for _, organization := range organizations {
  67. if organization == allowedOrganization {
  68. return true
  69. }
  70. }
  71. }
  72. return false
  73. }
  74. func (s *SocialGithub) FetchPrivateEmail(client *http.Client) (string, error) {
  75. type Record struct {
  76. Email string `json:"email"`
  77. Primary bool `json:"primary"`
  78. Verified bool `json:"verified"`
  79. }
  80. response, err := HttpGet(client, fmt.Sprintf(s.apiUrl+"/emails"))
  81. if err != nil {
  82. return "", fmt.Errorf("Error getting email address: %s", err)
  83. }
  84. var records []Record
  85. err = json.Unmarshal(response.Body, &records)
  86. if err != nil {
  87. return "", fmt.Errorf("Error getting email address: %s", err)
  88. }
  89. var email = ""
  90. for _, record := range records {
  91. if record.Primary {
  92. email = record.Email
  93. }
  94. }
  95. return email, nil
  96. }
  97. func (s *SocialGithub) FetchTeamMemberships(client *http.Client) ([]GithubTeam, error) {
  98. url := fmt.Sprintf(s.apiUrl + "/teams?per_page=100")
  99. hasMore := true
  100. teams := make([]GithubTeam, 0)
  101. for hasMore {
  102. response, err := HttpGet(client, url)
  103. if err != nil {
  104. return nil, fmt.Errorf("Error getting team memberships: %s", err)
  105. }
  106. var records []GithubTeam
  107. err = json.Unmarshal(response.Body, &records)
  108. if err != nil {
  109. return nil, fmt.Errorf("Error getting team memberships: %s", err)
  110. }
  111. teams = append(teams, records...)
  112. url, hasMore = s.HasMoreRecords(response.Headers)
  113. }
  114. return teams, nil
  115. }
  116. func (s *SocialGithub) HasMoreRecords(headers http.Header) (string, bool) {
  117. value, exists := headers["Link"]
  118. if !exists {
  119. return "", false
  120. }
  121. pattern := regexp.MustCompile(`<([^>]+)>; rel="next"`)
  122. matches := pattern.FindStringSubmatch(value[0])
  123. if matches == nil {
  124. return "", false
  125. }
  126. url := matches[1]
  127. return url, true
  128. }
  129. func (s *SocialGithub) FetchOrganizations(client *http.Client, organizationsUrl string) ([]string, error) {
  130. type Record struct {
  131. Login string `json:"login"`
  132. }
  133. response, err := HttpGet(client, organizationsUrl)
  134. if err != nil {
  135. return nil, fmt.Errorf("Error getting organizations: %s", err)
  136. }
  137. var records []Record
  138. err = json.Unmarshal(response.Body, &records)
  139. if err != nil {
  140. return nil, fmt.Errorf("Error getting organizations: %s", err)
  141. }
  142. var logins = make([]string, len(records))
  143. for i, record := range records {
  144. logins[i] = record.Login
  145. }
  146. return logins, nil
  147. }
  148. func (s *SocialGithub) UserInfo(client *http.Client, token *oauth2.Token) (*BasicUserInfo, error) {
  149. var data struct {
  150. Id int `json:"id"`
  151. Login string `json:"login"`
  152. Email string `json:"email"`
  153. }
  154. response, err := HttpGet(client, s.apiUrl)
  155. if err != nil {
  156. return nil, fmt.Errorf("Error getting user info: %s", err)
  157. }
  158. err = json.Unmarshal(response.Body, &data)
  159. if err != nil {
  160. return nil, fmt.Errorf("Error getting user info: %s", err)
  161. }
  162. teamMemberships, err := s.FetchTeamMemberships(client)
  163. if err != nil {
  164. return nil, fmt.Errorf("Error getting user teams: %s", err)
  165. }
  166. teams := convertToGroupList(teamMemberships)
  167. userInfo := &BasicUserInfo{
  168. Name: data.Login,
  169. Login: data.Login,
  170. Id: fmt.Sprintf("%d", data.Id),
  171. Email: data.Email,
  172. Groups: teams,
  173. }
  174. organizationsUrl := fmt.Sprintf(s.apiUrl + "/orgs")
  175. if !s.IsTeamMember(client) {
  176. return nil, ErrMissingTeamMembership
  177. }
  178. if !s.IsOrganizationMember(client, organizationsUrl) {
  179. return nil, ErrMissingOrganizationMembership
  180. }
  181. if userInfo.Email == "" {
  182. userInfo.Email, err = s.FetchPrivateEmail(client)
  183. if err != nil {
  184. return nil, err
  185. }
  186. }
  187. return userInfo, nil
  188. }
  189. func (t *GithubTeam) GetShorthand() (string, error) {
  190. if t.Organization.Login == "" || t.Slug == "" {
  191. return "", errors.New("Error getting team shorthand")
  192. }
  193. return fmt.Sprintf("@%s/%s", t.Organization.Login, t.Slug), nil
  194. }
  195. func convertToGroupList(t []GithubTeam) []string {
  196. groups := make([]string, 0)
  197. for _, team := range t {
  198. // Group shouldn't be empty string, otherwise team sync will not work properly
  199. if team.URL != "" {
  200. groups = append(groups, team.URL)
  201. }
  202. teamShorthand, _ := team.GetShorthand()
  203. if teamShorthand != "" {
  204. groups = append(groups, teamShorthand)
  205. }
  206. }
  207. return groups
  208. }