user.go 22 KB

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