auth.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. // 防止不同newapi版本冲突,导致数据不通用
  123. c.Header("Auth-Version", "864b7076dbcd0a3c01b5520316720ebf")
  124. c.Set("username", username)
  125. c.Set("role", role)
  126. c.Set("id", id)
  127. c.Set("group", session.Get("group"))
  128. c.Set("user_group", session.Get("group"))
  129. c.Set("use_access_token", useAccessToken)
  130. c.Next()
  131. }
  132. func TryUserAuth() func(c *gin.Context) {
  133. return func(c *gin.Context) {
  134. session := sessions.Default(c)
  135. id := session.Get("id")
  136. if id != nil {
  137. c.Set("id", id)
  138. }
  139. c.Next()
  140. }
  141. }
  142. func UserAuth() func(c *gin.Context) {
  143. return func(c *gin.Context) {
  144. authHelper(c, common.RoleCommonUser)
  145. }
  146. }
  147. func AdminAuth() func(c *gin.Context) {
  148. return func(c *gin.Context) {
  149. authHelper(c, common.RoleAdminUser)
  150. }
  151. }
  152. func RootAuth() func(c *gin.Context) {
  153. return func(c *gin.Context) {
  154. authHelper(c, common.RoleRootUser)
  155. }
  156. }
  157. func WssAuth(c *gin.Context) {
  158. }
  159. // TokenAuthReadOnly 宽松版本的令牌认证中间件,用于只读查询接口。
  160. // 只验证令牌 key 是否存在,不检查令牌状态、过期时间和额度。
  161. // 即使令牌已过期、已耗尽或已禁用,也允许访问。
  162. // 仍然检查用户是否被封禁。
  163. func TokenAuthReadOnly() func(c *gin.Context) {
  164. return func(c *gin.Context) {
  165. key := c.Request.Header.Get("Authorization")
  166. if key == "" {
  167. c.JSON(http.StatusUnauthorized, gin.H{
  168. "success": false,
  169. "message": "未提供 Authorization 请求头",
  170. })
  171. c.Abort()
  172. return
  173. }
  174. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  175. key = strings.TrimSpace(key[7:])
  176. }
  177. key = strings.TrimPrefix(key, "sk-")
  178. parts := strings.Split(key, "-")
  179. key = parts[0]
  180. token, err := model.GetTokenByKey(key, false)
  181. if err != nil {
  182. c.JSON(http.StatusUnauthorized, gin.H{
  183. "success": false,
  184. "message": "无效的令牌",
  185. })
  186. c.Abort()
  187. return
  188. }
  189. userCache, err := model.GetUserCache(token.UserId)
  190. if err != nil {
  191. c.JSON(http.StatusInternalServerError, gin.H{
  192. "success": false,
  193. "message": err.Error(),
  194. })
  195. c.Abort()
  196. return
  197. }
  198. if userCache.Status != common.UserStatusEnabled {
  199. c.JSON(http.StatusForbidden, gin.H{
  200. "success": false,
  201. "message": "用户已被封禁",
  202. })
  203. c.Abort()
  204. return
  205. }
  206. c.Set("id", token.UserId)
  207. c.Set("token_id", token.Id)
  208. c.Set("token_key", token.Key)
  209. c.Next()
  210. }
  211. }
  212. func TokenAuth() func(c *gin.Context) {
  213. return func(c *gin.Context) {
  214. // 先检测是否为ws
  215. if c.Request.Header.Get("Sec-WebSocket-Protocol") != "" {
  216. // Sec-WebSocket-Protocol: realtime, openai-insecure-api-key.sk-xxx, openai-beta.realtime-v1
  217. // read sk from Sec-WebSocket-Protocol
  218. key := c.Request.Header.Get("Sec-WebSocket-Protocol")
  219. parts := strings.Split(key, ",")
  220. for _, part := range parts {
  221. part = strings.TrimSpace(part)
  222. if strings.HasPrefix(part, "openai-insecure-api-key") {
  223. key = strings.TrimPrefix(part, "openai-insecure-api-key.")
  224. break
  225. }
  226. }
  227. c.Request.Header.Set("Authorization", "Bearer "+key)
  228. }
  229. // 检查path包含/v1/messages 或 /v1/models
  230. if strings.Contains(c.Request.URL.Path, "/v1/messages") || strings.Contains(c.Request.URL.Path, "/v1/models") {
  231. anthropicKey := c.Request.Header.Get("x-api-key")
  232. if anthropicKey != "" {
  233. c.Request.Header.Set("Authorization", "Bearer "+anthropicKey)
  234. }
  235. }
  236. // gemini api 从query中获取key
  237. if strings.HasPrefix(c.Request.URL.Path, "/v1beta/models") ||
  238. strings.HasPrefix(c.Request.URL.Path, "/v1beta/openai/models") ||
  239. strings.HasPrefix(c.Request.URL.Path, "/v1/models/") {
  240. skKey := c.Query("key")
  241. if skKey != "" {
  242. c.Request.Header.Set("Authorization", "Bearer "+skKey)
  243. }
  244. // 从x-goog-api-key header中获取key
  245. xGoogKey := c.Request.Header.Get("x-goog-api-key")
  246. if xGoogKey != "" {
  247. c.Request.Header.Set("Authorization", "Bearer "+xGoogKey)
  248. }
  249. }
  250. key := c.Request.Header.Get("Authorization")
  251. parts := make([]string, 0)
  252. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  253. key = strings.TrimSpace(key[7:])
  254. }
  255. if key == "" || key == "midjourney-proxy" {
  256. key = c.Request.Header.Get("mj-api-secret")
  257. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  258. key = strings.TrimSpace(key[7:])
  259. }
  260. key = strings.TrimPrefix(key, "sk-")
  261. parts = strings.Split(key, "-")
  262. key = parts[0]
  263. } else {
  264. key = strings.TrimPrefix(key, "sk-")
  265. parts = strings.Split(key, "-")
  266. key = parts[0]
  267. }
  268. token, err := model.ValidateUserToken(key)
  269. if token != nil {
  270. id := c.GetInt("id")
  271. if id == 0 {
  272. c.Set("id", token.UserId)
  273. }
  274. }
  275. if err != nil {
  276. abortWithOpenAiMessage(c, http.StatusUnauthorized, err.Error())
  277. return
  278. }
  279. allowIps := token.GetIpLimits()
  280. if len(allowIps) > 0 {
  281. clientIp := c.ClientIP()
  282. logger.LogDebug(c, "Token has IP restrictions, checking client IP %s", clientIp)
  283. ip := net.ParseIP(clientIp)
  284. if ip == nil {
  285. abortWithOpenAiMessage(c, http.StatusForbidden, "无法解析客户端 IP 地址")
  286. return
  287. }
  288. if common.IsIpInCIDRList(ip, allowIps) == false {
  289. abortWithOpenAiMessage(c, http.StatusForbidden, "您的 IP 不在令牌允许访问的列表中", types.ErrorCodeAccessDenied)
  290. return
  291. }
  292. logger.LogDebug(c, "Client IP %s passed the token IP restrictions check", clientIp)
  293. }
  294. userCache, err := model.GetUserCache(token.UserId)
  295. if err != nil {
  296. abortWithOpenAiMessage(c, http.StatusInternalServerError, err.Error())
  297. return
  298. }
  299. userEnabled := userCache.Status == common.UserStatusEnabled
  300. if !userEnabled {
  301. abortWithOpenAiMessage(c, http.StatusForbidden, "用户已被封禁")
  302. return
  303. }
  304. userCache.WriteContext(c)
  305. userGroup := userCache.Group
  306. tokenGroup := token.Group
  307. if tokenGroup != "" {
  308. // check common.UserUsableGroups[userGroup]
  309. if _, ok := service.GetUserUsableGroups(userGroup)[tokenGroup]; !ok {
  310. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("无权访问 %s 分组", tokenGroup))
  311. return
  312. }
  313. // check group in common.GroupRatio
  314. if !ratio_setting.ContainsGroupRatio(tokenGroup) {
  315. if tokenGroup != "auto" {
  316. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("分组 %s 已被弃用", tokenGroup))
  317. return
  318. }
  319. }
  320. userGroup = tokenGroup
  321. }
  322. common.SetContextKey(c, constant.ContextKeyUsingGroup, userGroup)
  323. err = SetupContextForToken(c, token, parts...)
  324. if err != nil {
  325. return
  326. }
  327. c.Next()
  328. }
  329. }
  330. func SetupContextForToken(c *gin.Context, token *model.Token, parts ...string) error {
  331. if token == nil {
  332. return fmt.Errorf("token is nil")
  333. }
  334. c.Set("id", token.UserId)
  335. c.Set("token_id", token.Id)
  336. c.Set("token_key", token.Key)
  337. c.Set("token_name", token.Name)
  338. c.Set("token_unlimited_quota", token.UnlimitedQuota)
  339. if !token.UnlimitedQuota {
  340. c.Set("token_quota", token.RemainQuota)
  341. }
  342. if token.ModelLimitsEnabled {
  343. c.Set("token_model_limit_enabled", true)
  344. c.Set("token_model_limit", token.GetModelLimitsMap())
  345. } else {
  346. c.Set("token_model_limit_enabled", false)
  347. }
  348. common.SetContextKey(c, constant.ContextKeyTokenGroup, token.Group)
  349. common.SetContextKey(c, constant.ContextKeyTokenCrossGroupRetry, token.CrossGroupRetry)
  350. if len(parts) > 1 {
  351. if model.IsAdmin(token.UserId) {
  352. c.Set("specific_channel_id", parts[1])
  353. } else {
  354. c.Header("specific_channel_version", "701e3ae1dc3f7975556d354e0675168d004891c8")
  355. abortWithOpenAiMessage(c, http.StatusForbidden, "普通用户不支持指定渠道")
  356. return fmt.Errorf("普通用户不支持指定渠道")
  357. }
  358. }
  359. return nil
  360. }