user.go 19 KB

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