auth.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package middleware
  2. import (
  3. "fmt"
  4. "net"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/constant"
  10. "github.com/QuantumNous/new-api/logger"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/service"
  13. "github.com/QuantumNous/new-api/setting/ratio_setting"
  14. "github.com/QuantumNous/new-api/types"
  15. "github.com/gin-contrib/sessions"
  16. "github.com/gin-gonic/gin"
  17. )
  18. func validUserInfo(username string, role int) bool {
  19. // check username is empty
  20. if strings.TrimSpace(username) == "" {
  21. return false
  22. }
  23. if !common.IsValidateRole(role) {
  24. return false
  25. }
  26. return true
  27. }
  28. func authHelper(c *gin.Context, minRole int) {
  29. session := sessions.Default(c)
  30. username := session.Get("username")
  31. role := session.Get("role")
  32. id := session.Get("id")
  33. status := session.Get("status")
  34. useAccessToken := false
  35. if username == nil {
  36. // Check access token
  37. accessToken := c.Request.Header.Get("Authorization")
  38. if accessToken == "" {
  39. c.JSON(http.StatusUnauthorized, gin.H{
  40. "success": false,
  41. "message": "无权进行此操作,未登录且未提供 access token",
  42. })
  43. c.Abort()
  44. return
  45. }
  46. user := model.ValidateAccessToken(accessToken)
  47. if user != nil && user.Username != "" {
  48. if !validUserInfo(user.Username, user.Role) {
  49. c.JSON(http.StatusOK, gin.H{
  50. "success": false,
  51. "message": "无权进行此操作,用户信息无效",
  52. })
  53. c.Abort()
  54. return
  55. }
  56. // Token is valid
  57. username = user.Username
  58. role = user.Role
  59. id = user.Id
  60. status = user.Status
  61. useAccessToken = true
  62. } else {
  63. c.JSON(http.StatusOK, gin.H{
  64. "success": false,
  65. "message": "无权进行此操作,access token 无效",
  66. })
  67. c.Abort()
  68. return
  69. }
  70. }
  71. // get header New-Api-User
  72. apiUserIdStr := c.Request.Header.Get("New-Api-User")
  73. if apiUserIdStr == "" {
  74. c.JSON(http.StatusUnauthorized, gin.H{
  75. "success": false,
  76. "message": "无权进行此操作,未提供 New-Api-User",
  77. })
  78. c.Abort()
  79. return
  80. }
  81. apiUserId, err := strconv.Atoi(apiUserIdStr)
  82. if err != nil {
  83. c.JSON(http.StatusUnauthorized, gin.H{
  84. "success": false,
  85. "message": "无权进行此操作,New-Api-User 格式错误",
  86. })
  87. c.Abort()
  88. return
  89. }
  90. if id != apiUserId {
  91. c.JSON(http.StatusUnauthorized, gin.H{
  92. "success": false,
  93. "message": "无权进行此操作,New-Api-User 与登录用户不匹配",
  94. })
  95. c.Abort()
  96. return
  97. }
  98. if status.(int) == common.UserStatusDisabled {
  99. c.JSON(http.StatusOK, gin.H{
  100. "success": false,
  101. "message": "用户已被封禁",
  102. })
  103. c.Abort()
  104. return
  105. }
  106. if role.(int) < minRole {
  107. c.JSON(http.StatusOK, gin.H{
  108. "success": false,
  109. "message": "无权进行此操作,权限不足",
  110. })
  111. c.Abort()
  112. return
  113. }
  114. if !validUserInfo(username.(string), role.(int)) {
  115. c.JSON(http.StatusOK, gin.H{
  116. "success": false,
  117. "message": "无权进行此操作,用户信息无效",
  118. })
  119. c.Abort()
  120. return
  121. }
  122. c.Set("username", username)
  123. c.Set("role", role)
  124. c.Set("id", id)
  125. c.Set("group", session.Get("group"))
  126. c.Set("user_group", session.Get("group"))
  127. c.Set("use_access_token", useAccessToken)
  128. c.Next()
  129. }
  130. func TryUserAuth() func(c *gin.Context) {
  131. return func(c *gin.Context) {
  132. session := sessions.Default(c)
  133. id := session.Get("id")
  134. if id != nil {
  135. c.Set("id", id)
  136. }
  137. c.Next()
  138. }
  139. }
  140. func UserAuth() func(c *gin.Context) {
  141. return func(c *gin.Context) {
  142. authHelper(c, common.RoleCommonUser)
  143. }
  144. }
  145. func AdminAuth() func(c *gin.Context) {
  146. return func(c *gin.Context) {
  147. authHelper(c, common.RoleAdminUser)
  148. }
  149. }
  150. func RootAuth() func(c *gin.Context) {
  151. return func(c *gin.Context) {
  152. authHelper(c, common.RoleRootUser)
  153. }
  154. }
  155. func WssAuth(c *gin.Context) {
  156. }
  157. func TokenAuth() func(c *gin.Context) {
  158. return func(c *gin.Context) {
  159. // 先检测是否为ws
  160. if c.Request.Header.Get("Sec-WebSocket-Protocol") != "" {
  161. // Sec-WebSocket-Protocol: realtime, openai-insecure-api-key.sk-xxx, openai-beta.realtime-v1
  162. // read sk from Sec-WebSocket-Protocol
  163. key := c.Request.Header.Get("Sec-WebSocket-Protocol")
  164. parts := strings.Split(key, ",")
  165. for _, part := range parts {
  166. part = strings.TrimSpace(part)
  167. if strings.HasPrefix(part, "openai-insecure-api-key") {
  168. key = strings.TrimPrefix(part, "openai-insecure-api-key.")
  169. break
  170. }
  171. }
  172. c.Request.Header.Set("Authorization", "Bearer "+key)
  173. }
  174. // 检查path包含/v1/messages 或 /v1/models
  175. if strings.Contains(c.Request.URL.Path, "/v1/messages") || strings.Contains(c.Request.URL.Path, "/v1/models") {
  176. anthropicKey := c.Request.Header.Get("x-api-key")
  177. if anthropicKey != "" {
  178. c.Request.Header.Set("Authorization", "Bearer "+anthropicKey)
  179. }
  180. }
  181. // gemini api 从query中获取key
  182. if strings.HasPrefix(c.Request.URL.Path, "/v1beta/models") ||
  183. strings.HasPrefix(c.Request.URL.Path, "/v1beta/openai/models") ||
  184. strings.HasPrefix(c.Request.URL.Path, "/v1/models/") {
  185. skKey := c.Query("key")
  186. if skKey != "" {
  187. c.Request.Header.Set("Authorization", "Bearer "+skKey)
  188. }
  189. // 从x-goog-api-key header中获取key
  190. xGoogKey := c.Request.Header.Get("x-goog-api-key")
  191. if xGoogKey != "" {
  192. c.Request.Header.Set("Authorization", "Bearer "+xGoogKey)
  193. }
  194. }
  195. key := c.Request.Header.Get("Authorization")
  196. parts := make([]string, 0)
  197. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  198. key = strings.TrimSpace(key[7:])
  199. }
  200. if key == "" || key == "midjourney-proxy" {
  201. key = c.Request.Header.Get("mj-api-secret")
  202. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  203. key = strings.TrimSpace(key[7:])
  204. }
  205. key = strings.TrimPrefix(key, "sk-")
  206. parts = strings.Split(key, "-")
  207. key = parts[0]
  208. } else {
  209. key = strings.TrimPrefix(key, "sk-")
  210. parts = strings.Split(key, "-")
  211. key = parts[0]
  212. }
  213. token, err := model.ValidateUserToken(key)
  214. if token != nil {
  215. id := c.GetInt("id")
  216. if id == 0 {
  217. c.Set("id", token.UserId)
  218. }
  219. }
  220. if err != nil {
  221. abortWithOpenAiMessage(c, http.StatusUnauthorized, err.Error())
  222. return
  223. }
  224. allowIps := token.GetIpLimits()
  225. if len(allowIps) > 0 {
  226. clientIp := c.ClientIP()
  227. logger.LogDebug(c, "Token has IP restrictions, checking client IP %s", clientIp)
  228. ip := net.ParseIP(clientIp)
  229. if ip == nil {
  230. abortWithOpenAiMessage(c, http.StatusForbidden, "无法解析客户端 IP 地址")
  231. return
  232. }
  233. if common.IsIpInCIDRList(ip, allowIps) == false {
  234. abortWithOpenAiMessage(c, http.StatusForbidden, "您的 IP 不在令牌允许访问的列表中", types.ErrorCodeAccessDenied)
  235. return
  236. }
  237. logger.LogDebug(c, "Client IP %s passed the token IP restrictions check", clientIp)
  238. }
  239. userCache, err := model.GetUserCache(token.UserId)
  240. if err != nil {
  241. abortWithOpenAiMessage(c, http.StatusInternalServerError, err.Error())
  242. return
  243. }
  244. userEnabled := userCache.Status == common.UserStatusEnabled
  245. if !userEnabled {
  246. abortWithOpenAiMessage(c, http.StatusForbidden, "用户已被封禁")
  247. return
  248. }
  249. userCache.WriteContext(c)
  250. userGroup := userCache.Group
  251. tokenGroup := token.Group
  252. if tokenGroup != "" {
  253. // check common.UserUsableGroups[userGroup]
  254. if _, ok := service.GetUserUsableGroups(userGroup)[tokenGroup]; !ok {
  255. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("无权访问 %s 分组", tokenGroup))
  256. return
  257. }
  258. // check group in common.GroupRatio
  259. if !ratio_setting.ContainsGroupRatio(tokenGroup) {
  260. if tokenGroup != "auto" {
  261. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("分组 %s 已被弃用", tokenGroup))
  262. return
  263. }
  264. }
  265. userGroup = tokenGroup
  266. }
  267. common.SetContextKey(c, constant.ContextKeyUsingGroup, userGroup)
  268. err = SetupContextForToken(c, token, parts...)
  269. if err != nil {
  270. return
  271. }
  272. c.Next()
  273. }
  274. }
  275. func SetupContextForToken(c *gin.Context, token *model.Token, parts ...string) error {
  276. if token == nil {
  277. return fmt.Errorf("token is nil")
  278. }
  279. c.Set("id", token.UserId)
  280. c.Set("token_id", token.Id)
  281. c.Set("token_key", token.Key)
  282. c.Set("token_name", token.Name)
  283. c.Set("token_unlimited_quota", token.UnlimitedQuota)
  284. if !token.UnlimitedQuota {
  285. c.Set("token_quota", token.RemainQuota)
  286. }
  287. if token.ModelLimitsEnabled {
  288. c.Set("token_model_limit_enabled", true)
  289. c.Set("token_model_limit", token.GetModelLimitsMap())
  290. } else {
  291. c.Set("token_model_limit_enabled", false)
  292. }
  293. common.SetContextKey(c, constant.ContextKeyTokenGroup, token.Group)
  294. common.SetContextKey(c, constant.ContextKeyTokenCrossGroupRetry, token.CrossGroupRetry)
  295. if len(parts) > 1 {
  296. if model.IsAdmin(token.UserId) {
  297. c.Set("specific_channel_id", parts[1])
  298. } else {
  299. abortWithOpenAiMessage(c, http.StatusForbidden, "普通用户不支持指定渠道")
  300. return fmt.Errorf("普通用户不支持指定渠道")
  301. }
  302. }
  303. return nil
  304. }