user.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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. if originUser.Quota != updatedUser.Quota {
  532. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", logger.LogQuota(originUser.Quota), logger.LogQuota(updatedUser.Quota)))
  533. }
  534. c.JSON(http.StatusOK, gin.H{
  535. "success": true,
  536. "message": "",
  537. })
  538. return
  539. }
  540. func AdminClearUserBinding(c *gin.Context) {
  541. id, err := strconv.Atoi(c.Param("id"))
  542. if err != nil {
  543. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  544. return
  545. }
  546. bindingType := strings.ToLower(strings.TrimSpace(c.Param("binding_type")))
  547. if bindingType == "" {
  548. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  549. return
  550. }
  551. user, err := model.GetUserById(id, false)
  552. if err != nil {
  553. common.ApiError(c, err)
  554. return
  555. }
  556. myRole := c.GetInt("role")
  557. if myRole <= user.Role && myRole != common.RoleRootUser {
  558. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
  559. return
  560. }
  561. if err := user.ClearBinding(bindingType); err != nil {
  562. common.ApiError(c, err)
  563. return
  564. }
  565. model.RecordLog(user.Id, model.LogTypeManage, fmt.Sprintf("admin cleared %s binding for user %s", bindingType, user.Username))
  566. c.JSON(http.StatusOK, gin.H{
  567. "success": true,
  568. "message": "success",
  569. })
  570. }
  571. func UpdateSelf(c *gin.Context) {
  572. var requestData map[string]interface{}
  573. err := json.NewDecoder(c.Request.Body).Decode(&requestData)
  574. if err != nil {
  575. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  576. return
  577. }
  578. // 检查是否是用户设置更新请求 (sidebar_modules 或 language)
  579. if sidebarModules, sidebarExists := requestData["sidebar_modules"]; sidebarExists {
  580. userId := c.GetInt("id")
  581. user, err := model.GetUserById(userId, false)
  582. if err != nil {
  583. common.ApiError(c, err)
  584. return
  585. }
  586. // 获取当前用户设置
  587. currentSetting := user.GetSetting()
  588. // 更新sidebar_modules字段
  589. if sidebarModulesStr, ok := sidebarModules.(string); ok {
  590. currentSetting.SidebarModules = sidebarModulesStr
  591. }
  592. // 保存更新后的设置
  593. user.SetSetting(currentSetting)
  594. if err := user.Update(false); err != nil {
  595. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  596. return
  597. }
  598. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  599. return
  600. }
  601. // 检查是否是语言偏好更新请求
  602. if language, langExists := requestData["language"]; langExists {
  603. userId := c.GetInt("id")
  604. user, err := model.GetUserById(userId, false)
  605. if err != nil {
  606. common.ApiError(c, err)
  607. return
  608. }
  609. // 获取当前用户设置
  610. currentSetting := user.GetSetting()
  611. // 更新language字段
  612. if langStr, ok := language.(string); ok {
  613. currentSetting.Language = langStr
  614. }
  615. // 保存更新后的设置
  616. user.SetSetting(currentSetting)
  617. if err := user.Update(false); err != nil {
  618. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  619. return
  620. }
  621. common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
  622. return
  623. }
  624. // 原有的用户信息更新逻辑
  625. var user model.User
  626. requestDataBytes, err := json.Marshal(requestData)
  627. if err != nil {
  628. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  629. return
  630. }
  631. err = json.Unmarshal(requestDataBytes, &user)
  632. if err != nil {
  633. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  634. return
  635. }
  636. if user.Password == "" {
  637. user.Password = "$I_LOVE_U" // make Validator happy :)
  638. }
  639. if err := common.Validate.Struct(&user); err != nil {
  640. common.ApiErrorI18n(c, i18n.MsgInvalidInput)
  641. return
  642. }
  643. cleanUser := model.User{
  644. Id: c.GetInt("id"),
  645. Username: user.Username,
  646. Password: user.Password,
  647. DisplayName: user.DisplayName,
  648. }
  649. if user.Password == "$I_LOVE_U" {
  650. user.Password = "" // rollback to what it should be
  651. cleanUser.Password = ""
  652. }
  653. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  654. if err != nil {
  655. common.ApiError(c, err)
  656. return
  657. }
  658. if err := cleanUser.Update(updatePassword); err != nil {
  659. common.ApiError(c, err)
  660. return
  661. }
  662. c.JSON(http.StatusOK, gin.H{
  663. "success": true,
  664. "message": "",
  665. })
  666. return
  667. }
  668. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  669. var currentUser *model.User
  670. currentUser, err = model.GetUserById(userId, true)
  671. if err != nil {
  672. return
  673. }
  674. // 密码不为空,需要验证原密码
  675. // 支持第一次账号绑定时原密码为空的情况
  676. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) && currentUser.Password != "" {
  677. err = fmt.Errorf("原密码错误")
  678. return
  679. }
  680. if newPassword == "" {
  681. return
  682. }
  683. updatePassword = true
  684. return
  685. }
  686. func DeleteUser(c *gin.Context) {
  687. id, err := strconv.Atoi(c.Param("id"))
  688. if err != nil {
  689. common.ApiError(c, err)
  690. return
  691. }
  692. originUser, err := model.GetUserById(id, false)
  693. if err != nil {
  694. common.ApiError(c, err)
  695. return
  696. }
  697. myRole := c.GetInt("role")
  698. if myRole <= originUser.Role {
  699. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  700. return
  701. }
  702. err = model.HardDeleteUserById(id)
  703. if err != nil {
  704. c.JSON(http.StatusOK, gin.H{
  705. "success": true,
  706. "message": "",
  707. })
  708. return
  709. }
  710. }
  711. func DeleteSelf(c *gin.Context) {
  712. id := c.GetInt("id")
  713. user, _ := model.GetUserById(id, false)
  714. if user.Role == common.RoleRootUser {
  715. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  716. return
  717. }
  718. err := model.DeleteUserById(id)
  719. if err != nil {
  720. common.ApiError(c, err)
  721. return
  722. }
  723. c.JSON(http.StatusOK, gin.H{
  724. "success": true,
  725. "message": "",
  726. })
  727. return
  728. }
  729. func CreateUser(c *gin.Context) {
  730. var user model.User
  731. err := json.NewDecoder(c.Request.Body).Decode(&user)
  732. user.Username = strings.TrimSpace(user.Username)
  733. if err != nil || user.Username == "" || user.Password == "" {
  734. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  735. return
  736. }
  737. if err := common.Validate.Struct(&user); err != nil {
  738. common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
  739. return
  740. }
  741. if user.DisplayName == "" {
  742. user.DisplayName = user.Username
  743. }
  744. myRole := c.GetInt("role")
  745. if user.Role >= myRole {
  746. common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
  747. return
  748. }
  749. // Even for admin users, we cannot fully trust them!
  750. cleanUser := model.User{
  751. Username: user.Username,
  752. Password: user.Password,
  753. DisplayName: user.DisplayName,
  754. Role: user.Role, // 保持管理员设置的角色
  755. }
  756. if err := cleanUser.Insert(0); err != nil {
  757. common.ApiError(c, err)
  758. return
  759. }
  760. c.JSON(http.StatusOK, gin.H{
  761. "success": true,
  762. "message": "",
  763. })
  764. return
  765. }
  766. type ManageRequest struct {
  767. Id int `json:"id"`
  768. Action string `json:"action"`
  769. }
  770. // ManageUser Only admin user can do this
  771. func ManageUser(c *gin.Context) {
  772. var req ManageRequest
  773. err := json.NewDecoder(c.Request.Body).Decode(&req)
  774. if err != nil {
  775. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  776. return
  777. }
  778. user := model.User{
  779. Id: req.Id,
  780. }
  781. // Fill attributes
  782. model.DB.Unscoped().Where(&user).First(&user)
  783. if user.Id == 0 {
  784. common.ApiErrorI18n(c, i18n.MsgUserNotExists)
  785. return
  786. }
  787. myRole := c.GetInt("role")
  788. if myRole <= user.Role && myRole != common.RoleRootUser {
  789. common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
  790. return
  791. }
  792. switch req.Action {
  793. case "disable":
  794. user.Status = common.UserStatusDisabled
  795. if user.Role == common.RoleRootUser {
  796. common.ApiErrorI18n(c, i18n.MsgUserCannotDisableRootUser)
  797. return
  798. }
  799. case "enable":
  800. user.Status = common.UserStatusEnabled
  801. case "delete":
  802. if user.Role == common.RoleRootUser {
  803. common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
  804. return
  805. }
  806. if err := user.Delete(); err != nil {
  807. c.JSON(http.StatusOK, gin.H{
  808. "success": false,
  809. "message": err.Error(),
  810. })
  811. return
  812. }
  813. case "promote":
  814. if myRole != common.RoleRootUser {
  815. common.ApiErrorI18n(c, i18n.MsgUserAdminCannotPromote)
  816. return
  817. }
  818. if user.Role >= common.RoleAdminUser {
  819. common.ApiErrorI18n(c, i18n.MsgUserAlreadyAdmin)
  820. return
  821. }
  822. user.Role = common.RoleAdminUser
  823. case "demote":
  824. if user.Role == common.RoleRootUser {
  825. common.ApiErrorI18n(c, i18n.MsgUserCannotDemoteRootUser)
  826. return
  827. }
  828. if user.Role == common.RoleCommonUser {
  829. common.ApiErrorI18n(c, i18n.MsgUserAlreadyCommon)
  830. return
  831. }
  832. user.Role = common.RoleCommonUser
  833. }
  834. if err := user.Update(false); err != nil {
  835. common.ApiError(c, err)
  836. return
  837. }
  838. clearUser := model.User{
  839. Role: user.Role,
  840. Status: user.Status,
  841. }
  842. c.JSON(http.StatusOK, gin.H{
  843. "success": true,
  844. "message": "",
  845. "data": clearUser,
  846. })
  847. return
  848. }
  849. func EmailBind(c *gin.Context) {
  850. email := c.Query("email")
  851. code := c.Query("code")
  852. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  853. common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
  854. return
  855. }
  856. session := sessions.Default(c)
  857. id := session.Get("id")
  858. user := model.User{
  859. Id: id.(int),
  860. }
  861. err := user.FillUserById()
  862. if err != nil {
  863. common.ApiError(c, err)
  864. return
  865. }
  866. user.Email = email
  867. // no need to check if this email already taken, because we have used verification code to check it
  868. err = user.Update(false)
  869. if err != nil {
  870. common.ApiError(c, err)
  871. return
  872. }
  873. c.JSON(http.StatusOK, gin.H{
  874. "success": true,
  875. "message": "",
  876. })
  877. return
  878. }
  879. type topUpRequest struct {
  880. Key string `json:"key"`
  881. }
  882. var topUpLocks sync.Map
  883. var topUpCreateLock sync.Mutex
  884. type topUpTryLock struct {
  885. ch chan struct{}
  886. }
  887. func newTopUpTryLock() *topUpTryLock {
  888. return &topUpTryLock{ch: make(chan struct{}, 1)}
  889. }
  890. func (l *topUpTryLock) TryLock() bool {
  891. select {
  892. case l.ch <- struct{}{}:
  893. return true
  894. default:
  895. return false
  896. }
  897. }
  898. func (l *topUpTryLock) Unlock() {
  899. select {
  900. case <-l.ch:
  901. default:
  902. }
  903. }
  904. func getTopUpLock(userID int) *topUpTryLock {
  905. if v, ok := topUpLocks.Load(userID); ok {
  906. return v.(*topUpTryLock)
  907. }
  908. topUpCreateLock.Lock()
  909. defer topUpCreateLock.Unlock()
  910. if v, ok := topUpLocks.Load(userID); ok {
  911. return v.(*topUpTryLock)
  912. }
  913. l := newTopUpTryLock()
  914. topUpLocks.Store(userID, l)
  915. return l
  916. }
  917. func TopUp(c *gin.Context) {
  918. id := c.GetInt("id")
  919. lock := getTopUpLock(id)
  920. if !lock.TryLock() {
  921. common.ApiErrorI18n(c, i18n.MsgUserTopUpProcessing)
  922. return
  923. }
  924. defer lock.Unlock()
  925. req := topUpRequest{}
  926. err := c.ShouldBindJSON(&req)
  927. if err != nil {
  928. common.ApiError(c, err)
  929. return
  930. }
  931. quota, err := model.Redeem(req.Key, id)
  932. if err != nil {
  933. if errors.Is(err, model.ErrRedeemFailed) {
  934. common.ApiErrorI18n(c, i18n.MsgRedeemFailed)
  935. return
  936. }
  937. common.ApiError(c, err)
  938. return
  939. }
  940. c.JSON(http.StatusOK, gin.H{
  941. "success": true,
  942. "message": "",
  943. "data": quota,
  944. })
  945. }
  946. type UpdateUserSettingRequest struct {
  947. QuotaWarningType string `json:"notify_type"`
  948. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  949. WebhookUrl string `json:"webhook_url,omitempty"`
  950. WebhookSecret string `json:"webhook_secret,omitempty"`
  951. NotificationEmail string `json:"notification_email,omitempty"`
  952. BarkUrl string `json:"bark_url,omitempty"`
  953. GotifyUrl string `json:"gotify_url,omitempty"`
  954. GotifyToken string `json:"gotify_token,omitempty"`
  955. GotifyPriority int `json:"gotify_priority,omitempty"`
  956. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  957. RecordIpLog bool `json:"record_ip_log"`
  958. }
  959. func UpdateUserSetting(c *gin.Context) {
  960. var req UpdateUserSettingRequest
  961. if err := c.ShouldBindJSON(&req); err != nil {
  962. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  963. return
  964. }
  965. // 验证预警类型
  966. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark && req.QuotaWarningType != dto.NotifyTypeGotify {
  967. common.ApiErrorI18n(c, i18n.MsgSettingInvalidType)
  968. return
  969. }
  970. // 验证预警阈值
  971. if req.QuotaWarningThreshold <= 0 {
  972. common.ApiErrorI18n(c, i18n.MsgQuotaThresholdGtZero)
  973. return
  974. }
  975. // 如果是webhook类型,验证webhook地址
  976. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  977. if req.WebhookUrl == "" {
  978. common.ApiErrorI18n(c, i18n.MsgSettingWebhookEmpty)
  979. return
  980. }
  981. // 验证URL格式
  982. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  983. common.ApiErrorI18n(c, i18n.MsgSettingWebhookInvalid)
  984. return
  985. }
  986. }
  987. // 如果是邮件类型,验证邮箱地址
  988. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  989. // 验证邮箱格式
  990. if !strings.Contains(req.NotificationEmail, "@") {
  991. common.ApiErrorI18n(c, i18n.MsgSettingEmailInvalid)
  992. return
  993. }
  994. }
  995. // 如果是Bark类型,验证Bark URL
  996. if req.QuotaWarningType == dto.NotifyTypeBark {
  997. if req.BarkUrl == "" {
  998. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlEmpty)
  999. return
  1000. }
  1001. // 验证URL格式
  1002. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  1003. common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlInvalid)
  1004. return
  1005. }
  1006. // 检查是否是HTTP或HTTPS
  1007. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  1008. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1009. return
  1010. }
  1011. }
  1012. // 如果是Gotify类型,验证Gotify URL和Token
  1013. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1014. if req.GotifyUrl == "" {
  1015. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlEmpty)
  1016. return
  1017. }
  1018. if req.GotifyToken == "" {
  1019. common.ApiErrorI18n(c, i18n.MsgSettingGotifyTokenEmpty)
  1020. return
  1021. }
  1022. // 验证URL格式
  1023. if _, err := url.ParseRequestURI(req.GotifyUrl); err != nil {
  1024. common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlInvalid)
  1025. return
  1026. }
  1027. // 检查是否是HTTP或HTTPS
  1028. if !strings.HasPrefix(req.GotifyUrl, "https://") && !strings.HasPrefix(req.GotifyUrl, "http://") {
  1029. common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
  1030. return
  1031. }
  1032. }
  1033. userId := c.GetInt("id")
  1034. user, err := model.GetUserById(userId, true)
  1035. if err != nil {
  1036. common.ApiError(c, err)
  1037. return
  1038. }
  1039. // 构建设置
  1040. settings := dto.UserSetting{
  1041. NotifyType: req.QuotaWarningType,
  1042. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1043. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1044. RecordIpLog: req.RecordIpLog,
  1045. }
  1046. // 如果是webhook类型,添加webhook相关设置
  1047. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1048. settings.WebhookUrl = req.WebhookUrl
  1049. if req.WebhookSecret != "" {
  1050. settings.WebhookSecret = req.WebhookSecret
  1051. }
  1052. }
  1053. // 如果提供了通知邮箱,添加到设置中
  1054. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1055. settings.NotificationEmail = req.NotificationEmail
  1056. }
  1057. // 如果是Bark类型,添加Bark URL到设置中
  1058. if req.QuotaWarningType == dto.NotifyTypeBark {
  1059. settings.BarkUrl = req.BarkUrl
  1060. }
  1061. // 如果是Gotify类型,添加Gotify配置到设置中
  1062. if req.QuotaWarningType == dto.NotifyTypeGotify {
  1063. settings.GotifyUrl = req.GotifyUrl
  1064. settings.GotifyToken = req.GotifyToken
  1065. // Gotify优先级范围0-10,超出范围则使用默认值5
  1066. if req.GotifyPriority < 0 || req.GotifyPriority > 10 {
  1067. settings.GotifyPriority = 5
  1068. } else {
  1069. settings.GotifyPriority = req.GotifyPriority
  1070. }
  1071. }
  1072. // 更新用户设置
  1073. user.SetSetting(settings)
  1074. if err := user.Update(false); err != nil {
  1075. common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
  1076. return
  1077. }
  1078. common.ApiSuccessI18n(c, i18n.MsgSettingSaved, nil)
  1079. }