social.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. "errors"
  8. "fmt"
  9. // "strings"
  10. "time"
  11. "github.com/macaron-contrib/oauth2"
  12. "github.com/gogits/gogs/models"
  13. "github.com/gogits/gogs/modules/log"
  14. "github.com/gogits/gogs/modules/middleware"
  15. "github.com/gogits/gogs/modules/setting"
  16. "github.com/gogits/gogs/modules/social"
  17. )
  18. func SocialSignIn(ctx *middleware.Context) {
  19. if setting.OauthService == nil {
  20. ctx.Handle(404, "OAuth2 service not enabled", nil)
  21. return
  22. }
  23. next := setting.AppSubUrl + "/user/login"
  24. info := ctx.Session.Get(oauth2.KEY_TOKEN)
  25. if info == nil {
  26. ctx.Redirect(next)
  27. return
  28. }
  29. name := ctx.Params(":name")
  30. connect, ok := social.SocialMap[name]
  31. if !ok {
  32. ctx.Handle(404, "social login not enabled", errors.New(name))
  33. return
  34. }
  35. tk := new(oauth2.Token)
  36. if err := json.Unmarshal(info.([]byte), tk); err != nil {
  37. ctx.Handle(500, "Unmarshal token", err)
  38. return
  39. }
  40. ui, err := connect.UserInfo(tk, ctx.Req.URL)
  41. if err != nil {
  42. ctx.Handle(500, fmt.Sprintf("UserInfo(%s)", name), err)
  43. return
  44. }
  45. log.Info("social.SocialSignIn(social login): %s", ui)
  46. oa, err := models.GetOauth2(ui.Identity)
  47. switch err {
  48. case nil:
  49. ctx.Session.Set("uid", oa.User.Id)
  50. ctx.Session.Set("uname", oa.User.Name)
  51. case models.ErrOauth2RecordNotExist:
  52. raw, _ := json.Marshal(tk)
  53. oa = &models.Oauth2{
  54. Uid: -1,
  55. Type: connect.Type(),
  56. Identity: ui.Identity,
  57. Token: string(raw),
  58. }
  59. log.Trace("social.SocialSignIn(oa): %v", oa)
  60. if err = models.AddOauth2(oa); err != nil {
  61. log.Error(4, "social.SocialSignIn(add oauth2): %v", err) // 501
  62. return
  63. }
  64. case models.ErrOauth2NotAssociated:
  65. next = setting.AppSubUrl + "/user/sign_up"
  66. default:
  67. ctx.Handle(500, "social.SocialSignIn(GetOauth2)", err)
  68. return
  69. }
  70. oa.Updated = time.Now()
  71. if err = models.UpdateOauth2(oa); err != nil {
  72. log.Error(4, "UpdateOauth2: %v", err)
  73. }
  74. ctx.Session.Set("socialId", oa.Id)
  75. ctx.Session.Set("socialName", ui.Name)
  76. ctx.Session.Set("socialEmail", ui.Email)
  77. log.Trace("social.SocialSignIn(social ID): %v", oa.Id)
  78. ctx.Redirect(next)
  79. }