github.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. "net/http"
  10. "one-api/common"
  11. "one-api/model"
  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. state := c.Query("state")
  78. if state == "" || session.Get("oauth_state") == nil || state != session.Get("oauth_state").(string) {
  79. c.JSON(http.StatusForbidden, gin.H{
  80. "success": false,
  81. "message": "state is empty or not same",
  82. })
  83. return
  84. }
  85. username := session.Get("username")
  86. if username != nil {
  87. GitHubBind(c)
  88. return
  89. }
  90. if !common.GitHubOAuthEnabled {
  91. c.JSON(http.StatusOK, gin.H{
  92. "success": false,
  93. "message": "管理员未开启通过 GitHub 登录以及注册",
  94. })
  95. return
  96. }
  97. code := c.Query("code")
  98. githubUser, err := getGitHubUserInfoByCode(code)
  99. if err != nil {
  100. c.JSON(http.StatusOK, gin.H{
  101. "success": false,
  102. "message": err.Error(),
  103. })
  104. return
  105. }
  106. user := model.User{
  107. GitHubId: githubUser.Login,
  108. }
  109. if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
  110. err := user.FillUserByGitHubId()
  111. if err != nil {
  112. c.JSON(http.StatusOK, gin.H{
  113. "success": false,
  114. "message": err.Error(),
  115. })
  116. return
  117. }
  118. } else {
  119. if common.RegisterEnabled {
  120. user.Username = "github_" + strconv.Itoa(model.GetMaxUserId()+1)
  121. if githubUser.Name != "" {
  122. user.DisplayName = githubUser.Name
  123. } else {
  124. user.DisplayName = "GitHub User"
  125. }
  126. user.Email = githubUser.Email
  127. user.Role = common.RoleCommonUser
  128. user.Status = common.UserStatusEnabled
  129. if err := user.Insert(0); err != nil {
  130. c.JSON(http.StatusOK, gin.H{
  131. "success": false,
  132. "message": err.Error(),
  133. })
  134. return
  135. }
  136. } else {
  137. c.JSON(http.StatusOK, gin.H{
  138. "success": false,
  139. "message": "管理员关闭了新用户注册",
  140. })
  141. return
  142. }
  143. }
  144. if user.Status != common.UserStatusEnabled {
  145. c.JSON(http.StatusOK, gin.H{
  146. "message": "用户已被封禁",
  147. "success": false,
  148. })
  149. return
  150. }
  151. setupLogin(&user, c)
  152. }
  153. func GitHubBind(c *gin.Context) {
  154. if !common.GitHubOAuthEnabled {
  155. c.JSON(http.StatusOK, gin.H{
  156. "success": false,
  157. "message": "管理员未开启通过 GitHub 登录以及注册",
  158. })
  159. return
  160. }
  161. code := c.Query("code")
  162. githubUser, err := getGitHubUserInfoByCode(code)
  163. if err != nil {
  164. c.JSON(http.StatusOK, gin.H{
  165. "success": false,
  166. "message": err.Error(),
  167. })
  168. return
  169. }
  170. user := model.User{
  171. GitHubId: githubUser.Login,
  172. }
  173. if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
  174. c.JSON(http.StatusOK, gin.H{
  175. "success": false,
  176. "message": "该 GitHub 账户已被绑定",
  177. })
  178. return
  179. }
  180. session := sessions.Default(c)
  181. id := session.Get("id")
  182. // id := c.GetInt("id") // critical bug!
  183. user.Id = id.(int)
  184. err = user.FillUserById()
  185. if err != nil {
  186. c.JSON(http.StatusOK, gin.H{
  187. "success": false,
  188. "message": err.Error(),
  189. })
  190. return
  191. }
  192. user.GitHubId = githubUser.Login
  193. err = user.Update(false)
  194. if err != nil {
  195. c.JSON(http.StatusOK, gin.H{
  196. "success": false,
  197. "message": err.Error(),
  198. })
  199. return
  200. }
  201. c.JSON(http.StatusOK, gin.H{
  202. "success": true,
  203. "message": "bind",
  204. })
  205. return
  206. }
  207. func GenerateOAuthCode(c *gin.Context) {
  208. session := sessions.Default(c)
  209. state := common.GetRandomString(12)
  210. session.Set("oauth_state", state)
  211. err := session.Save()
  212. if err != nil {
  213. c.JSON(http.StatusOK, gin.H{
  214. "success": false,
  215. "message": err.Error(),
  216. })
  217. return
  218. }
  219. c.JSON(http.StatusOK, gin.H{
  220. "success": true,
  221. "message": "",
  222. "data": state,
  223. })
  224. }