auth.go 7.4 KB

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