github.go 5.7 KB

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