user.go 21 KB

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