auth.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. //userCache, err := model.GetUserCache(id.(int))
  129. //if err != nil {
  130. // c.JSON(http.StatusOK, gin.H{
  131. // "success": false,
  132. // "message": err.Error(),
  133. // })
  134. // c.Abort()
  135. // return
  136. //}
  137. //userCache.WriteContext(c)
  138. c.Next()
  139. }
  140. func TryUserAuth() func(c *gin.Context) {
  141. return func(c *gin.Context) {
  142. session := sessions.Default(c)
  143. id := session.Get("id")
  144. if id != nil {
  145. c.Set("id", id)
  146. }
  147. c.Next()
  148. }
  149. }
  150. func UserAuth() func(c *gin.Context) {
  151. return func(c *gin.Context) {
  152. authHelper(c, common.RoleCommonUser)
  153. }
  154. }
  155. func AdminAuth() func(c *gin.Context) {
  156. return func(c *gin.Context) {
  157. authHelper(c, common.RoleAdminUser)
  158. }
  159. }
  160. func RootAuth() func(c *gin.Context) {
  161. return func(c *gin.Context) {
  162. authHelper(c, common.RoleRootUser)
  163. }
  164. }
  165. func WssAuth(c *gin.Context) {
  166. }
  167. func TokenAuth() func(c *gin.Context) {
  168. return func(c *gin.Context) {
  169. // 先检测是否为ws
  170. if c.Request.Header.Get("Sec-WebSocket-Protocol") != "" {
  171. // Sec-WebSocket-Protocol: realtime, openai-insecure-api-key.sk-xxx, openai-beta.realtime-v1
  172. // read sk from Sec-WebSocket-Protocol
  173. key := c.Request.Header.Get("Sec-WebSocket-Protocol")
  174. parts := strings.Split(key, ",")
  175. for _, part := range parts {
  176. part = strings.TrimSpace(part)
  177. if strings.HasPrefix(part, "openai-insecure-api-key") {
  178. key = strings.TrimPrefix(part, "openai-insecure-api-key.")
  179. break
  180. }
  181. }
  182. c.Request.Header.Set("Authorization", "Bearer "+key)
  183. }
  184. // 检查path是 /v1/messages (Claude API)
  185. if strings.HasPrefix(c.Request.URL.Path, "/v1/messages") {
  186. anthropicKey := c.Request.Header.Get("x-api-key")
  187. if anthropicKey != "" {
  188. c.Request.Header.Set("Authorization", "Bearer "+anthropicKey)
  189. }
  190. }
  191. // gemini api 从query中获取key
  192. if strings.HasPrefix(c.Request.URL.Path, "/v1beta/models") ||
  193. strings.HasPrefix(c.Request.URL.Path, "/v1beta/files") ||
  194. strings.HasPrefix(c.Request.URL.Path, "/upload/v1beta/files") ||
  195. strings.HasPrefix(c.Request.URL.Path, "/v1beta/openai/models") ||
  196. strings.HasPrefix(c.Request.URL.Path, "/v1/models") {
  197. skKey := c.Query("key")
  198. if skKey != "" {
  199. c.Request.Header.Set("Authorization", "Bearer "+skKey)
  200. }
  201. // 从x-goog-api-key header中获取key
  202. xGoogKey := c.Request.Header.Get("x-goog-api-key")
  203. if xGoogKey != "" {
  204. c.Request.Header.Set("Authorization", "Bearer "+xGoogKey)
  205. }
  206. }
  207. key := c.Request.Header.Get("Authorization")
  208. parts := make([]string, 0)
  209. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  210. key = strings.TrimSpace(key[7:])
  211. }
  212. if key == "" || key == "midjourney-proxy" {
  213. key = c.Request.Header.Get("mj-api-secret")
  214. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  215. key = strings.TrimSpace(key[7:])
  216. }
  217. key = strings.TrimPrefix(key, "sk-")
  218. parts = strings.Split(key, "-")
  219. key = parts[0]
  220. } else {
  221. key = strings.TrimPrefix(key, "sk-")
  222. parts = strings.Split(key, "-")
  223. key = parts[0]
  224. }
  225. token, err := model.ValidateUserToken(key)
  226. if token != nil {
  227. id := c.GetInt("id")
  228. if id == 0 {
  229. c.Set("id", token.UserId)
  230. }
  231. }
  232. if err != nil {
  233. abortWithOpenAiMessage(c, http.StatusUnauthorized, err.Error())
  234. return
  235. }
  236. allowIps := token.GetIpLimits()
  237. if len(allowIps) > 0 {
  238. clientIp := c.ClientIP()
  239. logger.LogDebug(c, "Token has IP restrictions, checking client IP %s", clientIp)
  240. ip := net.ParseIP(clientIp)
  241. if ip == nil {
  242. abortWithOpenAiMessage(c, http.StatusForbidden, "无法解析客户端 IP 地址")
  243. return
  244. }
  245. if common.IsIpInCIDRList(ip, allowIps) == false {
  246. abortWithOpenAiMessage(c, http.StatusForbidden, "您的 IP 不在令牌允许访问的列表中", types.ErrorCodeAccessDenied)
  247. return
  248. }
  249. logger.LogDebug(c, "Client IP %s passed the token IP restrictions check", clientIp)
  250. }
  251. userCache, err := model.GetUserCache(token.UserId)
  252. if err != nil {
  253. abortWithOpenAiMessage(c, http.StatusInternalServerError, err.Error())
  254. return
  255. }
  256. userEnabled := userCache.Status == common.UserStatusEnabled
  257. if !userEnabled {
  258. abortWithOpenAiMessage(c, http.StatusForbidden, "用户已被封禁")
  259. return
  260. }
  261. userCache.WriteContext(c)
  262. userGroup := userCache.Group
  263. tokenGroup := token.Group
  264. if tokenGroup != "" {
  265. // check common.UserUsableGroups[userGroup]
  266. if _, ok := service.GetUserUsableGroups(userGroup)[tokenGroup]; !ok {
  267. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("无权访问 %s 分组", tokenGroup))
  268. return
  269. }
  270. // check group in common.GroupRatio
  271. if !ratio_setting.ContainsGroupRatio(tokenGroup) {
  272. if tokenGroup != "auto" {
  273. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("分组 %s 已被弃用", tokenGroup))
  274. return
  275. }
  276. }
  277. userGroup = tokenGroup
  278. }
  279. common.SetContextKey(c, constant.ContextKeyUsingGroup, userGroup)
  280. err = SetupContextForToken(c, token, parts...)
  281. if err != nil {
  282. return
  283. }
  284. c.Next()
  285. }
  286. }
  287. func SetupContextForToken(c *gin.Context, token *model.Token, parts ...string) error {
  288. if token == nil {
  289. return fmt.Errorf("token is nil")
  290. }
  291. c.Set("id", token.UserId)
  292. c.Set("token_id", token.Id)
  293. c.Set("token_key", token.Key)
  294. c.Set("token_name", token.Name)
  295. c.Set("token_unlimited_quota", token.UnlimitedQuota)
  296. if !token.UnlimitedQuota {
  297. c.Set("token_quota", token.RemainQuota)
  298. }
  299. if token.ModelLimitsEnabled {
  300. c.Set("token_model_limit_enabled", true)
  301. c.Set("token_model_limit", token.GetModelLimitsMap())
  302. } else {
  303. c.Set("token_model_limit_enabled", false)
  304. }
  305. common.SetContextKey(c, constant.ContextKeyTokenGroup, token.Group)
  306. common.SetContextKey(c, constant.ContextKeyTokenCrossGroupRetry, token.CrossGroupRetry)
  307. if len(parts) > 1 {
  308. if model.IsAdmin(token.UserId) {
  309. c.Set("specific_channel_id", parts[1])
  310. } else {
  311. abortWithOpenAiMessage(c, http.StatusForbidden, "普通用户不支持指定渠道")
  312. return fmt.Errorf("普通用户不支持指定渠道")
  313. }
  314. }
  315. return nil
  316. }