auth.go 8.1 KB

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