github.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. user.Username = "github_" + strconv.Itoa(model.GetMaxUserId()+1)
  105. user.DisplayName = githubUser.Name
  106. user.Email = githubUser.Email
  107. user.Role = common.RoleCommonUser
  108. user.Status = common.UserStatusEnabled
  109. if err := user.Insert(); err != nil {
  110. c.JSON(http.StatusOK, gin.H{
  111. "success": false,
  112. "message": err.Error(),
  113. })
  114. return
  115. }
  116. }
  117. if user.Status != common.UserStatusEnabled {
  118. c.JSON(http.StatusOK, gin.H{
  119. "message": "用户已被封禁",
  120. "success": false,
  121. })
  122. return
  123. }
  124. setupLogin(&user, c)
  125. }
  126. func GitHubBind(c *gin.Context) {
  127. if !common.GitHubOAuthEnabled {
  128. c.JSON(http.StatusOK, gin.H{
  129. "success": false,
  130. "message": "管理员未开启通过 GitHub 登录以及注册",
  131. })
  132. return
  133. }
  134. code := c.Query("code")
  135. githubUser, err := getGitHubUserInfoByCode(code)
  136. if err != nil {
  137. c.JSON(http.StatusOK, gin.H{
  138. "success": false,
  139. "message": err.Error(),
  140. })
  141. return
  142. }
  143. user := model.User{
  144. GitHubId: githubUser.Login,
  145. }
  146. if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
  147. c.JSON(http.StatusOK, gin.H{
  148. "success": false,
  149. "message": "该 GitHub 账户已被绑定",
  150. })
  151. return
  152. }
  153. id := c.GetInt("id")
  154. user.Id = id
  155. user.FillUserById()
  156. user.GitHubId = githubUser.Login
  157. err = user.Update(false)
  158. if err != nil {
  159. c.JSON(http.StatusOK, gin.H{
  160. "success": false,
  161. "message": err.Error(),
  162. })
  163. return
  164. }
  165. c.JSON(http.StatusOK, gin.H{
  166. "success": true,
  167. "message": "bind",
  168. })
  169. return
  170. }