auth.go 8.6 KB

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