auth.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  207. key = strings.TrimSpace(key[7:])
  208. }
  209. if key == "" || key == "midjourney-proxy" {
  210. key = c.Request.Header.Get("mj-api-secret")
  211. if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
  212. key = strings.TrimSpace(key[7:])
  213. }
  214. key = strings.TrimPrefix(key, "sk-")
  215. parts = strings.Split(key, "-")
  216. key = parts[0]
  217. } else {
  218. key = strings.TrimPrefix(key, "sk-")
  219. parts = strings.Split(key, "-")
  220. key = parts[0]
  221. }
  222. token, err := model.ValidateUserToken(key)
  223. if token != nil {
  224. id := c.GetInt("id")
  225. if id == 0 {
  226. c.Set("id", token.UserId)
  227. }
  228. }
  229. if err != nil {
  230. abortWithOpenAiMessage(c, http.StatusUnauthorized, err.Error())
  231. return
  232. }
  233. allowIps := token.GetIpLimits()
  234. if len(allowIps) > 0 {
  235. clientIp := c.ClientIP()
  236. logger.LogDebug(c, "Token has IP restrictions, checking client IP %s", clientIp)
  237. ip := net.ParseIP(clientIp)
  238. if ip == nil {
  239. abortWithOpenAiMessage(c, http.StatusForbidden, "无法解析客户端 IP 地址")
  240. return
  241. }
  242. if common.IsIpInCIDRList(ip, allowIps) == false {
  243. abortWithOpenAiMessage(c, http.StatusForbidden, "您的 IP 不在令牌允许访问的列表中")
  244. return
  245. }
  246. logger.LogDebug(c, "Client IP %s passed the token IP restrictions check", clientIp)
  247. }
  248. userCache, err := model.GetUserCache(token.UserId)
  249. if err != nil {
  250. abortWithOpenAiMessage(c, http.StatusInternalServerError, err.Error())
  251. return
  252. }
  253. userEnabled := userCache.Status == common.UserStatusEnabled
  254. if !userEnabled {
  255. abortWithOpenAiMessage(c, http.StatusForbidden, "用户已被封禁")
  256. return
  257. }
  258. userCache.WriteContext(c)
  259. userGroup := userCache.Group
  260. tokenGroup := token.Group
  261. if tokenGroup != "" {
  262. // check common.UserUsableGroups[userGroup]
  263. if _, ok := service.GetUserUsableGroups(userGroup)[tokenGroup]; !ok {
  264. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("无权访问 %s 分组", tokenGroup))
  265. return
  266. }
  267. // check group in common.GroupRatio
  268. if !ratio_setting.ContainsGroupRatio(tokenGroup) {
  269. if tokenGroup != "auto" {
  270. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("分组 %s 已被弃用", tokenGroup))
  271. return
  272. }
  273. }
  274. userGroup = tokenGroup
  275. }
  276. common.SetContextKey(c, constant.ContextKeyUsingGroup, userGroup)
  277. err = SetupContextForToken(c, token, parts...)
  278. if err != nil {
  279. return
  280. }
  281. c.Next()
  282. }
  283. }
  284. func SetupContextForToken(c *gin.Context, token *model.Token, parts ...string) error {
  285. if token == nil {
  286. return fmt.Errorf("token is nil")
  287. }
  288. c.Set("id", token.UserId)
  289. c.Set("token_id", token.Id)
  290. c.Set("token_key", token.Key)
  291. c.Set("token_name", token.Name)
  292. c.Set("token_unlimited_quota", token.UnlimitedQuota)
  293. if !token.UnlimitedQuota {
  294. c.Set("token_quota", token.RemainQuota)
  295. }
  296. if token.ModelLimitsEnabled {
  297. c.Set("token_model_limit_enabled", true)
  298. c.Set("token_model_limit", token.GetModelLimitsMap())
  299. } else {
  300. c.Set("token_model_limit_enabled", false)
  301. }
  302. common.SetContextKey(c, constant.ContextKeyTokenGroup, token.Group)
  303. common.SetContextKey(c, constant.ContextKeyTokenCrossGroupRetry, token.CrossGroupRetry)
  304. if len(parts) > 1 {
  305. if model.IsAdmin(token.UserId) {
  306. c.Set("specific_channel_id", parts[1])
  307. } else {
  308. abortWithOpenAiMessage(c, http.StatusForbidden, "普通用户不支持指定渠道")
  309. return fmt.Errorf("普通用户不支持指定渠道")
  310. }
  311. }
  312. return nil
  313. }