user.go 31 KB

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