user.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "one-api/common"
  8. "one-api/dto"
  9. "one-api/logger"
  10. "one-api/model"
  11. "one-api/setting"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "one-api/constant"
  16. "github.com/gin-contrib/sessions"
  17. "github.com/gin-gonic/gin"
  18. )
  19. type LoginRequest struct {
  20. Username string `json:"username"`
  21. Password string `json:"password"`
  22. }
  23. func Login(c *gin.Context) {
  24. if !common.PasswordLoginEnabled {
  25. c.JSON(http.StatusOK, gin.H{
  26. "message": "管理员关闭了密码登录",
  27. "success": false,
  28. })
  29. return
  30. }
  31. var loginRequest LoginRequest
  32. err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
  33. if err != nil {
  34. c.JSON(http.StatusOK, gin.H{
  35. "message": "无效的参数",
  36. "success": false,
  37. })
  38. return
  39. }
  40. username := loginRequest.Username
  41. password := loginRequest.Password
  42. if username == "" || password == "" {
  43. c.JSON(http.StatusOK, gin.H{
  44. "message": "无效的参数",
  45. "success": false,
  46. })
  47. return
  48. }
  49. user := model.User{
  50. Username: username,
  51. Password: password,
  52. }
  53. err = user.ValidateAndFill()
  54. if err != nil {
  55. c.JSON(http.StatusOK, gin.H{
  56. "message": err.Error(),
  57. "success": false,
  58. })
  59. return
  60. }
  61. // 检查是否启用2FA
  62. if model.IsTwoFAEnabled(user.Id) {
  63. // 设置pending session,等待2FA验证
  64. session := sessions.Default(c)
  65. session.Set("pending_username", user.Username)
  66. session.Set("pending_user_id", user.Id)
  67. err := session.Save()
  68. if err != nil {
  69. c.JSON(http.StatusOK, gin.H{
  70. "message": "无法保存会话信息,请重试",
  71. "success": false,
  72. })
  73. return
  74. }
  75. c.JSON(http.StatusOK, gin.H{
  76. "message": "请输入两步验证码",
  77. "success": true,
  78. "data": map[string]interface{}{
  79. "require_2fa": true,
  80. },
  81. })
  82. return
  83. }
  84. setupLogin(&user, c)
  85. }
  86. // setup session & cookies and then return user info
  87. func setupLogin(user *model.User, c *gin.Context) {
  88. session := sessions.Default(c)
  89. session.Set("id", user.Id)
  90. session.Set("username", user.Username)
  91. session.Set("role", user.Role)
  92. session.Set("status", user.Status)
  93. session.Set("group", user.Group)
  94. err := session.Save()
  95. if err != nil {
  96. c.JSON(http.StatusOK, gin.H{
  97. "message": "无法保存会话信息,请重试",
  98. "success": false,
  99. })
  100. return
  101. }
  102. cleanUser := model.User{
  103. Id: user.Id,
  104. Username: user.Username,
  105. DisplayName: user.DisplayName,
  106. Role: user.Role,
  107. Status: user.Status,
  108. Group: user.Group,
  109. }
  110. c.JSON(http.StatusOK, gin.H{
  111. "message": "",
  112. "success": true,
  113. "data": cleanUser,
  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. "group": user.Group,
  424. "quota": user.Quota,
  425. "used_quota": user.UsedQuota,
  426. "request_count": user.RequestCount,
  427. "aff_code": user.AffCode,
  428. "aff_count": user.AffCount,
  429. "aff_quota": user.AffQuota,
  430. "aff_history_quota": user.AffHistoryQuota,
  431. "inviter_id": user.InviterId,
  432. "linux_do_id": user.LinuxDOId,
  433. "setting": user.Setting,
  434. "stripe_customer": user.StripeCustomer,
  435. "sidebar_modules": userSetting.SidebarModules, // 正确提取sidebar_modules字段
  436. "permissions": permissions, // 新增权限字段
  437. }
  438. c.JSON(http.StatusOK, gin.H{
  439. "success": true,
  440. "message": "",
  441. "data": responseData,
  442. })
  443. return
  444. }
  445. // 计算用户权限的辅助函数
  446. func calculateUserPermissions(userRole int) map[string]interface{} {
  447. permissions := map[string]interface{}{}
  448. // 根据用户角色计算权限
  449. if userRole == common.RoleRootUser {
  450. // 超级管理员不需要边栏设置功能
  451. permissions["sidebar_settings"] = false
  452. permissions["sidebar_modules"] = map[string]interface{}{}
  453. } else if userRole == common.RoleAdminUser {
  454. // 管理员可以设置边栏,但不包含系统设置功能
  455. permissions["sidebar_settings"] = true
  456. permissions["sidebar_modules"] = map[string]interface{}{
  457. "admin": map[string]interface{}{
  458. "setting": false, // 管理员不能访问系统设置
  459. },
  460. }
  461. } else {
  462. // 普通用户只能设置个人功能,不包含管理员区域
  463. permissions["sidebar_settings"] = true
  464. permissions["sidebar_modules"] = map[string]interface{}{
  465. "admin": false, // 普通用户不能访问管理员区域
  466. }
  467. }
  468. return permissions
  469. }
  470. // 根据用户角色生成默认的边栏配置
  471. func generateDefaultSidebarConfig(userRole int) string {
  472. defaultConfig := map[string]interface{}{}
  473. // 聊天区域 - 所有用户都可以访问
  474. defaultConfig["chat"] = map[string]interface{}{
  475. "enabled": true,
  476. "playground": true,
  477. "chat": true,
  478. }
  479. // 控制台区域 - 所有用户都可以访问
  480. defaultConfig["console"] = map[string]interface{}{
  481. "enabled": true,
  482. "detail": true,
  483. "token": true,
  484. "log": true,
  485. "midjourney": true,
  486. "task": true,
  487. }
  488. // 个人中心区域 - 所有用户都可以访问
  489. defaultConfig["personal"] = map[string]interface{}{
  490. "enabled": true,
  491. "topup": true,
  492. "personal": true,
  493. }
  494. // 管理员区域 - 根据角色决定
  495. if userRole == common.RoleAdminUser {
  496. // 管理员可以访问管理员区域,但不能访问系统设置
  497. defaultConfig["admin"] = map[string]interface{}{
  498. "enabled": true,
  499. "channel": true,
  500. "models": true,
  501. "redemption": true,
  502. "user": true,
  503. "setting": false, // 管理员不能访问系统设置
  504. }
  505. } else if userRole == common.RoleRootUser {
  506. // 超级管理员可以访问所有功能
  507. defaultConfig["admin"] = map[string]interface{}{
  508. "enabled": true,
  509. "channel": true,
  510. "models": true,
  511. "redemption": true,
  512. "user": true,
  513. "setting": true,
  514. }
  515. }
  516. // 普通用户不包含admin区域
  517. // 转换为JSON字符串
  518. configBytes, err := json.Marshal(defaultConfig)
  519. if err != nil {
  520. common.SysLog("生成默认边栏配置失败: " + err.Error())
  521. return ""
  522. }
  523. return string(configBytes)
  524. }
  525. func GetUserModels(c *gin.Context) {
  526. id, err := strconv.Atoi(c.Param("id"))
  527. if err != nil {
  528. id = c.GetInt("id")
  529. }
  530. user, err := model.GetUserCache(id)
  531. if err != nil {
  532. common.ApiError(c, err)
  533. return
  534. }
  535. groups := setting.GetUserUsableGroups(user.Group)
  536. var models []string
  537. for group := range groups {
  538. for _, g := range model.GetGroupEnabledModels(group) {
  539. if !common.StringsContains(models, g) {
  540. models = append(models, g)
  541. }
  542. }
  543. }
  544. c.JSON(http.StatusOK, gin.H{
  545. "success": true,
  546. "message": "",
  547. "data": models,
  548. })
  549. return
  550. }
  551. func UpdateUser(c *gin.Context) {
  552. var updatedUser model.User
  553. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  554. if err != nil || updatedUser.Id == 0 {
  555. c.JSON(http.StatusOK, gin.H{
  556. "success": false,
  557. "message": "无效的参数",
  558. })
  559. return
  560. }
  561. if updatedUser.Password == "" {
  562. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  563. }
  564. if err := common.Validate.Struct(&updatedUser); err != nil {
  565. c.JSON(http.StatusOK, gin.H{
  566. "success": false,
  567. "message": "输入不合法 " + err.Error(),
  568. })
  569. return
  570. }
  571. originUser, err := model.GetUserById(updatedUser.Id, false)
  572. if err != nil {
  573. common.ApiError(c, err)
  574. return
  575. }
  576. myRole := c.GetInt("role")
  577. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  578. c.JSON(http.StatusOK, gin.H{
  579. "success": false,
  580. "message": "无权更新同权限等级或更高权限等级的用户信息",
  581. })
  582. return
  583. }
  584. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": false,
  587. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  588. })
  589. return
  590. }
  591. if updatedUser.Password == "$I_LOVE_U" {
  592. updatedUser.Password = "" // rollback to what it should be
  593. }
  594. updatePassword := updatedUser.Password != ""
  595. if err := updatedUser.Edit(updatePassword); err != nil {
  596. common.ApiError(c, err)
  597. return
  598. }
  599. if originUser.Quota != updatedUser.Quota {
  600. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", logger.LogQuota(originUser.Quota), logger.LogQuota(updatedUser.Quota)))
  601. }
  602. c.JSON(http.StatusOK, gin.H{
  603. "success": true,
  604. "message": "",
  605. })
  606. return
  607. }
  608. func UpdateSelf(c *gin.Context) {
  609. var requestData map[string]interface{}
  610. err := json.NewDecoder(c.Request.Body).Decode(&requestData)
  611. if err != nil {
  612. c.JSON(http.StatusOK, gin.H{
  613. "success": false,
  614. "message": "无效的参数",
  615. })
  616. return
  617. }
  618. // 检查是否是sidebar_modules更新请求
  619. if sidebarModules, exists := requestData["sidebar_modules"]; exists {
  620. userId := c.GetInt("id")
  621. userRole := c.GetInt("role")
  622. // 注意超级管理员目前在 calculateUserPermissions 中被设置为无权更新设置
  623. perms := calculateUserPermissions(userRole)
  624. allow, ok := perms["sidebar_settings"]
  625. if !ok {
  626. c.JSON(http.StatusOK, gin.H{
  627. "success": false,
  628. "message": "无权更新设置",
  629. })
  630. return
  631. }
  632. allowBool, ok := allow.(bool)
  633. if !ok || !allowBool {
  634. c.JSON(http.StatusOK, gin.H{
  635. "success": false,
  636. "message": "无权更新设置",
  637. })
  638. return
  639. }
  640. user, err := model.GetUserById(userId, false)
  641. if err != nil {
  642. common.ApiError(c, err)
  643. return
  644. }
  645. // 获取当前用户设置
  646. currentSetting := user.GetSetting()
  647. // 更新sidebar_modules字段
  648. if sidebarModulesStr, ok := sidebarModules.(string); ok {
  649. currentSetting.SidebarModules = sidebarModulesStr
  650. }
  651. // 保存更新后的设置
  652. user.SetSetting(currentSetting)
  653. if err := user.Update(false); err != nil {
  654. c.JSON(http.StatusOK, gin.H{
  655. "success": false,
  656. "message": "更新设置失败: " + err.Error(),
  657. })
  658. return
  659. }
  660. c.JSON(http.StatusOK, gin.H{
  661. "success": true,
  662. "message": "设置更新成功",
  663. })
  664. return
  665. }
  666. // 原有的用户信息更新逻辑
  667. var user model.User
  668. requestDataBytes, err := json.Marshal(requestData)
  669. if err != nil {
  670. c.JSON(http.StatusOK, gin.H{
  671. "success": false,
  672. "message": "无效的参数",
  673. })
  674. return
  675. }
  676. err = json.Unmarshal(requestDataBytes, &user)
  677. if err != nil {
  678. c.JSON(http.StatusOK, gin.H{
  679. "success": false,
  680. "message": "无效的参数",
  681. })
  682. return
  683. }
  684. if user.Password == "" {
  685. user.Password = "$I_LOVE_U" // make Validator happy :)
  686. }
  687. if err := common.Validate.Struct(&user); err != nil {
  688. c.JSON(http.StatusOK, gin.H{
  689. "success": false,
  690. "message": "输入不合法 " + err.Error(),
  691. })
  692. return
  693. }
  694. cleanUser := model.User{
  695. Id: c.GetInt("id"),
  696. Username: user.Username,
  697. Password: user.Password,
  698. DisplayName: user.DisplayName,
  699. }
  700. if user.Password == "$I_LOVE_U" {
  701. user.Password = "" // rollback to what it should be
  702. cleanUser.Password = ""
  703. }
  704. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  705. if err != nil {
  706. common.ApiError(c, err)
  707. return
  708. }
  709. if err := cleanUser.Update(updatePassword); err != nil {
  710. common.ApiError(c, err)
  711. return
  712. }
  713. c.JSON(http.StatusOK, gin.H{
  714. "success": true,
  715. "message": "",
  716. })
  717. return
  718. }
  719. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  720. var currentUser *model.User
  721. currentUser, err = model.GetUserById(userId, true)
  722. if err != nil {
  723. return
  724. }
  725. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) {
  726. err = fmt.Errorf("原密码错误")
  727. return
  728. }
  729. if newPassword == "" {
  730. return
  731. }
  732. updatePassword = true
  733. return
  734. }
  735. func DeleteUser(c *gin.Context) {
  736. id, err := strconv.Atoi(c.Param("id"))
  737. if err != nil {
  738. common.ApiError(c, err)
  739. return
  740. }
  741. originUser, err := model.GetUserById(id, false)
  742. if err != nil {
  743. common.ApiError(c, err)
  744. return
  745. }
  746. myRole := c.GetInt("role")
  747. if myRole <= originUser.Role {
  748. c.JSON(http.StatusOK, gin.H{
  749. "success": false,
  750. "message": "无权删除同权限等级或更高权限等级的用户",
  751. })
  752. return
  753. }
  754. err = model.HardDeleteUserById(id)
  755. if err != nil {
  756. c.JSON(http.StatusOK, gin.H{
  757. "success": true,
  758. "message": "",
  759. })
  760. return
  761. }
  762. }
  763. func DeleteSelf(c *gin.Context) {
  764. id := c.GetInt("id")
  765. user, _ := model.GetUserById(id, false)
  766. if user.Role == common.RoleRootUser {
  767. c.JSON(http.StatusOK, gin.H{
  768. "success": false,
  769. "message": "不能删除超级管理员账户",
  770. })
  771. return
  772. }
  773. err := model.DeleteUserById(id)
  774. if err != nil {
  775. common.ApiError(c, err)
  776. return
  777. }
  778. c.JSON(http.StatusOK, gin.H{
  779. "success": true,
  780. "message": "",
  781. })
  782. return
  783. }
  784. func CreateUser(c *gin.Context) {
  785. var user model.User
  786. err := json.NewDecoder(c.Request.Body).Decode(&user)
  787. user.Username = strings.TrimSpace(user.Username)
  788. if err != nil || user.Username == "" || user.Password == "" {
  789. c.JSON(http.StatusOK, gin.H{
  790. "success": false,
  791. "message": "无效的参数",
  792. })
  793. return
  794. }
  795. if err := common.Validate.Struct(&user); err != nil {
  796. c.JSON(http.StatusOK, gin.H{
  797. "success": false,
  798. "message": "输入不合法 " + err.Error(),
  799. })
  800. return
  801. }
  802. if user.DisplayName == "" {
  803. user.DisplayName = user.Username
  804. }
  805. myRole := c.GetInt("role")
  806. if user.Role >= myRole {
  807. c.JSON(http.StatusOK, gin.H{
  808. "success": false,
  809. "message": "无法创建权限大于等于自己的用户",
  810. })
  811. return
  812. }
  813. // Even for admin users, we cannot fully trust them!
  814. cleanUser := model.User{
  815. Username: user.Username,
  816. Password: user.Password,
  817. DisplayName: user.DisplayName,
  818. Role: user.Role, // 保持管理员设置的角色
  819. }
  820. if err := cleanUser.Insert(0); err != nil {
  821. common.ApiError(c, err)
  822. return
  823. }
  824. c.JSON(http.StatusOK, gin.H{
  825. "success": true,
  826. "message": "",
  827. })
  828. return
  829. }
  830. type ManageRequest struct {
  831. Id int `json:"id"`
  832. Action string `json:"action"`
  833. }
  834. // ManageUser Only admin user can do this
  835. func ManageUser(c *gin.Context) {
  836. var req ManageRequest
  837. err := json.NewDecoder(c.Request.Body).Decode(&req)
  838. if err != nil {
  839. c.JSON(http.StatusOK, gin.H{
  840. "success": false,
  841. "message": "无效的参数",
  842. })
  843. return
  844. }
  845. user := model.User{
  846. Id: req.Id,
  847. }
  848. // Fill attributes
  849. model.DB.Unscoped().Where(&user).First(&user)
  850. if user.Id == 0 {
  851. c.JSON(http.StatusOK, gin.H{
  852. "success": false,
  853. "message": "用户不存在",
  854. })
  855. return
  856. }
  857. myRole := c.GetInt("role")
  858. if myRole <= user.Role && myRole != common.RoleRootUser {
  859. c.JSON(http.StatusOK, gin.H{
  860. "success": false,
  861. "message": "无权更新同权限等级或更高权限等级的用户信息",
  862. })
  863. return
  864. }
  865. switch req.Action {
  866. case "disable":
  867. user.Status = common.UserStatusDisabled
  868. if user.Role == common.RoleRootUser {
  869. c.JSON(http.StatusOK, gin.H{
  870. "success": false,
  871. "message": "无法禁用超级管理员用户",
  872. })
  873. return
  874. }
  875. case "enable":
  876. user.Status = common.UserStatusEnabled
  877. case "delete":
  878. if user.Role == common.RoleRootUser {
  879. c.JSON(http.StatusOK, gin.H{
  880. "success": false,
  881. "message": "无法删除超级管理员用户",
  882. })
  883. return
  884. }
  885. if err := user.Delete(); err != nil {
  886. c.JSON(http.StatusOK, gin.H{
  887. "success": false,
  888. "message": err.Error(),
  889. })
  890. return
  891. }
  892. case "promote":
  893. if myRole != common.RoleRootUser {
  894. c.JSON(http.StatusOK, gin.H{
  895. "success": false,
  896. "message": "普通管理员用户无法提升其他用户为管理员",
  897. })
  898. return
  899. }
  900. if user.Role >= common.RoleAdminUser {
  901. c.JSON(http.StatusOK, gin.H{
  902. "success": false,
  903. "message": "该用户已经是管理员",
  904. })
  905. return
  906. }
  907. user.Role = common.RoleAdminUser
  908. case "demote":
  909. if user.Role == common.RoleRootUser {
  910. c.JSON(http.StatusOK, gin.H{
  911. "success": false,
  912. "message": "无法降级超级管理员用户",
  913. })
  914. return
  915. }
  916. if user.Role == common.RoleCommonUser {
  917. c.JSON(http.StatusOK, gin.H{
  918. "success": false,
  919. "message": "该用户已经是普通用户",
  920. })
  921. return
  922. }
  923. user.Role = common.RoleCommonUser
  924. }
  925. if err := user.Update(false); err != nil {
  926. common.ApiError(c, err)
  927. return
  928. }
  929. clearUser := model.User{
  930. Role: user.Role,
  931. Status: user.Status,
  932. }
  933. c.JSON(http.StatusOK, gin.H{
  934. "success": true,
  935. "message": "",
  936. "data": clearUser,
  937. })
  938. return
  939. }
  940. func EmailBind(c *gin.Context) {
  941. email := c.Query("email")
  942. code := c.Query("code")
  943. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  944. c.JSON(http.StatusOK, gin.H{
  945. "success": false,
  946. "message": "验证码错误或已过期",
  947. })
  948. return
  949. }
  950. session := sessions.Default(c)
  951. id := session.Get("id")
  952. user := model.User{
  953. Id: id.(int),
  954. }
  955. err := user.FillUserById()
  956. if err != nil {
  957. common.ApiError(c, err)
  958. return
  959. }
  960. user.Email = email
  961. // no need to check if this email already taken, because we have used verification code to check it
  962. err = user.Update(false)
  963. if err != nil {
  964. common.ApiError(c, err)
  965. return
  966. }
  967. c.JSON(http.StatusOK, gin.H{
  968. "success": true,
  969. "message": "",
  970. })
  971. return
  972. }
  973. type topUpRequest struct {
  974. Key string `json:"key"`
  975. }
  976. var topUpLocks sync.Map
  977. var topUpCreateLock sync.Mutex
  978. type topUpTryLock struct {
  979. ch chan struct{}
  980. }
  981. func newTopUpTryLock() *topUpTryLock {
  982. return &topUpTryLock{ch: make(chan struct{}, 1)}
  983. }
  984. func (l *topUpTryLock) TryLock() bool {
  985. select {
  986. case l.ch <- struct{}{}:
  987. return true
  988. default:
  989. return false
  990. }
  991. }
  992. func (l *topUpTryLock) Unlock() {
  993. select {
  994. case <-l.ch:
  995. default:
  996. }
  997. }
  998. func getTopUpLock(userID int) *topUpTryLock {
  999. if v, ok := topUpLocks.Load(userID); ok {
  1000. return v.(*topUpTryLock)
  1001. }
  1002. topUpCreateLock.Lock()
  1003. defer topUpCreateLock.Unlock()
  1004. if v, ok := topUpLocks.Load(userID); ok {
  1005. return v.(*topUpTryLock)
  1006. }
  1007. l := newTopUpTryLock()
  1008. topUpLocks.Store(userID, l)
  1009. return l
  1010. }
  1011. func TopUp(c *gin.Context) {
  1012. id := c.GetInt("id")
  1013. lock := getTopUpLock(id)
  1014. if !lock.TryLock() {
  1015. c.JSON(http.StatusOK, gin.H{
  1016. "success": false,
  1017. "message": "充值处理中,请稍后重试",
  1018. })
  1019. return
  1020. }
  1021. defer lock.Unlock()
  1022. req := topUpRequest{}
  1023. err := c.ShouldBindJSON(&req)
  1024. if err != nil {
  1025. common.ApiError(c, err)
  1026. return
  1027. }
  1028. quota, err := model.Redeem(req.Key, id)
  1029. if err != nil {
  1030. common.ApiError(c, err)
  1031. return
  1032. }
  1033. c.JSON(http.StatusOK, gin.H{
  1034. "success": true,
  1035. "message": "",
  1036. "data": quota,
  1037. })
  1038. }
  1039. type UpdateUserSettingRequest struct {
  1040. QuotaWarningType string `json:"notify_type"`
  1041. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  1042. WebhookUrl string `json:"webhook_url,omitempty"`
  1043. WebhookSecret string `json:"webhook_secret,omitempty"`
  1044. NotificationEmail string `json:"notification_email,omitempty"`
  1045. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  1046. RecordIpLog bool `json:"record_ip_log"`
  1047. }
  1048. func UpdateUserSetting(c *gin.Context) {
  1049. var req UpdateUserSettingRequest
  1050. if err := c.ShouldBindJSON(&req); err != nil {
  1051. c.JSON(http.StatusOK, gin.H{
  1052. "success": false,
  1053. "message": "无效的参数",
  1054. })
  1055. return
  1056. }
  1057. // 验证预警类型
  1058. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook {
  1059. c.JSON(http.StatusOK, gin.H{
  1060. "success": false,
  1061. "message": "无效的预警类型",
  1062. })
  1063. return
  1064. }
  1065. // 验证预警阈值
  1066. if req.QuotaWarningThreshold <= 0 {
  1067. c.JSON(http.StatusOK, gin.H{
  1068. "success": false,
  1069. "message": "预警阈值必须大于0",
  1070. })
  1071. return
  1072. }
  1073. // 如果是webhook类型,验证webhook地址
  1074. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1075. if req.WebhookUrl == "" {
  1076. c.JSON(http.StatusOK, gin.H{
  1077. "success": false,
  1078. "message": "Webhook地址不能为空",
  1079. })
  1080. return
  1081. }
  1082. // 验证URL格式
  1083. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  1084. c.JSON(http.StatusOK, gin.H{
  1085. "success": false,
  1086. "message": "无效的Webhook地址",
  1087. })
  1088. return
  1089. }
  1090. }
  1091. // 如果是邮件类型,验证邮箱地址
  1092. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1093. // 验证邮箱格式
  1094. if !strings.Contains(req.NotificationEmail, "@") {
  1095. c.JSON(http.StatusOK, gin.H{
  1096. "success": false,
  1097. "message": "无效的邮箱地址",
  1098. })
  1099. return
  1100. }
  1101. }
  1102. userId := c.GetInt("id")
  1103. user, err := model.GetUserById(userId, true)
  1104. if err != nil {
  1105. common.ApiError(c, err)
  1106. return
  1107. }
  1108. // 构建设置
  1109. settings := dto.UserSetting{
  1110. NotifyType: req.QuotaWarningType,
  1111. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1112. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1113. RecordIpLog: req.RecordIpLog,
  1114. }
  1115. // 如果是webhook类型,添加webhook相关设置
  1116. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1117. settings.WebhookUrl = req.WebhookUrl
  1118. if req.WebhookSecret != "" {
  1119. settings.WebhookSecret = req.WebhookSecret
  1120. }
  1121. }
  1122. // 如果提供了通知邮箱,添加到设置中
  1123. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1124. settings.NotificationEmail = req.NotificationEmail
  1125. }
  1126. // 更新用户设置
  1127. user.SetSetting(settings)
  1128. if err := user.Update(false); err != nil {
  1129. c.JSON(http.StatusOK, gin.H{
  1130. "success": false,
  1131. "message": "更新设置失败: " + err.Error(),
  1132. })
  1133. return
  1134. }
  1135. c.JSON(http.StatusOK, gin.H{
  1136. "success": true,
  1137. "message": "设置已更新",
  1138. })
  1139. }