auth.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "one-api/common"
  6. "one-api/constant"
  7. "one-api/model"
  8. "one-api/setting"
  9. "one-api/setting/ratio_setting"
  10. "one-api/setting/system_setting"
  11. "one-api/src/oauth"
  12. "strconv"
  13. "strings"
  14. "github.com/gin-contrib/sessions"
  15. "github.com/gin-gonic/gin"
  16. jwt "github.com/golang-jwt/jwt/v5"
  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. rawAuth := c.Request.Header.Get("Authorization")
  170. // 先检测是否为ws
  171. if c.Request.Header.Get("Sec-WebSocket-Protocol") != "" {
  172. // Sec-WebSocket-Protocol: realtime, openai-insecure-api-key.sk-xxx, openai-beta.realtime-v1
  173. // read sk from Sec-WebSocket-Protocol
  174. key := c.Request.Header.Get("Sec-WebSocket-Protocol")
  175. parts := strings.Split(key, ",")
  176. for _, part := range parts {
  177. part = strings.TrimSpace(part)
  178. if strings.HasPrefix(part, "openai-insecure-api-key") {
  179. key = strings.TrimPrefix(part, "openai-insecure-api-key.")
  180. break
  181. }
  182. }
  183. c.Request.Header.Set("Authorization", "Bearer "+key)
  184. }
  185. // 检查path包含/v1/messages
  186. if strings.Contains(c.Request.URL.Path, "/v1/messages") {
  187. anthropicKey := c.Request.Header.Get("x-api-key")
  188. if anthropicKey != "" {
  189. c.Request.Header.Set("Authorization", "Bearer "+anthropicKey)
  190. }
  191. }
  192. // gemini api 从query中获取key
  193. if strings.HasPrefix(c.Request.URL.Path, "/v1beta/models") ||
  194. strings.HasPrefix(c.Request.URL.Path, "/v1beta/openai/models") ||
  195. strings.HasPrefix(c.Request.URL.Path, "/v1/models/") {
  196. skKey := c.Query("key")
  197. if skKey != "" {
  198. c.Request.Header.Set("Authorization", "Bearer "+skKey)
  199. }
  200. // 从x-goog-api-key header中获取key
  201. xGoogKey := c.Request.Header.Get("x-goog-api-key")
  202. if xGoogKey != "" {
  203. c.Request.Header.Set("Authorization", "Bearer "+xGoogKey)
  204. }
  205. }
  206. key := c.Request.Header.Get("Authorization")
  207. parts := make([]string, 0)
  208. key = strings.TrimPrefix(key, "Bearer ")
  209. if key == "" || key == "midjourney-proxy" {
  210. key = c.Request.Header.Get("mj-api-secret")
  211. key = strings.TrimPrefix(key, "Bearer ")
  212. key = strings.TrimPrefix(key, "sk-")
  213. parts = strings.Split(key, "-")
  214. key = parts[0]
  215. } else {
  216. key = strings.TrimPrefix(key, "sk-")
  217. parts = strings.Split(key, "-")
  218. key = parts[0]
  219. }
  220. token, err := model.ValidateUserToken(key)
  221. if token != nil {
  222. id := c.GetInt("id")
  223. if id == 0 {
  224. c.Set("id", token.UserId)
  225. }
  226. }
  227. if err != nil {
  228. // OAuth Bearer fallback
  229. if tryOAuthBearer(c, rawAuth) {
  230. c.Next()
  231. return
  232. }
  233. abortWithOpenAiMessage(c, http.StatusUnauthorized, err.Error())
  234. return
  235. }
  236. allowIpsMap := token.GetIpLimitsMap()
  237. if len(allowIpsMap) != 0 {
  238. clientIp := c.ClientIP()
  239. if _, ok := allowIpsMap[clientIp]; !ok {
  240. abortWithOpenAiMessage(c, http.StatusForbidden, "您的 IP 不在令牌允许访问的列表中")
  241. return
  242. }
  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 := setting.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. // tryOAuthBearer validates an OAuth JWT access token and sets minimal context for relay
  281. func tryOAuthBearer(c *gin.Context, rawAuth string) bool {
  282. if rawAuth == "" || !strings.HasPrefix(rawAuth, "Bearer ") {
  283. return false
  284. }
  285. tokenString := strings.TrimSpace(strings.TrimPrefix(rawAuth, "Bearer "))
  286. if tokenString == "" {
  287. return false
  288. }
  289. settings := system_setting.GetOAuth2Settings()
  290. // Parse & verify
  291. parsed, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
  292. if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
  293. return nil, jwt.ErrTokenSignatureInvalid
  294. }
  295. if kid, ok := t.Header["kid"].(string); ok {
  296. if settings.JWTKeyID != "" && kid != settings.JWTKeyID {
  297. return nil, jwt.ErrTokenSignatureInvalid
  298. }
  299. }
  300. pub := oauth.GetRSAPublicKey()
  301. if pub == nil {
  302. return nil, jwt.ErrTokenUnverifiable
  303. }
  304. return pub, nil
  305. })
  306. if err != nil || parsed == nil || !parsed.Valid {
  307. return false
  308. }
  309. claims, ok := parsed.Claims.(jwt.MapClaims)
  310. if !ok {
  311. return false
  312. }
  313. // issuer check when configured
  314. if iss, ok2 := claims["iss"].(string); !ok2 || (settings.Issuer != "" && iss != settings.Issuer) {
  315. return false
  316. }
  317. // revoke check
  318. if jti, ok2 := claims["jti"].(string); ok2 && jti != "" {
  319. if revoked, _ := model.IsTokenRevoked(jti); revoked {
  320. return false
  321. }
  322. }
  323. // scope check: must contain api:read or api:write or admin
  324. scope, _ := claims["scope"].(string)
  325. scopePadded := " " + scope + " "
  326. if !(strings.Contains(scopePadded, " api:read ") || strings.Contains(scopePadded, " api:write ") || strings.Contains(scopePadded, " admin ")) {
  327. return false
  328. }
  329. // subject must be user id to support quota logic
  330. sub, _ := claims["sub"].(string)
  331. uid, err := strconv.Atoi(sub)
  332. if err != nil || uid <= 0 {
  333. return false
  334. }
  335. // load user cache & set context
  336. userCache, err := model.GetUserCache(uid)
  337. if err != nil || userCache == nil || userCache.Status != common.UserStatusEnabled {
  338. return false
  339. }
  340. c.Set("id", uid)
  341. c.Set("group", userCache.Group)
  342. c.Set("user_group", userCache.Group)
  343. // set UsingGroup
  344. common.SetContextKey(c, constant.ContextKeyUsingGroup, userCache.Group)
  345. return true
  346. }
  347. func SetupContextForToken(c *gin.Context, token *model.Token, parts ...string) error {
  348. if token == nil {
  349. return fmt.Errorf("token is nil")
  350. }
  351. c.Set("id", token.UserId)
  352. c.Set("token_id", token.Id)
  353. c.Set("token_key", token.Key)
  354. c.Set("token_name", token.Name)
  355. c.Set("token_unlimited_quota", token.UnlimitedQuota)
  356. if !token.UnlimitedQuota {
  357. c.Set("token_quota", token.RemainQuota)
  358. }
  359. if token.ModelLimitsEnabled {
  360. c.Set("token_model_limit_enabled", true)
  361. c.Set("token_model_limit", token.GetModelLimitsMap())
  362. } else {
  363. c.Set("token_model_limit_enabled", false)
  364. }
  365. c.Set("token_group", token.Group)
  366. if len(parts) > 1 {
  367. if model.IsAdmin(token.UserId) {
  368. c.Set("specific_channel_id", parts[1])
  369. } else {
  370. abortWithOpenAiMessage(c, http.StatusForbidden, "普通用户不支持指定渠道")
  371. return fmt.Errorf("普通用户不支持指定渠道")
  372. }
  373. }
  374. return nil
  375. }