user.go 31 KB

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