github.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package controller
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "one-api/common"
  9. "one-api/model"
  10. "strconv"
  11. "time"
  12. "github.com/gin-contrib/sessions"
  13. "github.com/gin-gonic/gin"
  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. common.ApiError(c, err)
  101. return
  102. }
  103. user := model.User{
  104. GitHubId: githubUser.Login,
  105. }
  106. // IsGitHubIdAlreadyTaken is unscoped
  107. if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
  108. // FillUserByGitHubId is scoped
  109. err := user.FillUserByGitHubId()
  110. if err != nil {
  111. c.JSON(http.StatusOK, gin.H{
  112. "success": false,
  113. "message": err.Error(),
  114. })
  115. return
  116. }
  117. // if user.Id == 0 , user has been deleted
  118. if user.Id == 0 {
  119. c.JSON(http.StatusOK, gin.H{
  120. "success": false,
  121. "message": "用户已注销",
  122. })
  123. return
  124. }
  125. } else {
  126. if common.RegisterEnabled {
  127. user.Username = "github_" + strconv.Itoa(model.GetMaxUserId()+1)
  128. if githubUser.Name != "" {
  129. user.DisplayName = githubUser.Name
  130. } else {
  131. user.DisplayName = "GitHub User"
  132. }
  133. user.Email = githubUser.Email
  134. user.Role = common.RoleCommonUser
  135. user.Status = common.UserStatusEnabled
  136. affCode := session.Get("aff")
  137. inviterId := 0
  138. if affCode != nil {
  139. inviterId, _ = model.GetUserIdByAffCode(affCode.(string))
  140. }
  141. if err := user.Insert(inviterId); err != nil {
  142. c.JSON(http.StatusOK, gin.H{
  143. "success": false,
  144. "message": err.Error(),
  145. })
  146. return
  147. }
  148. } else {
  149. c.JSON(http.StatusOK, gin.H{
  150. "success": false,
  151. "message": "管理员关闭了新用户注册",
  152. })
  153. return
  154. }
  155. }
  156. if user.Status != common.UserStatusEnabled {
  157. c.JSON(http.StatusOK, gin.H{
  158. "message": "用户已被封禁",
  159. "success": false,
  160. })
  161. return
  162. }
  163. setupLogin(&user, c)
  164. }
  165. func GitHubBind(c *gin.Context) {
  166. if !common.GitHubOAuthEnabled {
  167. c.JSON(http.StatusOK, gin.H{
  168. "success": false,
  169. "message": "管理员未开启通过 GitHub 登录以及注册",
  170. })
  171. return
  172. }
  173. code := c.Query("code")
  174. githubUser, err := getGitHubUserInfoByCode(code)
  175. if err != nil {
  176. common.ApiError(c, err)
  177. return
  178. }
  179. user := model.User{
  180. GitHubId: githubUser.Login,
  181. }
  182. if model.IsGitHubIdAlreadyTaken(user.GitHubId) {
  183. c.JSON(http.StatusOK, gin.H{
  184. "success": false,
  185. "message": "该 GitHub 账户已被绑定",
  186. })
  187. return
  188. }
  189. session := sessions.Default(c)
  190. id := session.Get("id")
  191. // id := c.GetInt("id") // critical bug!
  192. user.Id = id.(int)
  193. err = user.FillUserById()
  194. if err != nil {
  195. common.ApiError(c, err)
  196. return
  197. }
  198. user.GitHubId = githubUser.Login
  199. err = user.Update(false)
  200. if err != nil {
  201. common.ApiError(c, err)
  202. return
  203. }
  204. c.JSON(http.StatusOK, gin.H{
  205. "success": true,
  206. "message": "bind",
  207. })
  208. return
  209. }
  210. func GenerateOAuthCode(c *gin.Context) {
  211. session := sessions.Default(c)
  212. state := common.GetRandomString(12)
  213. affCode := c.Query("aff")
  214. if affCode != "" {
  215. session.Set("aff", affCode)
  216. }
  217. session.Set("oauth_state", state)
  218. err := session.Save()
  219. if err != nil {
  220. common.ApiError(c, err)
  221. return
  222. }
  223. c.JSON(http.StatusOK, gin.H{
  224. "success": true,
  225. "message": "",
  226. "data": state,
  227. })
  228. }