auth.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package middleware
  2. import (
  3. "github.com/gin-contrib/sessions"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/model"
  8. "strconv"
  9. "strings"
  10. )
  11. func validUserInfo(username string, role int) bool {
  12. // check username is empty
  13. if strings.TrimSpace(username) == "" {
  14. return false
  15. }
  16. if !common.IsValidateRole(role) {
  17. return false
  18. }
  19. return true
  20. }
  21. func authHelper(c *gin.Context, minRole int) {
  22. session := sessions.Default(c)
  23. username := session.Get("username")
  24. role := session.Get("role")
  25. id := session.Get("id")
  26. status := session.Get("status")
  27. useAccessToken := false
  28. if username == nil {
  29. // Check access token
  30. accessToken := c.Request.Header.Get("Authorization")
  31. if accessToken == "" {
  32. c.JSON(http.StatusUnauthorized, gin.H{
  33. "success": false,
  34. "message": "无权进行此操作,未登录且未提供 access token",
  35. })
  36. c.Abort()
  37. return
  38. }
  39. user := model.ValidateAccessToken(accessToken)
  40. if user != nil && user.Username != "" {
  41. if !validUserInfo(user.Username, user.Role) {
  42. c.JSON(http.StatusOK, gin.H{
  43. "success": false,
  44. "message": "无权进行此操作,用户信息无效",
  45. })
  46. c.Abort()
  47. return
  48. }
  49. // Token is valid
  50. username = user.Username
  51. role = user.Role
  52. id = user.Id
  53. status = user.Status
  54. useAccessToken = true
  55. } else {
  56. c.JSON(http.StatusOK, gin.H{
  57. "success": false,
  58. "message": "无权进行此操作,access token 无效",
  59. })
  60. c.Abort()
  61. return
  62. }
  63. }
  64. if !useAccessToken {
  65. // get header New-Api-User
  66. apiUserIdStr := c.Request.Header.Get("New-Api-User")
  67. if apiUserIdStr == "" {
  68. c.JSON(http.StatusUnauthorized, gin.H{
  69. "success": false,
  70. "message": "无权进行此操作,请刷新页面或清空缓存后重试",
  71. })
  72. c.Abort()
  73. return
  74. }
  75. apiUserId, err := strconv.Atoi(apiUserIdStr)
  76. if err != nil {
  77. c.JSON(http.StatusUnauthorized, gin.H{
  78. "success": false,
  79. "message": "无权进行此操作,登录信息无效,请重新登录",
  80. })
  81. c.Abort()
  82. return
  83. }
  84. if id != apiUserId {
  85. c.JSON(http.StatusUnauthorized, gin.H{
  86. "success": false,
  87. "message": "无权进行此操作,与登录用户不匹配,请重新登录",
  88. })
  89. c.Abort()
  90. return
  91. }
  92. }
  93. if status.(int) == common.UserStatusDisabled {
  94. c.JSON(http.StatusOK, gin.H{
  95. "success": false,
  96. "message": "用户已被封禁",
  97. })
  98. c.Abort()
  99. return
  100. }
  101. if role.(int) < minRole {
  102. c.JSON(http.StatusOK, gin.H{
  103. "success": false,
  104. "message": "无权进行此操作,权限不足",
  105. })
  106. c.Abort()
  107. return
  108. }
  109. if !validUserInfo(username.(string), role.(int)) {
  110. c.JSON(http.StatusOK, gin.H{
  111. "success": false,
  112. "message": "无权进行此操作,用户信息无效",
  113. })
  114. c.Abort()
  115. return
  116. }
  117. c.Set("username", username)
  118. c.Set("role", role)
  119. c.Set("id", id)
  120. c.Next()
  121. }
  122. func TryUserAuth() func(c *gin.Context) {
  123. return func(c *gin.Context) {
  124. session := sessions.Default(c)
  125. id := session.Get("id")
  126. if id != nil {
  127. c.Set("id", id)
  128. }
  129. c.Next()
  130. }
  131. }
  132. func UserAuth() func(c *gin.Context) {
  133. return func(c *gin.Context) {
  134. authHelper(c, common.RoleCommonUser)
  135. }
  136. }
  137. func AdminAuth() func(c *gin.Context) {
  138. return func(c *gin.Context) {
  139. authHelper(c, common.RoleAdminUser)
  140. }
  141. }
  142. func RootAuth() func(c *gin.Context) {
  143. return func(c *gin.Context) {
  144. authHelper(c, common.RoleRootUser)
  145. }
  146. }
  147. func TokenAuth() func(c *gin.Context) {
  148. return func(c *gin.Context) {
  149. key := c.Request.Header.Get("Authorization")
  150. parts := make([]string, 0)
  151. key = strings.TrimPrefix(key, "Bearer ")
  152. if key == "" || key == "midjourney-proxy" {
  153. key = c.Request.Header.Get("mj-api-secret")
  154. key = strings.TrimPrefix(key, "Bearer ")
  155. key = strings.TrimPrefix(key, "sk-")
  156. parts = strings.Split(key, "-")
  157. key = parts[0]
  158. } else {
  159. key = strings.TrimPrefix(key, "sk-")
  160. parts = strings.Split(key, "-")
  161. key = parts[0]
  162. }
  163. token, err := model.ValidateUserToken(key)
  164. if token != nil {
  165. id := c.GetInt("id")
  166. if id == 0 {
  167. c.Set("id", token.UserId)
  168. }
  169. }
  170. if err != nil {
  171. abortWithOpenAiMessage(c, http.StatusUnauthorized, err.Error())
  172. return
  173. }
  174. userEnabled, err := model.CacheIsUserEnabled(token.UserId)
  175. if err != nil {
  176. abortWithOpenAiMessage(c, http.StatusInternalServerError, err.Error())
  177. return
  178. }
  179. if !userEnabled {
  180. abortWithOpenAiMessage(c, http.StatusForbidden, "用户已被封禁")
  181. return
  182. }
  183. c.Set("id", token.UserId)
  184. c.Set("token_id", token.Id)
  185. c.Set("token_name", token.Name)
  186. c.Set("token_unlimited_quota", token.UnlimitedQuota)
  187. if !token.UnlimitedQuota {
  188. c.Set("token_quota", token.RemainQuota)
  189. }
  190. if token.ModelLimitsEnabled {
  191. c.Set("token_model_limit_enabled", true)
  192. c.Set("token_model_limit", token.GetModelLimitsMap())
  193. } else {
  194. c.Set("token_model_limit_enabled", false)
  195. }
  196. c.Set("allow_ips", token.GetIpLimitsMap())
  197. c.Set("token_group", token.Group)
  198. if len(parts) > 1 {
  199. if model.IsAdmin(token.UserId) {
  200. c.Set("specific_channel_id", parts[1])
  201. } else {
  202. abortWithOpenAiMessage(c, http.StatusForbidden, "普通用户不支持指定渠道")
  203. return
  204. }
  205. }
  206. c.Next()
  207. }
  208. }