user.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/i18n"
  14. "github.com/QuantumNous/new-api/logger"
  15. "github.com/QuantumNous/new-api/model"
  16. "github.com/QuantumNous/new-api/service"
  17. "github.com/QuantumNous/new-api/setting"
  18. "github.com/QuantumNous/new-api/constant"
  19. "github.com/gin-contrib/sessions"
  20. "github.com/gin-gonic/gin"
  21. )
  22. type LoginRequest struct {
  23. Username string `json:"username"`
  24. Password string `json:"password"`
  25. }
  26. func Login(c *gin.Context) {
  27. if !common.PasswordLoginEnabled {
  28. common.ApiErrorI18n(c, i18n.MsgUserPasswordLoginDisabled)
  29. return
  30. }
  31. var loginRequest LoginRequest
  32. err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
  33. if err != nil {
  34. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  35. return
  36. }
  37. username := loginRequest.Username
  38. password := loginRequest.Password
  39. if username == "" || password == "" {
  40. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  41. return
  42. }
  43. user := model.User{
  44. Username: username,
  45. Password: password,
  46. }
  47. err = user.ValidateAndFill()
  48. if err != nil {
  49. c.JSON(http.StatusOK, gin.H{
  50. "message": err.Error(),
  51. "success": false,
  52. })
  53. return
  54. }
  55. // 检查是否启用2FA
  56. if model.IsTwoFAEnabled(user.Id) {
  57. // 设置pending session,等待2FA验证
  58. session := sessions.Default(c)
  59. session.Set("pending_username", user.Username)
  60. session.Set("pending_user_id", user.Id)
  61. err := session.Save()
  62. if err != nil {
  63. common.ApiErrorI18n(c, i18n.MsgUserSessionSaveFailed)
  64. return
  65. }
  66. c.JSON(http.StatusOK, gin.H{
  67. "message": i18n.T(c, i18n.MsgUserRequire2FA),
  68. "success": true,
  69. "data": map[string]interface{}{
  70. "require_2fa": true,
  71. },
  72. })
  73. return
  74. }
  75. setupLogin(&user, c)
  76. }
  77. // setup session & cookies and then return user info
  78. func setupLogin(user *model.User, c *gin.Context) {
  79. session := sessions.Default(c)
  80. session.Set("id", user.Id)
  81. session.Set("username", user.Username)
  82. session.Set("role", user.Role)
  83. session.Set("status", user.Status)
  84. session.Set("group", user.Group)
  85. err := session.Save()
  86. if err != nil {
  87. common.ApiErrorI18n(c, i18n.MsgUserSessionSaveFailed)
  88. return
  89. }
  90. c.JSON(http.StatusOK, gin.H{
  91. "message": "",
  92. "success": true,
  93. "data": map[string]any{
  94. "id": user.Id,
  95. "username": user.Username,
  96. "display_name": user.DisplayName,
  97. "role": user.Role,
  98. "status": user.Status,
  99. "group": user.Group,
  100. },
  101. })
  102. }
  103. func Logout(c *gin.Context) {
  104. session := sessions.Default(c)
  105. session.Clear()
  106. err := session.Save()
  107. if err != nil {
  108. c.JSON(http.StatusOK, gin.H{
  109. "message": err.Error(),
  110. "success": false,
  111. })
  112. return
  113. }
  114. c.JSON(http.StatusOK, gin.H{
  115. "message": "",
  116. "success": true,
  117. })
  118. }
  119. func Register(c *gin.Context) {
  120. if !common.RegisterEnabled {
  121. common.ApiErrorI18n(c, i18n.MsgUserRegisterDisabled)
  122. return
  123. }
  124. if !common.PasswordRegisterEnabled {
  125. common.ApiErrorI18n(c, i18n.MsgUserPasswordRegisterDisabled)
  126. return
  127. }
  128. var user model.User
  129. err := json.NewDecoder(c.Request.Body).Decode(&user)
  130. if err != nil {
  131. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  132. return
  133. }
  134. if err := common.Validate.Struct(&user); err != nil {
  135. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  136. return
  137. }
  138. if common.EmailVerificationEnabled {
  139. if user.Email == "" || user.VerificationCode == "" {
  140. common.ApiErrorI18n(c, i18n.MsgUserEmailVerificationRequired)
  141. return
  142. }
  143. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  144. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  145. return
  146. }
  147. }
  148. exist, err := model.CheckUserExistOrDeleted(user.Username, user.Email)
  149. if err != nil {
  150. common.ApiErrorI18n(c, i18n.MsgDatabaseError)
  151. common.SysLog(fmt.Sprintf("CheckUserExistOrDeleted error: %v", err))
  152. return
  153. }
  154. if exist {
  155. common.ApiErrorI18n(c, i18n.MsgUserExists)
  156. return
  157. }
  158. affCode := user.AffCode // this code is the inviter's code, not the user's own code
  159. inviterId, _ := model.GetUserIdByAffCode(affCode)
  160. cleanUser := model.User{
  161. Username: user.Username,
  162. Password: user.Password,
  163. DisplayName: user.Username,
  164. InviterId: inviterId,
  165. Role: common.RoleCommonUser, // 明确设置角色为普通用户
  166. }
  167. if common.EmailVerificationEnabled {
  168. cleanUser.Email = user.Email
  169. }
  170. if err := cleanUser.Insert(inviterId); err != nil {
  171. common.ApiError(c, err)
  172. return
  173. }
  174. // 获取插入后的用户ID
  175. var insertedUser model.User
  176. if err := model.DB.Where("username = ?", cleanUser.Username).First(&insertedUser).Error; err != nil {
  177. common.ApiErrorI18n(c, i18n.MsgUserRegisterFailed)
  178. return
  179. }
  180. // 生成默认令牌
  181. if constant.GenerateDefaultToken {
  182. key, err := common.GenerateKey()
  183. if err != nil {
  184. common.ApiErrorI18n(c, i18n.MsgUserDefaultTokenFailed)
  185. common.SysLog("failed to generate token key: " + err.Error())
  186. return
  187. }
  188. // 生成默认令牌
  189. token := model.Token{
  190. UserId: insertedUser.Id, // 使用插入后的用户ID
  191. Name: cleanUser.Username + "的初始令牌",
  192. Key: key,
  193. CreatedTime: common.GetTimestamp(),
  194. AccessedTime: common.GetTimestamp(),
  195. ExpiredTime: -1, // 永不过期
  196. RemainQuota: 500000, // 示例额度
  197. UnlimitedQuota: true,
  198. ModelLimitsEnabled: false,
  199. }
  200. if setting.DefaultUseAutoGroup {
  201. token.Group = "auto"
  202. }
  203. if err := token.Insert(); err != nil {
  204. common.ApiErrorI18n(c, i18n.MsgCreateDefaultTokenErr)
  205. return
  206. }
  207. }
  208. c.JSON(http.StatusOK, gin.H{
  209. "success": true,
  210. "message": "",
  211. })
  212. return
  213. }
  214. func GetAllUsers(c *gin.Context) {
  215. pageInfo := common.GetPageQuery(c)
  216. users, total, err := model.GetAllUsers(pageInfo)
  217. if err != nil {
  218. common.ApiError(c, err)
  219. return
  220. }
  221. pageInfo.SetTotal(int(total))
  222. pageInfo.SetItems(users)
  223. common.ApiSuccess(c, pageInfo)
  224. return
  225. }
  226. func SearchUsers(c *gin.Context) {
  227. keyword := c.Query("keyword")
  228. group := c.Query("group")
  229. pageInfo := common.GetPageQuery(c)
  230. users, total, err := model.SearchUsers(keyword, group, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  231. if err != nil {
  232. common.ApiError(c, err)
  233. return
  234. }
  235. pageInfo.SetTotal(int(total))
  236. pageInfo.SetItems(users)
  237. common.ApiSuccess(c, pageInfo)
  238. return
  239. }
  240. func GetUser(c *gin.Context) {
  241. id, err := strconv.Atoi(c.Param("id"))
  242. if err != nil {
  243. common.ApiError(c, err)
  244. return
  245. }
  246. user, err := model.GetUserById(id, false)
  247. if err != nil {
  248. common.ApiError(c, err)
  249. return
  250. }
  251. myRole := c.GetInt("role")
  252. if myRole <= user.Role && myRole != common.RoleRootUser {
  253. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
  254. return
  255. }
  256. c.JSON(http.StatusOK, gin.H{
  257. "success": true,
  258. "message": "",
  259. "data": user,
  260. })
  261. return
  262. }
  263. func GenerateAccessToken(c *gin.Context) {
  264. id := c.GetInt("id")
  265. user, err := model.GetUserById(id, true)
  266. if err != nil {
  267. common.ApiError(c, err)
  268. return
  269. }
  270. // get rand int 28-32
  271. randI := common.GetRandomInt(4)
  272. key, err := common.GenerateRandomKey(29 + randI)
  273. if err != nil {
  274. common.ApiErrorI18n(c, i18n.MsgGenerateFailed)
  275. common.SysLog("failed to generate key: " + err.Error())
  276. return
  277. }
  278. user.SetAccessToken(key)
  279. if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
  280. common.ApiErrorI18n(c, i18n.MsgUuidDuplicate)
  281. return
  282. }
  283. if err := user.Update(false); err != nil {
  284. common.ApiError(c, err)
  285. return
  286. }
  287. c.JSON(http.StatusOK, gin.H{
  288. "success": true,
  289. "message": "",
  290. "data": user.AccessToken,
  291. })
  292. return
  293. }
  294. type TransferAffQuotaRequest struct {
  295. Quota int `json:"quota" binding:"required"`
  296. }
  297. func TransferAffQuota(c *gin.Context) {
  298. id := c.GetInt("id")
  299. user, err := model.GetUserById(id, true)
  300. if err != nil {
  301. common.ApiError(c, err)
  302. return
  303. }
  304. tran := TransferAffQuotaRequest{}
  305. if err := c.ShouldBindJSON(&tran); err != nil {
  306. common.ApiError(c, err)
  307. return
  308. }
  309. err = user.TransferAffQuotaToQuota(tran.Quota)
  310. if err != nil {
  311. common.ApiErrorI18n(c, i18n.MsgUserTransferFailed, map[string]any{"Error": err.Error()})
  312. return
  313. }
  314. common.ApiSuccessI18n(c, i18n.MsgUserTransferSuccess, nil)
  315. }
  316. func GetAffCode(c *gin.Context) {
  317. id := c.GetInt("id")
  318. user, err := model.GetUserById(id, true)
  319. if err != nil {
  320. common.ApiError(c, err)
  321. return
  322. }
  323. if user.AffCode == "" {
  324. user.AffCode = common.GetRandomString(4)
  325. if err := user.Update(false); err != nil {
  326. c.JSON(http.StatusOK, gin.H{
  327. "success": false,
  328. "message": err.Error(),
  329. })
  330. return
  331. }
  332. }
  333. c.JSON(http.StatusOK, gin.H{
  334. "success": true,
  335. "message": "",
  336. "data": user.AffCode,
  337. })
  338. return
  339. }
  340. func GetSelf(c *gin.Context) {
  341. id := c.GetInt("id")
  342. userRole := c.GetInt("role")
  343. user, err := model.GetUserById(id, false)
  344. if err != nil {
  345. common.ApiError(c, err)
  346. return
  347. }
  348. // Hide admin remarks: set to empty to trigger omitempty tag, ensuring the remark field is not included in JSON returned to regular users
  349. user.Remark = ""
  350. // 计算用户权限信息
  351. permissions := calculateUserPermissions(userRole)
  352. // 获取用户设置并提取sidebar_modules
  353. userSetting := user.GetSetting()
  354. // 构建响应数据,包含用户信息和权限
  355. responseData := map[string]interface{}{
  356. "id": user.Id,
  357. "username": user.Username,
  358. "display_name": user.DisplayName,
  359. "role": user.Role,
  360. "status": user.Status,
  361. "email": user.Email,
  362. "github_id": user.GitHubId,
  363. "discord_id": user.DiscordId,
  364. "oidc_id": user.OidcId,
  365. "wechat_id": user.WeChatId,
  366. "telegram_id": user.TelegramId,
  367. "group": user.Group,
  368. "quota": user.Quota,
  369. "used_quota": user.UsedQuota,
  370. "request_count": user.RequestCount,
  371. "aff_code": user.AffCode,
  372. "aff_count": user.AffCount,
  373. "aff_quota": user.AffQuota,
  374. "aff_history_quota": user.AffHistoryQuota,
  375. "inviter_id": user.InviterId,
  376. "linux_do_id": user.LinuxDOId,
  377. "setting": user.Setting,
  378. "stripe_customer": user.StripeCustomer,
  379. "sidebar_modules": userSetting.SidebarModules, // 正确提取sidebar_modules字段
  380. "permissions": permissions, // 新增权限字段
  381. }
  382. c.JSON(http.StatusOK, gin.H{
  383. "success": true,
  384. "message": "",
  385. "data": responseData,
  386. })
  387. return
  388. }
  389. // 计算用户权限的辅助函数
  390. func calculateUserPermissions(userRole int) map[string]interface{} {
  391. permissions := map[string]interface{}{}
  392. // 根据用户角色计算权限
  393. if userRole == common.RoleRootUser {
  394. // 超级管理员不需要边栏设置功能
  395. permissions["sidebar_settings"] = false
  396. permissions["sidebar_modules"] = map[string]interface{}{}
  397. } else if userRole == common.RoleAdminUser {
  398. // 管理员可以设置边栏,但不包含系统设置功能
  399. permissions["sidebar_settings"] = true
  400. permissions["sidebar_modules"] = map[string]interface{}{
  401. "admin": map[string]interface{}{
  402. "setting": false, // 管理员不能访问系统设置
  403. },
  404. }
  405. } else {
  406. // 普通用户只能设置个人功能,不包含管理员区域
  407. permissions["sidebar_settings"] = true
  408. permissions["sidebar_modules"] = map[string]interface{}{
  409. "admin": false, // 普通用户不能访问管理员区域
  410. }
  411. }
  412. return permissions
  413. }
  414. // 根据用户角色生成默认的边栏配置
  415. func generateDefaultSidebarConfig(userRole int) string {
  416. defaultConfig := map[string]interface{}{}
  417. // 聊天区域 - 所有用户都可以访问
  418. defaultConfig["chat"] = map[string]interface{}{
  419. "enabled": true,
  420. "playground": true,
  421. "chat": true,
  422. }
  423. // 控制台区域 - 所有用户都可以访问
  424. defaultConfig["console"] = map[string]interface{}{
  425. "enabled": true,
  426. "detail": true,
  427. "token": true,
  428. "log": true,
  429. "midjourney": true,
  430. "task": true,
  431. }
  432. // 个人中心区域 - 所有用户都可以访问
  433. defaultConfig["personal"] = map[string]interface{}{
  434. "enabled": true,
  435. "topup": true,
  436. "personal": true,
  437. }
  438. // 管理员区域 - 根据角色决定
  439. if userRole == common.RoleAdminUser {
  440. // 管理员可以访问管理员区域,但不能访问系统设置
  441. defaultConfig["admin"] = map[string]interface{}{
  442. "enabled": true,
  443. "channel": true,
  444. "models": true,
  445. "redemption": true,
  446. "user": true,
  447. "setting": false, // 管理员不能访问系统设置
  448. }
  449. } else if userRole == common.RoleRootUser {
  450. // 超级管理员可以访问所有功能
  451. defaultConfig["admin"] = map[string]interface{}{
  452. "enabled": true,
  453. "channel": true,
  454. "models": true,
  455. "redemption": true,
  456. "user": true,
  457. "setting": true,
  458. }
  459. }
  460. // 普通用户不包含admin区域
  461. // 转换为JSON字符串
  462. configBytes, err := json.Marshal(defaultConfig)
  463. if err != nil {
  464. common.SysLog("生成默认边栏配置失败: " + err.Error())
  465. return ""
  466. }
  467. return string(configBytes)
  468. }
  469. func GetUserModels(c *gin.Context) {
  470. id, err := strconv.Atoi(c.Param("id"))
  471. if err != nil {
  472. id = c.GetInt("id")
  473. }
  474. user, err := model.GetUserCache(id)
  475. if err != nil {
  476. common.ApiError(c, err)
  477. return
  478. }
  479. groups := service.GetUserUsableGroups(user.Group)
  480. var models []string
  481. for group := range groups {
  482. for _, g := range model.GetGroupEnabledModels(group) {
  483. if !common.StringsContains(models, g) {
  484. models = append(models, g)
  485. }
  486. }
  487. }
  488. c.JSON(http.StatusOK, gin.H{
  489. "success": true,
  490. "message": "",
  491. "data": models,
  492. })
  493. return
  494. }
  495. func UpdateUser(c *gin.Context) {
  496. var updatedUser model.User
  497. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  498. if err != nil || updatedUser.Id == 0 {
  499. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  500. return
  501. }
  502. if updatedUser.Password == "" {
  503. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  504. }
  505. if err := common.Validate.Struct(&updatedUser); err != nil {
  506. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  507. return
  508. }
  509. originUser, err := model.GetUserById(updatedUser.Id, false)
  510. if err != nil {
  511. common.ApiError(c, err)
  512. return
  513. }
  514. myRole := c.GetInt("role")
  515. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  516. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  517. return
  518. }
  519. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  520. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  521. return
  522. }
  523. if updatedUser.Password == "$I_LOVE_U" {
  524. updatedUser.Password = "" // rollback to what it should be
  525. }
  526. updatePassword := updatedUser.Password != ""
  527. if err := updatedUser.Edit(updatePassword); err != nil {
  528. common.ApiError(c, err)
  529. return
  530. }
  531. c.JSON(http.StatusOK, gin.H{
  532. "success": true,
  533. "message": "",
  534. })
  535. return
  536. }
  537. func AdminClearUserBinding(c *gin.Context) {
  538. id, err := strconv.Atoi(c.Param("id"))
  539. if err != nil {
  540. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  541. return
  542. }
  543. bindingType := strings.ToLower(strings.TrimSpace(c.Param("binding_type")))
  544. if bindingType == "" {
  545. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  546. return
  547. }
  548. user, err := model.GetUserById(id, false)
  549. if err != nil {
  550. common.ApiError(c, err)
  551. return
  552. }
  553. myRole := c.GetInt("role")
  554. if myRole <= user.Role && myRole != common.RoleRootUser {
  555. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
  556. return
  557. }
  558. if err := user.ClearBinding(bindingType); err != nil {
  559. common.ApiError(c, err)
  560. return
  561. }
  562. model.RecordLog(user.Id, model.LogTypeManage, fmt.Sprintf("admin cleared %s binding for user %s", bindingType, user.Username))
  563. c.JSON(http.StatusOK, gin.H{
  564. "success": true,
  565. "message": "success",
  566. })
  567. }
  568. func UpdateSelf(c *gin.Context) {
  569. var requestData map[string]interface{}
  570. err := json.NewDecoder(c.Request.Body).Decode(&requestData)
  571. if err != nil {
  572. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  573. return
  574. }
  575. // 检查是否是用户设置更新请求 (sidebar_modules 或 language)
  576. if sidebarModules, sidebarExists := requestData["sidebar_modules"]; sidebarExists {
  577. userId := c.GetInt("id")
  578. user, err := model.GetUserById(userId, false)
  579. if err != nil {
  580. common.ApiError(c, err)
  581. return
  582. }
  583. // 获取当前用户设置
  584. currentSetting := user.GetSetting()
  585. // 更新sidebar_modules字段
  586. if sidebarModulesStr, ok := sidebarModules.(string); ok {
  587. currentSetting.SidebarModules = sidebarModulesStr
  588. }
  589. // 保存更新后的设置
  590. user.SetSetting(currentSetting)
  591. if err := user.Update(false); err != nil {
  592. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  593. return
  594. }
  595. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  596. return
  597. }
  598. // 检查是否是语言偏好更新请求
  599. if language, langExists := requestData["language"]; langExists {
  600. userId := c.GetInt("id")
  601. user, err := model.GetUserById(userId, false)
  602. if err != nil {
  603. common.ApiError(c, err)
  604. return
  605. }
  606. // 获取当前用户设置
  607. currentSetting := user.GetSetting()
  608. // 更新language字段
  609. if langStr, ok := language.(string); ok {
  610. currentSetting.Language = langStr
  611. }
  612. // 保存更新后的设置
  613. user.SetSetting(currentSetting)
  614. if err := user.Update(false); err != nil {
  615. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  616. return
  617. }
  618. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  619. return
  620. }
  621. // 原有的用户信息更新逻辑
  622. var user model.User
  623. requestDataBytes, err := json.Marshal(requestData)
  624. if err != nil {
  625. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  626. return
  627. }
  628. err = json.Unmarshal(requestDataBytes, &user)
  629. if err != nil {
  630. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  631. return
  632. }
  633. if user.Password == "" {
  634. user.Password = "$I_LOVE_U" // make Validator happy :)
  635. }
  636. if err := common.Validate.Struct(&user); err != nil {
  637. common.ApiErrorI18n(c, i18n.MsgInvalidInput)
  638. return
  639. }
  640. cleanUser := model.User{
  641. Id: c.GetInt("id"),
  642. Username: user.Username,
  643. Password: user.Password,
  644. DisplayName: user.DisplayName,
  645. }
  646. if user.Password == "$I_LOVE_U" {
  647. user.Password = "" // rollback to what it should be
  648. cleanUser.Password = ""
  649. }
  650. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  651. if err != nil {
  652. common.ApiError(c, err)
  653. return
  654. }
  655. if err := cleanUser.Update(updatePassword); err != nil {
  656. common.ApiError(c, err)
  657. return
  658. }
  659. c.JSON(http.StatusOK, gin.H{
  660. "success": true,
  661. "message": "",
  662. })
  663. return
  664. }
  665. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  666. var currentUser *model.User
  667. currentUser, err = model.GetUserById(userId, true)
  668. if err != nil {
  669. return
  670. }
  671. // 密码不为空,需要验证原密码
  672. // 支持第一次账号绑定时原密码为空的情况
  673. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) && currentUser.Password != "" {
  674. err = fmt.Errorf("原密码错误")
  675. return
  676. }
  677. if newPassword == "" {
  678. return
  679. }
  680. updatePassword = true
  681. return
  682. }
  683. func DeleteUser(c *gin.Context) {
  684. id, err := strconv.Atoi(c.Param("id"))
  685. if err != nil {
  686. common.ApiError(c, err)
  687. return
  688. }
  689. originUser, err := model.GetUserById(id, false)
  690. if err != nil {
  691. common.ApiError(c, err)
  692. return
  693. }
  694. myRole := c.GetInt("role")
  695. if myRole <= originUser.Role {
  696. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  697. return
  698. }
  699. err = model.HardDeleteUserById(id)
  700. if err != nil {
  701. c.JSON(http.StatusOK, gin.H{
  702. "success": true,
  703. "message": "",
  704. })
  705. return
  706. }
  707. }
  708. func DeleteSelf(c *gin.Context) {
  709. id := c.GetInt("id")
  710. user, _ := model.GetUserById(id, false)
  711. if user.Role == common.RoleRootUser {
  712. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  713. return
  714. }
  715. err := model.DeleteUserById(id)
  716. if err != nil {
  717. common.ApiError(c, err)
  718. return
  719. }
  720. c.JSON(http.StatusOK, gin.H{
  721. "success": true,
  722. "message": "",
  723. })
  724. return
  725. }
  726. func CreateUser(c *gin.Context) {
  727. var user model.User
  728. err := json.NewDecoder(c.Request.Body).Decode(&user)
  729. user.Username = strings.TrimSpace(user.Username)
  730. if err != nil || user.Username == "" || user.Password == "" {
  731. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  732. return
  733. }
  734. if err := common.Validate.Struct(&user); err != nil {
  735. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  736. return
  737. }
  738. if user.DisplayName == "" {
  739. user.DisplayName = user.Username
  740. }
  741. myRole := c.GetInt("role")
  742. if user.Role >= myRole {
  743. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  744. return
  745. }
  746. // Even for admin users, we cannot fully trust them!
  747. cleanUser := model.User{
  748. Username: user.Username,
  749. Password: user.Password,
  750. DisplayName: user.DisplayName,
  751. Role: user.Role, // 保持管理员设置的角色
  752. }
  753. if err := cleanUser.Insert(0); err != nil {
  754. common.ApiError(c, err)
  755. return
  756. }
  757. c.JSON(http.StatusOK, gin.H{
  758. "success": true,
  759. "message": "",
  760. })
  761. return
  762. }
  763. type ManageRequest struct {
  764. Id int `json:"id"`
  765. Action string `json:"action"`
  766. Value int `json:"value"`
  767. Mode string `json:"mode"`
  768. }
  769. // ManageUser Only admin user can do this
  770. func ManageUser(c *gin.Context) {
  771. var req ManageRequest
  772. err := json.NewDecoder(c.Request.Body).Decode(&req)
  773. if err != nil {
  774. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  775. return
  776. }
  777. user := model.User{
  778. Id: req.Id,
  779. }
  780. // Fill attributes
  781. model.DB.Unscoped().Where(&user).First(&user)
  782. if user.Id == 0 {
  783. common.ApiErrorI18n(c, i18n.MsgUserNotExists)
  784. return
  785. }
  786. myRole := c.GetInt("role")
  787. if myRole <= user.Role && myRole != common.RoleRootUser {
  788. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  789. return
  790. }
  791. switch req.Action {
  792. case "disable":
  793. user.Status = common.UserStatusDisabled
  794. if user.Role == common.RoleRootUser {
  795. common.ApiErrorI18n(c, i18n.MsgUserCannotDisableRootUser)
  796. return
  797. }
  798. case "enable":
  799. user.Status = common.UserStatusEnabled
  800. case "delete":
  801. if user.Role == common.RoleRootUser {
  802. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  803. return
  804. }
  805. if err := user.Delete(); err != nil {
  806. c.JSON(http.StatusOK, gin.H{
  807. "success": false,
  808. "message": err.Error(),
  809. })
  810. return
  811. }
  812. case "promote":
  813. if myRole != common.RoleRootUser {
  814. common.ApiErrorI18n(c, i18n.MsgUserAdminCannotPromote)
  815. return
  816. }
  817. if user.Role >= common.RoleAdminUser {
  818. common.ApiErrorI18n(c, i18n.MsgUserAlreadyAdmin)
  819. return
  820. }
  821. user.Role = common.RoleAdminUser
  822. case "demote":
  823. if user.Role == common.RoleRootUser {
  824. common.ApiErrorI18n(c, i18n.MsgUserCannotDemoteRootUser)
  825. return
  826. }
  827. if user.Role == common.RoleCommonUser {
  828. common.ApiErrorI18n(c, i18n.MsgUserAlreadyCommon)
  829. return
  830. }
  831. user.Role = common.RoleCommonUser
  832. case "add_quota":
  833. switch req.Mode {
  834. case "add":
  835. if req.Value <= 0 {
  836. common.ApiErrorI18n(c, i18n.MsgUserQuotaChangeZero)
  837. return
  838. }
  839. if err := model.IncreaseUserQuota(user.Id, req.Value, true); err != nil {
  840. common.ApiError(c, err)
  841. return
  842. }
  843. model.RecordLog(user.Id, model.LogTypeManage,
  844. fmt.Sprintf("管理员增加用户额度 %s", logger.LogQuota(req.Value)))
  845. case "subtract":
  846. if req.Value <= 0 {
  847. common.ApiErrorI18n(c, i18n.MsgUserQuotaChangeZero)
  848. return
  849. }
  850. if err := model.DecreaseUserQuota(user.Id, req.Value, true); err != nil {
  851. common.ApiError(c, err)
  852. return
  853. }
  854. model.RecordLog(user.Id, model.LogTypeManage,
  855. fmt.Sprintf("管理员减少用户额度 %s", logger.LogQuota(req.Value)))
  856. case "override":
  857. oldQuota := user.Quota
  858. if err := model.DB.Model(&model.User{}).Where("id = ?", user.Id).Update("quota", req.Value).Error; err != nil {
  859. common.ApiError(c, err)
  860. return
  861. }
  862. model.RecordLog(user.Id, model.LogTypeManage,
  863. fmt.Sprintf("管理员覆盖用户额度从 %s 为 %s", logger.LogQuota(oldQuota), logger.LogQuota(req.Value)))
  864. default:
  865. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  866. return
  867. }
  868. c.JSON(http.StatusOK, gin.H{
  869. "success": true,
  870. "message": "",
  871. })
  872. return
  873. }
  874. if err := user.Update(false); err != nil {
  875. common.ApiError(c, err)
  876. return
  877. }
  878. clearUser := model.User{
  879. Role: user.Role,
  880. Status: user.Status,
  881. }
  882. c.JSON(http.StatusOK, gin.H{
  883. "success": true,
  884. "message": "",
  885. "data": clearUser,
  886. })
  887. return
  888. }
  889. type emailBindRequest struct {
  890. Email string `json:"email"`
  891. Code string `json:"code"`
  892. }
  893. func EmailBind(c *gin.Context) {
  894. var req emailBindRequest
  895. if err := common.DecodeJson(c.Request.Body, &req); err != nil {
  896. common.ApiError(c, errors.New("invalid request body"))
  897. return
  898. }
  899. email := req.Email
  900. code := req.Code
  901. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  902. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  903. return
  904. }
  905. session := sessions.Default(c)
  906. id := session.Get("id")
  907. user := model.User{
  908. Id: id.(int),
  909. }
  910. err := user.FillUserById()
  911. if err != nil {
  912. common.ApiError(c, err)
  913. return
  914. }
  915. user.Email = email
  916. // no need to check if this email already taken, because we have used verification code to check it
  917. err = user.Update(false)
  918. if err != nil {
  919. common.ApiError(c, err)
  920. return
  921. }
  922. c.JSON(http.StatusOK, gin.H{
  923. "success": true,
  924. "message": "",
  925. })
  926. return
  927. }
  928. type topUpRequest struct {
  929. Key string `json:"key"`
  930. }
  931. var topUpLocks sync.Map
  932. var topUpCreateLock sync.Mutex
  933. type topUpTryLock struct {
  934. ch chan struct{}
  935. }
  936. func newTopUpTryLock() *topUpTryLock {
  937. return &topUpTryLock{ch: make(chan struct{}, 1)}
  938. }
  939. func (l *topUpTryLock) TryLock() bool {
  940. select {
  941. case l.ch <- struct{}{}:
  942. return true
  943. default:
  944. return false
  945. }
  946. }
  947. func (l *topUpTryLock) Unlock() {
  948. select {
  949. case <-l.ch:
  950. default:
  951. }
  952. }
  953. func getTopUpLock(userID int) *topUpTryLock {
  954. if v, ok := topUpLocks.Load(userID); ok {
  955. return v.(*topUpTryLock)
  956. }
  957. topUpCreateLock.Lock()
  958. defer topUpCreateLock.Unlock()
  959. if v, ok := topUpLocks.Load(userID); ok {
  960. return v.(*topUpTryLock)
  961. }
  962. l := newTopUpTryLock()
  963. topUpLocks.Store(userID, l)
  964. return l
  965. }
  966. func TopUp(c *gin.Context) {
  967. id := c.GetInt("id")
  968. lock := getTopUpLock(id)
  969. if !lock.TryLock() {
  970. common.ApiErrorI18n(c, i18n.MsgUserTopUpProcessing)
  971. return
  972. }
  973. defer lock.Unlock()
  974. req := topUpRequest{}
  975. err := c.ShouldBindJSON(&req)
  976. if err != nil {
  977. common.ApiError(c, err)
  978. return
  979. }
  980. quota, err := model.Redeem(req.Key, id)
  981. if err != nil {
  982. if errors.Is(err, model.ErrRedeemFailed) {
  983. common.ApiErrorI18n(c, i18n.MsgRedeemFailed)
  984. return
  985. }
  986. common.ApiError(c, err)
  987. return
  988. }
  989. c.JSON(http.StatusOK, gin.H{
  990. "success": true,
  991. "message": "",
  992. "data": quota,
  993. })
  994. }
  995. type UpdateUserSettingRequest struct {
  996. QuotaWarningType string `json:"notify_type"`
  997. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  998. WebhookUrl string `json:"webhook_url,omitempty"`
  999. WebhookSecret string `json:"webhook_secret,omitempty"`
  1000. NotificationEmail string `json:"notification_email,omitempty"`
  1001. BarkUrl string `json:"bark_url,omitempty"`
  1002. GotifyUrl string `json:"gotify_url,omitempty"`
  1003. GotifyToken string `json:"gotify_token,omitempty"`
  1004. GotifyPriority int `json:"gotify_priority,omitempty"`
  1005. UpstreamModelUpdateNotifyEnabled *bool `json:"upstream_model_update_notify_enabled,omitempty"`
  1006. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  1007. RecordIpLog bool `json:"record_ip_log"`
  1008. }
  1009. func UpdateUserSetting(c *gin.Context) {
  1010. var req UpdateUserSettingRequest
  1011. if err := c.ShouldBindJSON(&req); err != nil {
  1012. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  1013. return
  1014. }
  1015. // 验证预警类型
  1016. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark && req.QuotaWarningType != dto.NotifyTypeGotify {
  1017. common.ApiErrorI18n(c, i18n.MsgSettingInvalidType)
  1018. return
  1019. }
  1020. // 验证预警阈值
  1021. if req.QuotaWarningThreshold <= 0 {
  1022. common.ApiErrorI18n(c, i18n.MsgQuotaThresholdGtZero)
  1023. return
  1024. }
  1025. // 如果是webhook类型,验证webhook地址
  1026. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1027. if req.WebhookUrl == "" {
  1028. common.ApiErrorI18n(c, i18n.MsgSettingWebhookEmpty)
  1029. return
  1030. }
  1031. // 验证URL格式
  1032. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  1033. common.ApiErrorI18n(c, i18n.MsgSettingWebhookInvalid)
  1034. return
  1035. }
  1036. }
  1037. // 如果是邮件类型,验证邮箱地址
  1038. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1039. // 验证邮箱格式
  1040. if !strings.Contains(req.NotificationEmail, "@") {
  1041. common.ApiErrorI18n(c, i18n.MsgSettingEmailInvalid)
  1042. return
  1043. }
  1044. }
  1045. // 如果是Bark类型,验证Bark URL
  1046. if req.QuotaWarningType == dto.NotifyTypeBark {
  1047. if req.BarkUrl == "" {
  1048. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlEmpty)
  1049. return
  1050. }
  1051. // 验证URL格式
  1052. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  1053. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlInvalid)
  1054. return
  1055. }
  1056. // 检查是否是HTTP或HTTPS
  1057. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  1058. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1059. return
  1060. }
  1061. }
  1062. // 如果是Gotify类型,验证Gotify URL和Token
  1063. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1064. if req.GotifyUrl == "" {
  1065. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlEmpty)
  1066. return
  1067. }
  1068. if req.GotifyToken == "" {
  1069. common.ApiErrorI18n(c, i18n.MsgSettingGotifyTokenEmpty)
  1070. return
  1071. }
  1072. // 验证URL格式
  1073. if _, err := url.ParseRequestURI(req.GotifyUrl); err != nil {
  1074. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlInvalid)
  1075. return
  1076. }
  1077. // 检查是否是HTTP或HTTPS
  1078. if !strings.HasPrefix(req.GotifyUrl, "https://") && !strings.HasPrefix(req.GotifyUrl, "http://") {
  1079. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1080. return
  1081. }
  1082. }
  1083. userId := c.GetInt("id")
  1084. user, err := model.GetUserById(userId, true)
  1085. if err != nil {
  1086. common.ApiError(c, err)
  1087. return
  1088. }
  1089. existingSettings := user.GetSetting()
  1090. upstreamModelUpdateNotifyEnabled := existingSettings.UpstreamModelUpdateNotifyEnabled
  1091. if user.Role >= common.RoleAdminUser && req.UpstreamModelUpdateNotifyEnabled != nil {
  1092. upstreamModelUpdateNotifyEnabled = *req.UpstreamModelUpdateNotifyEnabled
  1093. }
  1094. // 构建设置
  1095. settings := dto.UserSetting{
  1096. NotifyType: req.QuotaWarningType,
  1097. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1098. UpstreamModelUpdateNotifyEnabled: upstreamModelUpdateNotifyEnabled,
  1099. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1100. RecordIpLog: req.RecordIpLog,
  1101. }
  1102. // 如果是webhook类型,添加webhook相关设置
  1103. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1104. settings.WebhookUrl = req.WebhookUrl
  1105. if req.WebhookSecret != "" {
  1106. settings.WebhookSecret = req.WebhookSecret
  1107. }
  1108. }
  1109. // 如果提供了通知邮箱,添加到设置中
  1110. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1111. settings.NotificationEmail = req.NotificationEmail
  1112. }
  1113. // 如果是Bark类型,添加Bark URL到设置中
  1114. if req.QuotaWarningType == dto.NotifyTypeBark {
  1115. settings.BarkUrl = req.BarkUrl
  1116. }
  1117. // 如果是Gotify类型,添加Gotify配置到设置中
  1118. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1119. settings.GotifyUrl = req.GotifyUrl
  1120. settings.GotifyToken = req.GotifyToken
  1121. // Gotify优先级范围0-10,超出范围则使用默认值5
  1122. if req.GotifyPriority < 0 || req.GotifyPriority > 10 {
  1123. settings.GotifyPriority = 5
  1124. } else {
  1125. settings.GotifyPriority = req.GotifyPriority
  1126. }
  1127. }
  1128. // 更新用户设置
  1129. user.SetSetting(settings)
  1130. if err := user.Update(false); err != nil {
  1131. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  1132. return
  1133. }
  1134. common.ApiSuccessI18n(c, i18n.MsgSettingSaved, nil)
  1135. }