social_github.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package user
  5. import (
  6. "encoding/json"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "code.google.com/p/goauth2/oauth"
  12. "github.com/gogits/gogs/models"
  13. "github.com/gogits/gogs/modules/base"
  14. )
  15. type SocialGithub struct {
  16. Token *oauth.Token
  17. *oauth.Transport
  18. }
  19. func (s *SocialGithub) Type() int {
  20. return models.OT_GITHUB
  21. }
  22. func init() {
  23. github := &SocialGithub{}
  24. name := "github"
  25. config := &oauth.Config{
  26. ClientId: "09383403ff2dc16daaa1", //base.OauthService.GitHub.ClientId, // FIXME: panic when set
  27. ClientSecret: "0e4aa0c3630df396cdcea01a9d45cacf79925fea", //base.OauthService.GitHub.ClientSecret,
  28. RedirectURL: strings.TrimSuffix(base.AppUrl, "/") + "/user/login/" + name, //ctx.Req.URL.RequestURI(),
  29. Scope: "https://api.github.com/user",
  30. AuthURL: "https://github.com/login/oauth/authorize",
  31. TokenURL: "https://github.com/login/oauth/access_token",
  32. }
  33. github.Transport = &oauth.Transport{
  34. Config: config,
  35. Transport: http.DefaultTransport,
  36. }
  37. SocialMap[name] = github
  38. }
  39. func (s *SocialGithub) SetRedirectUrl(url string) {
  40. s.Transport.Config.RedirectURL = url
  41. }
  42. func (s *SocialGithub) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo, error) {
  43. transport := &oauth.Transport{
  44. Token: token,
  45. }
  46. var data struct {
  47. Id int `json:"id"`
  48. Name string `json:"login"`
  49. Email string `json:"email"`
  50. }
  51. var err error
  52. r, err := transport.Client().Get(s.Transport.Scope)
  53. if err != nil {
  54. return nil, err
  55. }
  56. defer r.Body.Close()
  57. if err = json.NewDecoder(r.Body).Decode(&data); err != nil {
  58. return nil, err
  59. }
  60. return &BasicUserInfo{
  61. Identity: strconv.Itoa(data.Id),
  62. Name: data.Name,
  63. Email: data.Email,
  64. }, nil
  65. }