2
0

user.go 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "one-api/common"
  8. "one-api/model"
  9. "one-api/setting"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "one-api/constant"
  14. "github.com/gin-contrib/sessions"
  15. "github.com/gin-gonic/gin"
  16. )
  17. type LoginRequest struct {
  18. Username string `json:"username"`
  19. Password string `json:"password"`
  20. }
  21. func Login(c *gin.Context) {
  22. if !common.PasswordLoginEnabled {
  23. c.JSON(http.StatusOK, gin.H{
  24. "message": "管理员关闭了密码登录",
  25. "success": false,
  26. })
  27. return
  28. }
  29. var loginRequest LoginRequest
  30. err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
  31. if err != nil {
  32. c.JSON(http.StatusOK, gin.H{
  33. "message": "无效的参数",
  34. "success": false,
  35. })
  36. return
  37. }
  38. username := loginRequest.Username
  39. password := loginRequest.Password
  40. if username == "" || password == "" {
  41. c.JSON(http.StatusOK, gin.H{
  42. "message": "无效的参数",
  43. "success": false,
  44. })
  45. return
  46. }
  47. user := model.User{
  48. Username: username,
  49. Password: password,
  50. }
  51. err = user.ValidateAndFill()
  52. if err != nil {
  53. c.JSON(http.StatusOK, gin.H{
  54. "message": err.Error(),
  55. "success": false,
  56. })
  57. return
  58. }
  59. setupLogin(&user, c)
  60. }
  61. // setup session & cookies and then return user info
  62. func setupLogin(user *model.User, c *gin.Context) {
  63. session := sessions.Default(c)
  64. session.Set("id", user.Id)
  65. session.Set("username", user.Username)
  66. session.Set("role", user.Role)
  67. session.Set("status", user.Status)
  68. session.Set("group", user.Group)
  69. err := session.Save()
  70. if err != nil {
  71. c.JSON(http.StatusOK, gin.H{
  72. "message": "无法保存会话信息,请重试",
  73. "success": false,
  74. })
  75. return
  76. }
  77. cleanUser := model.User{
  78. Id: user.Id,
  79. Username: user.Username,
  80. DisplayName: user.DisplayName,
  81. Role: user.Role,
  82. Status: user.Status,
  83. Group: user.Group,
  84. }
  85. c.JSON(http.StatusOK, gin.H{
  86. "message": "",
  87. "success": true,
  88. "data": cleanUser,
  89. })
  90. }
  91. func Logout(c *gin.Context) {
  92. session := sessions.Default(c)
  93. session.Clear()
  94. err := session.Save()
  95. if err != nil {
  96. c.JSON(http.StatusOK, gin.H{
  97. "message": err.Error(),
  98. "success": false,
  99. })
  100. return
  101. }
  102. c.JSON(http.StatusOK, gin.H{
  103. "message": "",
  104. "success": true,
  105. })
  106. }
  107. func Register(c *gin.Context) {
  108. if !common.RegisterEnabled {
  109. c.JSON(http.StatusOK, gin.H{
  110. "message": "管理员关闭了新用户注册",
  111. "success": false,
  112. })
  113. return
  114. }
  115. if !common.PasswordRegisterEnabled {
  116. c.JSON(http.StatusOK, gin.H{
  117. "message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
  118. "success": false,
  119. })
  120. return
  121. }
  122. var user model.User
  123. err := json.NewDecoder(c.Request.Body).Decode(&user)
  124. if err != nil {
  125. c.JSON(http.StatusOK, gin.H{
  126. "success": false,
  127. "message": "无效的参数",
  128. })
  129. return
  130. }
  131. if err := common.Validate.Struct(&user); err != nil {
  132. c.JSON(http.StatusOK, gin.H{
  133. "success": false,
  134. "message": "输入不合法 " + err.Error(),
  135. })
  136. return
  137. }
  138. if common.EmailVerificationEnabled {
  139. if user.Email == "" || user.VerificationCode == "" {
  140. c.JSON(http.StatusOK, gin.H{
  141. "success": false,
  142. "message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
  143. })
  144. return
  145. }
  146. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  147. c.JSON(http.StatusOK, gin.H{
  148. "success": false,
  149. "message": "验证码错误或已过期",
  150. })
  151. return
  152. }
  153. }
  154. exist, err := model.CheckUserExistOrDeleted(user.Username, user.Email)
  155. if err != nil {
  156. c.JSON(http.StatusOK, gin.H{
  157. "success": false,
  158. "message": "数据库错误,请稍后重试",
  159. })
  160. common.SysError(fmt.Sprintf("CheckUserExistOrDeleted error: %v", err))
  161. return
  162. }
  163. if exist {
  164. c.JSON(http.StatusOK, gin.H{
  165. "success": false,
  166. "message": "用户名已存在,或已注销",
  167. })
  168. return
  169. }
  170. affCode := user.AffCode // this code is the inviter's code, not the user's own code
  171. inviterId, _ := model.GetUserIdByAffCode(affCode)
  172. cleanUser := model.User{
  173. Username: user.Username,
  174. Password: user.Password,
  175. DisplayName: user.Username,
  176. InviterId: inviterId,
  177. }
  178. if common.EmailVerificationEnabled {
  179. cleanUser.Email = user.Email
  180. }
  181. if err := cleanUser.Insert(inviterId); err != nil {
  182. c.JSON(http.StatusOK, gin.H{
  183. "success": false,
  184. "message": err.Error(),
  185. })
  186. return
  187. }
  188. // 获取插入后的用户ID
  189. var insertedUser model.User
  190. if err := model.DB.Where("username = ?", cleanUser.Username).First(&insertedUser).Error; err != nil {
  191. c.JSON(http.StatusOK, gin.H{
  192. "success": false,
  193. "message": "用户注册失败或用户ID获取失败",
  194. })
  195. return
  196. }
  197. // 生成默认令牌
  198. if constant.GenerateDefaultToken {
  199. key, err := common.GenerateKey()
  200. if err != nil {
  201. c.JSON(http.StatusOK, gin.H{
  202. "success": false,
  203. "message": "生成默认令牌失败",
  204. })
  205. common.SysError("failed to generate token key: " + err.Error())
  206. return
  207. }
  208. // 生成默认令牌
  209. token := model.Token{
  210. UserId: insertedUser.Id, // 使用插入后的用户ID
  211. Name: cleanUser.Username + "的初始令牌",
  212. Key: key,
  213. CreatedTime: common.GetTimestamp(),
  214. AccessedTime: common.GetTimestamp(),
  215. ExpiredTime: -1, // 永不过期
  216. RemainQuota: 500000, // 示例额度
  217. UnlimitedQuota: true,
  218. ModelLimitsEnabled: false,
  219. }
  220. if setting.DefaultUseAutoGroup {
  221. token.Group = "auto"
  222. }
  223. if err := token.Insert(); err != nil {
  224. c.JSON(http.StatusOK, gin.H{
  225. "success": false,
  226. "message": "创建默认令牌失败",
  227. })
  228. return
  229. }
  230. }
  231. c.JSON(http.StatusOK, gin.H{
  232. "success": true,
  233. "message": "",
  234. })
  235. return
  236. }
  237. func GetAllUsers(c *gin.Context) {
  238. pageInfo, err := common.GetPageQuery(c)
  239. if err != nil {
  240. c.JSON(http.StatusOK, gin.H{
  241. "success": false,
  242. "message": "parse page query failed",
  243. })
  244. return
  245. }
  246. users, total, err := model.GetAllUsers(pageInfo)
  247. if err != nil {
  248. c.JSON(http.StatusOK, gin.H{
  249. "success": false,
  250. "message": err.Error(),
  251. })
  252. return
  253. }
  254. pageInfo.SetTotal(int(total))
  255. pageInfo.SetItems(users)
  256. c.JSON(http.StatusOK, gin.H{
  257. "success": true,
  258. "message": "",
  259. "data": pageInfo,
  260. })
  261. return
  262. }
  263. func SearchUsers(c *gin.Context) {
  264. keyword := c.Query("keyword")
  265. group := c.Query("group")
  266. p, _ := strconv.Atoi(c.Query("p"))
  267. pageSize, _ := strconv.Atoi(c.Query("page_size"))
  268. if p < 1 {
  269. p = 1
  270. }
  271. if pageSize < 0 {
  272. pageSize = common.ItemsPerPage
  273. }
  274. startIdx := (p - 1) * pageSize
  275. users, total, err := model.SearchUsers(keyword, group, startIdx, pageSize)
  276. if err != nil {
  277. c.JSON(http.StatusOK, gin.H{
  278. "success": false,
  279. "message": err.Error(),
  280. })
  281. return
  282. }
  283. c.JSON(http.StatusOK, gin.H{
  284. "success": true,
  285. "message": "",
  286. "data": gin.H{
  287. "items": users,
  288. "total": total,
  289. "page": p,
  290. "page_size": pageSize,
  291. },
  292. })
  293. return
  294. }
  295. func GetUser(c *gin.Context) {
  296. id, err := strconv.Atoi(c.Param("id"))
  297. if err != nil {
  298. c.JSON(http.StatusOK, gin.H{
  299. "success": false,
  300. "message": err.Error(),
  301. })
  302. return
  303. }
  304. user, err := model.GetUserById(id, false)
  305. if err != nil {
  306. c.JSON(http.StatusOK, gin.H{
  307. "success": false,
  308. "message": err.Error(),
  309. })
  310. return
  311. }
  312. myRole := c.GetInt("role")
  313. if myRole <= user.Role && myRole != common.RoleRootUser {
  314. c.JSON(http.StatusOK, gin.H{
  315. "success": false,
  316. "message": "无权获取同级或更高等级用户的信息",
  317. })
  318. return
  319. }
  320. c.JSON(http.StatusOK, gin.H{
  321. "success": true,
  322. "message": "",
  323. "data": user,
  324. })
  325. return
  326. }
  327. func GenerateAccessToken(c *gin.Context) {
  328. id := c.GetInt("id")
  329. user, err := model.GetUserById(id, true)
  330. if err != nil {
  331. c.JSON(http.StatusOK, gin.H{
  332. "success": false,
  333. "message": err.Error(),
  334. })
  335. return
  336. }
  337. // get rand int 28-32
  338. randI := common.GetRandomInt(4)
  339. key, err := common.GenerateRandomKey(29 + randI)
  340. if err != nil {
  341. c.JSON(http.StatusOK, gin.H{
  342. "success": false,
  343. "message": "生成失败",
  344. })
  345. common.SysError("failed to generate key: " + err.Error())
  346. return
  347. }
  348. user.SetAccessToken(key)
  349. if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
  350. c.JSON(http.StatusOK, gin.H{
  351. "success": false,
  352. "message": "请重试,系统生成的 UUID 竟然重复了!",
  353. })
  354. return
  355. }
  356. if err := user.Update(false); err != nil {
  357. c.JSON(http.StatusOK, gin.H{
  358. "success": false,
  359. "message": err.Error(),
  360. })
  361. return
  362. }
  363. c.JSON(http.StatusOK, gin.H{
  364. "success": true,
  365. "message": "",
  366. "data": user.AccessToken,
  367. })
  368. return
  369. }
  370. type TransferAffQuotaRequest struct {
  371. Quota int `json:"quota" binding:"required"`
  372. }
  373. func TransferAffQuota(c *gin.Context) {
  374. id := c.GetInt("id")
  375. user, err := model.GetUserById(id, true)
  376. if err != nil {
  377. c.JSON(http.StatusOK, gin.H{
  378. "success": false,
  379. "message": err.Error(),
  380. })
  381. return
  382. }
  383. tran := TransferAffQuotaRequest{}
  384. if err := c.ShouldBindJSON(&tran); err != nil {
  385. c.JSON(http.StatusOK, gin.H{
  386. "success": false,
  387. "message": err.Error(),
  388. })
  389. return
  390. }
  391. err = user.TransferAffQuotaToQuota(tran.Quota)
  392. if err != nil {
  393. c.JSON(http.StatusOK, gin.H{
  394. "success": false,
  395. "message": "划转失败 " + err.Error(),
  396. })
  397. return
  398. }
  399. c.JSON(http.StatusOK, gin.H{
  400. "success": true,
  401. "message": "划转成功",
  402. })
  403. }
  404. func GetAffCode(c *gin.Context) {
  405. id := c.GetInt("id")
  406. user, err := model.GetUserById(id, true)
  407. if err != nil {
  408. c.JSON(http.StatusOK, gin.H{
  409. "success": false,
  410. "message": err.Error(),
  411. })
  412. return
  413. }
  414. if user.AffCode == "" {
  415. user.AffCode = common.GetRandomString(4)
  416. if err := user.Update(false); err != nil {
  417. c.JSON(http.StatusOK, gin.H{
  418. "success": false,
  419. "message": err.Error(),
  420. })
  421. return
  422. }
  423. }
  424. c.JSON(http.StatusOK, gin.H{
  425. "success": true,
  426. "message": "",
  427. "data": user.AffCode,
  428. })
  429. return
  430. }
  431. func GetSelf(c *gin.Context) {
  432. id := c.GetInt("id")
  433. user, err := model.GetUserById(id, false)
  434. if err != nil {
  435. c.JSON(http.StatusOK, gin.H{
  436. "success": false,
  437. "message": err.Error(),
  438. })
  439. return
  440. }
  441. // Hide admin remarks: set to empty to trigger omitempty tag, ensuring the remark field is not included in JSON returned to regular users
  442. user.Remark = ""
  443. c.JSON(http.StatusOK, gin.H{
  444. "success": true,
  445. "message": "",
  446. "data": user,
  447. })
  448. return
  449. }
  450. func GetUserModels(c *gin.Context) {
  451. id, err := strconv.Atoi(c.Param("id"))
  452. if err != nil {
  453. id = c.GetInt("id")
  454. }
  455. user, err := model.GetUserCache(id)
  456. if err != nil {
  457. c.JSON(http.StatusOK, gin.H{
  458. "success": false,
  459. "message": err.Error(),
  460. })
  461. return
  462. }
  463. groups := setting.GetUserUsableGroups(user.Group)
  464. var models []string
  465. for group := range groups {
  466. for _, g := range model.GetGroupModels(group) {
  467. if !common.StringsContains(models, g) {
  468. models = append(models, g)
  469. }
  470. }
  471. }
  472. c.JSON(http.StatusOK, gin.H{
  473. "success": true,
  474. "message": "",
  475. "data": models,
  476. })
  477. return
  478. }
  479. func UpdateUser(c *gin.Context) {
  480. var updatedUser model.User
  481. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  482. if err != nil || updatedUser.Id == 0 {
  483. c.JSON(http.StatusOK, gin.H{
  484. "success": false,
  485. "message": "无效的参数",
  486. })
  487. return
  488. }
  489. if updatedUser.Password == "" {
  490. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  491. }
  492. if err := common.Validate.Struct(&updatedUser); err != nil {
  493. c.JSON(http.StatusOK, gin.H{
  494. "success": false,
  495. "message": "输入不合法 " + err.Error(),
  496. })
  497. return
  498. }
  499. originUser, err := model.GetUserById(updatedUser.Id, false)
  500. if err != nil {
  501. c.JSON(http.StatusOK, gin.H{
  502. "success": false,
  503. "message": err.Error(),
  504. })
  505. return
  506. }
  507. myRole := c.GetInt("role")
  508. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  509. c.JSON(http.StatusOK, gin.H{
  510. "success": false,
  511. "message": "无权更新同权限等级或更高权限等级的用户信息",
  512. })
  513. return
  514. }
  515. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  516. c.JSON(http.StatusOK, gin.H{
  517. "success": false,
  518. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  519. })
  520. return
  521. }
  522. if updatedUser.Password == "$I_LOVE_U" {
  523. updatedUser.Password = "" // rollback to what it should be
  524. }
  525. updatePassword := updatedUser.Password != ""
  526. if err := updatedUser.Edit(updatePassword); err != nil {
  527. c.JSON(http.StatusOK, gin.H{
  528. "success": false,
  529. "message": err.Error(),
  530. })
  531. return
  532. }
  533. if originUser.Quota != updatedUser.Quota {
  534. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", common.LogQuota(originUser.Quota), common.LogQuota(updatedUser.Quota)))
  535. }
  536. c.JSON(http.StatusOK, gin.H{
  537. "success": true,
  538. "message": "",
  539. })
  540. return
  541. }
  542. func UpdateSelf(c *gin.Context) {
  543. var user model.User
  544. err := json.NewDecoder(c.Request.Body).Decode(&user)
  545. if err != nil {
  546. c.JSON(http.StatusOK, gin.H{
  547. "success": false,
  548. "message": "无效的参数",
  549. })
  550. return
  551. }
  552. if user.Password == "" {
  553. user.Password = "$I_LOVE_U" // make Validator happy :)
  554. }
  555. if err := common.Validate.Struct(&user); err != nil {
  556. c.JSON(http.StatusOK, gin.H{
  557. "success": false,
  558. "message": "输入不合法 " + err.Error(),
  559. })
  560. return
  561. }
  562. cleanUser := model.User{
  563. Id: c.GetInt("id"),
  564. Username: user.Username,
  565. Password: user.Password,
  566. DisplayName: user.DisplayName,
  567. }
  568. if user.Password == "$I_LOVE_U" {
  569. user.Password = "" // rollback to what it should be
  570. cleanUser.Password = ""
  571. }
  572. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  573. if err != nil {
  574. c.JSON(http.StatusOK, gin.H{
  575. "success": false,
  576. "message": err.Error(),
  577. })
  578. return
  579. }
  580. if err := cleanUser.Update(updatePassword); err != nil {
  581. c.JSON(http.StatusOK, gin.H{
  582. "success": false,
  583. "message": err.Error(),
  584. })
  585. return
  586. }
  587. c.JSON(http.StatusOK, gin.H{
  588. "success": true,
  589. "message": "",
  590. })
  591. return
  592. }
  593. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  594. var currentUser *model.User
  595. currentUser, err = model.GetUserById(userId, true)
  596. if err != nil {
  597. return
  598. }
  599. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) {
  600. err = fmt.Errorf("原密码错误")
  601. return
  602. }
  603. if newPassword == "" {
  604. return
  605. }
  606. updatePassword = true
  607. return
  608. }
  609. func DeleteUser(c *gin.Context) {
  610. id, err := strconv.Atoi(c.Param("id"))
  611. if err != nil {
  612. c.JSON(http.StatusOK, gin.H{
  613. "success": false,
  614. "message": err.Error(),
  615. })
  616. return
  617. }
  618. originUser, err := model.GetUserById(id, false)
  619. if err != nil {
  620. c.JSON(http.StatusOK, gin.H{
  621. "success": false,
  622. "message": err.Error(),
  623. })
  624. return
  625. }
  626. myRole := c.GetInt("role")
  627. if myRole <= originUser.Role {
  628. c.JSON(http.StatusOK, gin.H{
  629. "success": false,
  630. "message": "无权删除同权限等级或更高权限等级的用户",
  631. })
  632. return
  633. }
  634. err = model.HardDeleteUserById(id)
  635. if err != nil {
  636. c.JSON(http.StatusOK, gin.H{
  637. "success": true,
  638. "message": "",
  639. })
  640. return
  641. }
  642. }
  643. func DeleteSelf(c *gin.Context) {
  644. id := c.GetInt("id")
  645. user, _ := model.GetUserById(id, false)
  646. if user.Role == common.RoleRootUser {
  647. c.JSON(http.StatusOK, gin.H{
  648. "success": false,
  649. "message": "不能删除超级管理员账户",
  650. })
  651. return
  652. }
  653. err := model.DeleteUserById(id)
  654. if err != nil {
  655. c.JSON(http.StatusOK, gin.H{
  656. "success": false,
  657. "message": err.Error(),
  658. })
  659. return
  660. }
  661. c.JSON(http.StatusOK, gin.H{
  662. "success": true,
  663. "message": "",
  664. })
  665. return
  666. }
  667. func CreateUser(c *gin.Context) {
  668. var user model.User
  669. err := json.NewDecoder(c.Request.Body).Decode(&user)
  670. user.Username = strings.TrimSpace(user.Username)
  671. if err != nil || user.Username == "" || user.Password == "" {
  672. c.JSON(http.StatusOK, gin.H{
  673. "success": false,
  674. "message": "无效的参数",
  675. })
  676. return
  677. }
  678. if err := common.Validate.Struct(&user); err != nil {
  679. c.JSON(http.StatusOK, gin.H{
  680. "success": false,
  681. "message": "输入不合法 " + err.Error(),
  682. })
  683. return
  684. }
  685. if user.DisplayName == "" {
  686. user.DisplayName = user.Username
  687. }
  688. myRole := c.GetInt("role")
  689. if user.Role >= myRole {
  690. c.JSON(http.StatusOK, gin.H{
  691. "success": false,
  692. "message": "无法创建权限大于等于自己的用户",
  693. })
  694. return
  695. }
  696. // Even for admin users, we cannot fully trust them!
  697. cleanUser := model.User{
  698. Username: user.Username,
  699. Password: user.Password,
  700. DisplayName: user.DisplayName,
  701. }
  702. if err := cleanUser.Insert(0); err != nil {
  703. c.JSON(http.StatusOK, gin.H{
  704. "success": false,
  705. "message": err.Error(),
  706. })
  707. return
  708. }
  709. c.JSON(http.StatusOK, gin.H{
  710. "success": true,
  711. "message": "",
  712. })
  713. return
  714. }
  715. type ManageRequest struct {
  716. Id int `json:"id"`
  717. Action string `json:"action"`
  718. }
  719. // ManageUser Only admin user can do this
  720. func ManageUser(c *gin.Context) {
  721. var req ManageRequest
  722. err := json.NewDecoder(c.Request.Body).Decode(&req)
  723. if err != nil {
  724. c.JSON(http.StatusOK, gin.H{
  725. "success": false,
  726. "message": "无效的参数",
  727. })
  728. return
  729. }
  730. user := model.User{
  731. Id: req.Id,
  732. }
  733. // Fill attributes
  734. model.DB.Unscoped().Where(&user).First(&user)
  735. if user.Id == 0 {
  736. c.JSON(http.StatusOK, gin.H{
  737. "success": false,
  738. "message": "用户不存在",
  739. })
  740. return
  741. }
  742. myRole := c.GetInt("role")
  743. if myRole <= user.Role && myRole != common.RoleRootUser {
  744. c.JSON(http.StatusOK, gin.H{
  745. "success": false,
  746. "message": "无权更新同权限等级或更高权限等级的用户信息",
  747. })
  748. return
  749. }
  750. switch req.Action {
  751. case "disable":
  752. user.Status = common.UserStatusDisabled
  753. if user.Role == common.RoleRootUser {
  754. c.JSON(http.StatusOK, gin.H{
  755. "success": false,
  756. "message": "无法禁用超级管理员用户",
  757. })
  758. return
  759. }
  760. case "enable":
  761. user.Status = common.UserStatusEnabled
  762. case "delete":
  763. if user.Role == common.RoleRootUser {
  764. c.JSON(http.StatusOK, gin.H{
  765. "success": false,
  766. "message": "无法删除超级管理员用户",
  767. })
  768. return
  769. }
  770. if err := user.Delete(); err != nil {
  771. c.JSON(http.StatusOK, gin.H{
  772. "success": false,
  773. "message": err.Error(),
  774. })
  775. return
  776. }
  777. case "promote":
  778. if myRole != common.RoleRootUser {
  779. c.JSON(http.StatusOK, gin.H{
  780. "success": false,
  781. "message": "普通管理员用户无法提升其他用户为管理员",
  782. })
  783. return
  784. }
  785. if user.Role >= common.RoleAdminUser {
  786. c.JSON(http.StatusOK, gin.H{
  787. "success": false,
  788. "message": "该用户已经是管理员",
  789. })
  790. return
  791. }
  792. user.Role = common.RoleAdminUser
  793. case "demote":
  794. if user.Role == common.RoleRootUser {
  795. c.JSON(http.StatusOK, gin.H{
  796. "success": false,
  797. "message": "无法降级超级管理员用户",
  798. })
  799. return
  800. }
  801. if user.Role == common.RoleCommonUser {
  802. c.JSON(http.StatusOK, gin.H{
  803. "success": false,
  804. "message": "该用户已经是普通用户",
  805. })
  806. return
  807. }
  808. user.Role = common.RoleCommonUser
  809. }
  810. if err := user.Update(false); err != nil {
  811. c.JSON(http.StatusOK, gin.H{
  812. "success": false,
  813. "message": err.Error(),
  814. })
  815. return
  816. }
  817. clearUser := model.User{
  818. Role: user.Role,
  819. Status: user.Status,
  820. }
  821. c.JSON(http.StatusOK, gin.H{
  822. "success": true,
  823. "message": "",
  824. "data": clearUser,
  825. })
  826. return
  827. }
  828. func EmailBind(c *gin.Context) {
  829. email := c.Query("email")
  830. code := c.Query("code")
  831. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  832. c.JSON(http.StatusOK, gin.H{
  833. "success": false,
  834. "message": "验证码错误或已过期",
  835. })
  836. return
  837. }
  838. session := sessions.Default(c)
  839. id := session.Get("id")
  840. user := model.User{
  841. Id: id.(int),
  842. }
  843. err := user.FillUserById()
  844. if err != nil {
  845. c.JSON(http.StatusOK, gin.H{
  846. "success": false,
  847. "message": err.Error(),
  848. })
  849. return
  850. }
  851. user.Email = email
  852. // no need to check if this email already taken, because we have used verification code to check it
  853. err = user.Update(false)
  854. if err != nil {
  855. c.JSON(http.StatusOK, gin.H{
  856. "success": false,
  857. "message": err.Error(),
  858. })
  859. return
  860. }
  861. c.JSON(http.StatusOK, gin.H{
  862. "success": true,
  863. "message": "",
  864. })
  865. return
  866. }
  867. type topUpRequest struct {
  868. Key string `json:"key"`
  869. }
  870. var topUpLock = sync.Mutex{}
  871. func TopUp(c *gin.Context) {
  872. topUpLock.Lock()
  873. defer topUpLock.Unlock()
  874. req := topUpRequest{}
  875. err := c.ShouldBindJSON(&req)
  876. if err != nil {
  877. c.JSON(http.StatusOK, gin.H{
  878. "success": false,
  879. "message": err.Error(),
  880. })
  881. return
  882. }
  883. id := c.GetInt("id")
  884. quota, err := model.Redeem(req.Key, id)
  885. if err != nil {
  886. c.JSON(http.StatusOK, gin.H{
  887. "success": false,
  888. "message": err.Error(),
  889. })
  890. return
  891. }
  892. c.JSON(http.StatusOK, gin.H{
  893. "success": true,
  894. "message": "",
  895. "data": quota,
  896. })
  897. return
  898. }
  899. type UpdateUserSettingRequest struct {
  900. QuotaWarningType string `json:"notify_type"`
  901. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  902. WebhookUrl string `json:"webhook_url,omitempty"`
  903. WebhookSecret string `json:"webhook_secret,omitempty"`
  904. NotificationEmail string `json:"notification_email,omitempty"`
  905. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  906. RecordIpLog bool `json:"record_ip_log"`
  907. }
  908. func UpdateUserSetting(c *gin.Context) {
  909. var req UpdateUserSettingRequest
  910. if err := c.ShouldBindJSON(&req); err != nil {
  911. c.JSON(http.StatusOK, gin.H{
  912. "success": false,
  913. "message": "无效的参数",
  914. })
  915. return
  916. }
  917. // 验证预警类型
  918. if req.QuotaWarningType != constant.NotifyTypeEmail && req.QuotaWarningType != constant.NotifyTypeWebhook {
  919. c.JSON(http.StatusOK, gin.H{
  920. "success": false,
  921. "message": "无效的预警类型",
  922. })
  923. return
  924. }
  925. // 验证预警阈值
  926. if req.QuotaWarningThreshold <= 0 {
  927. c.JSON(http.StatusOK, gin.H{
  928. "success": false,
  929. "message": "预警阈值必须大于0",
  930. })
  931. return
  932. }
  933. // 如果是webhook类型,验证webhook地址
  934. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  935. if req.WebhookUrl == "" {
  936. c.JSON(http.StatusOK, gin.H{
  937. "success": false,
  938. "message": "Webhook地址不能为空",
  939. })
  940. return
  941. }
  942. // 验证URL格式
  943. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  944. c.JSON(http.StatusOK, gin.H{
  945. "success": false,
  946. "message": "无效的Webhook地址",
  947. })
  948. return
  949. }
  950. }
  951. // 如果是邮件类型,验证邮箱地址
  952. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  953. // 验证邮箱格式
  954. if !strings.Contains(req.NotificationEmail, "@") {
  955. c.JSON(http.StatusOK, gin.H{
  956. "success": false,
  957. "message": "无效的邮箱地址",
  958. })
  959. return
  960. }
  961. }
  962. userId := c.GetInt("id")
  963. user, err := model.GetUserById(userId, true)
  964. if err != nil {
  965. c.JSON(http.StatusOK, gin.H{
  966. "success": false,
  967. "message": err.Error(),
  968. })
  969. return
  970. }
  971. // 构建设置
  972. settings := map[string]interface{}{
  973. constant.UserSettingNotifyType: req.QuotaWarningType,
  974. constant.UserSettingQuotaWarningThreshold: req.QuotaWarningThreshold,
  975. "accept_unset_model_ratio_model": req.AcceptUnsetModelRatioModel,
  976. constant.UserSettingRecordIpLog: req.RecordIpLog,
  977. }
  978. // 如果是webhook类型,添加webhook相关设置
  979. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  980. settings[constant.UserSettingWebhookUrl] = req.WebhookUrl
  981. if req.WebhookSecret != "" {
  982. settings[constant.UserSettingWebhookSecret] = req.WebhookSecret
  983. }
  984. }
  985. // 如果提供了通知邮箱,添加到设置中
  986. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  987. settings[constant.UserSettingNotificationEmail] = req.NotificationEmail
  988. }
  989. // 更新用户设置
  990. user.SetSetting(settings)
  991. if err := user.Update(false); err != nil {
  992. c.JSON(http.StatusOK, gin.H{
  993. "success": false,
  994. "message": "更新设置失败: " + err.Error(),
  995. })
  996. return
  997. }
  998. c.JSON(http.StatusOK, gin.H{
  999. "success": true,
  1000. "message": "设置已更新",
  1001. })
  1002. }