github.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package controller
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/gin-contrib/sessions"
  8. "github.com/gin-gonic/gin"
  9. "message-pusher/common"
  10. "message-pusher/model"
  11. "net/http"
  12. "strconv"
  13. "time"
  14. )
  15. type GitHubOAuthResponse struct {
  16. AccessToken string `json:"access_token"`
  17. Scope string `json:"scope"`
  18. TokenType string `json:"token_type"`
  19. }
  20. type GitHubUser struct {
  21. Login string `json:"login"`
  22. Name string `json:"name"`
  23. Email string `json:"email"`
  24. }
  25. func getGitHubUserInfoByCode(code string) (*GitHubUser, error) {
  26. if code == "" {
  27. return nil, errors.New("无效的参数")
  28. }
  29. values := map[string]string{"client_id": common.GitHubClientId, "client_secret": common.GitHubClientSecret, "code": code}
  30. jsonData, err := json.Marshal(values)
  31. if err != nil {
  32. return nil, err
  33. }
  34. req, err := http.NewRequest("POST", "https://github.com/login/oauth/access_token", bytes.NewBuffer(jsonData))
  35. if err != nil {
  36. return nil, err
  37. }
  38. req.Header.Set("Content-Type", "application/json")
  39. req.Header.Set("Accept", "application/json")
  40. client := http.Client{
  41. Timeout: 5 * time.Second,
  42. }
  43. res, err := client.Do(req)
  44. if err != nil {
  45. common.SysLog(err.Error())
  46. return nil, errors.New("无法连接至 GitHub 服务器,请稍后重试!")
  47. }
  48. defer res.Body.Close()
  49. var oAuthResponse GitHubOAuthResponse
  50. err = json.NewDecoder(res.Body).Decode(&oAuthResponse)
  51. if err != nil {
  52. return nil, err
  53. }
  54. req, err = http.NewRequest("GET", "https://api.github.com/user", nil)
  55. if err != nil {
  56. return nil, err
  57. }
  58. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", oAuthResponse.AccessToken))
  59. res2, err := client.Do(req)
  60. if err != nil {
  61. common.SysLog(err.Error())
  62. return nil, errors.New("无法连接至 GitHub 服务器,请稍后重试!")
  63. }
  64. defer res2.Body.Close()
  65. var githubUser GitHubUser
  66. err = json.NewDecoder(res2.Body).Decode(&githubUser)
  67. if err != nil {
  68. return nil, err
  69. }
  70. if githubUser.Login == "" {
  71. return nil, errors.New("返回值非法,用户字段为空,请稍后重试!")
  72. }
  73. return &githubUser, nil
  74. }
  75. func GitHubOAuth(c *gin.Context) {
  76. session := sessions.Default(c)
  77. username := session.Get("username")
  78. if username != nil {
  79. GitHubBind(c)
  80. return
  81. }
  82. if !common.GitHubOAuthEnabled {
  83. c.JSON(http.StatusOK, gin.H{
  84. "success": false,
  85. "message": "管理员未开启通过 GitHub 登录以及注册",
  86. })
  87. return
  88. }
  89. code := c.Query("code")
  90. githubUser, err := getGitHubUserInfoByCode(code)
  91. if err != nil {
  92. c.JSON(http.StatusOK, gin.H{
  93. "success": false,
  94. "message": err.Error(),
  95. })
  96. return
  97. }
  98. user := model.User{
  99. GitHubId: githubUser.Login,
  100. }
  101. if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
  102. user.FillUserByGitHubId()
  103. } else {
  104. if common.RegisterEnabled {
  105. user.Username = "github_" + strconv.Itoa(model.GetMaxUserId()+1)
  106. user.DisplayName = githubUser.Name
  107. user.Email = githubUser.Email
  108. user.Role = common.RoleCommonUser
  109. user.Status = common.UserStatusEnabled
  110. if err := user.Insert(); err != nil {
  111. c.JSON(http.StatusOK, gin.H{
  112. "success": false,
  113. "message": err.Error(),
  114. })
  115. return
  116. }
  117. } else {
  118. c.JSON(http.StatusOK, gin.H{
  119. "success": false,
  120. "message": "管理员关闭了新用户注册",
  121. })
  122. return
  123. }
  124. }
  125. if user.Status != common.UserStatusEnabled {
  126. c.JSON(http.StatusOK, gin.H{
  127. "message": "用户已被封禁",
  128. "success": false,
  129. })
  130. return
  131. }
  132. setupLogin(&user, c)
  133. }
  134. func GitHubBind(c *gin.Context) {
  135. if !common.GitHubOAuthEnabled {
  136. c.JSON(http.StatusOK, gin.H{
  137. "success": false,
  138. "message": "管理员未开启通过 GitHub 登录以及注册",
  139. })
  140. return
  141. }
  142. code := c.Query("code")
  143. githubUser, err := getGitHubUserInfoByCode(code)
  144. if err != nil {
  145. c.JSON(http.StatusOK, gin.H{
  146. "success": false,
  147. "message": err.Error(),
  148. })
  149. return
  150. }
  151. user := model.User{
  152. GitHubId: githubUser.Login,
  153. }
  154. if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
  155. c.JSON(http.StatusOK, gin.H{
  156. "success": false,
  157. "message": "该 GitHub 账户已被绑定",
  158. })
  159. return
  160. }
  161. session := sessions.Default(c)
  162. id := session.Get("id")
  163. // id := c.GetInt("id") // critical bug!
  164. user.Id = id.(int)
  165. user.FillUserById()
  166. user.GitHubId = githubUser.Login
  167. err = user.Update(false)
  168. if err != nil {
  169. c.JSON(http.StatusOK, gin.H{
  170. "success": false,
  171. "message": err.Error(),
  172. })
  173. return
  174. }
  175. c.JSON(http.StatusOK, gin.H{
  176. "success": true,
  177. "message": "bind",
  178. })
  179. return
  180. }