auth.go 6.7 KB

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