user.go 22 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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 err := token.Insert(); err != nil {
  221. c.JSON(http.StatusOK, gin.H{
  222. "success": false,
  223. "message": "创建默认令牌失败",
  224. })
  225. return
  226. }
  227. }
  228. c.JSON(http.StatusOK, gin.H{
  229. "success": true,
  230. "message": "",
  231. })
  232. return
  233. }
  234. func GetAllUsers(c *gin.Context) {
  235. p, _ := strconv.Atoi(c.Query("p"))
  236. pageSize, _ := strconv.Atoi(c.Query("page_size"))
  237. if p < 1 {
  238. p = 1
  239. }
  240. if pageSize < 0 {
  241. pageSize = common.ItemsPerPage
  242. }
  243. users, total, err := model.GetAllUsers((p-1)*pageSize, pageSize)
  244. if err != nil {
  245. c.JSON(http.StatusOK, gin.H{
  246. "success": false,
  247. "message": err.Error(),
  248. })
  249. return
  250. }
  251. c.JSON(http.StatusOK, gin.H{
  252. "success": true,
  253. "message": "",
  254. "data": gin.H{
  255. "items": users,
  256. "total": total,
  257. "page": p,
  258. "page_size": pageSize,
  259. },
  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. c.JSON(http.StatusOK, gin.H{
  442. "success": true,
  443. "message": "",
  444. "data": user,
  445. })
  446. return
  447. }
  448. func GetUserModels(c *gin.Context) {
  449. id, err := strconv.Atoi(c.Param("id"))
  450. if err != nil {
  451. id = c.GetInt("id")
  452. }
  453. user, err := model.GetUserCache(id)
  454. if err != nil {
  455. c.JSON(http.StatusOK, gin.H{
  456. "success": false,
  457. "message": err.Error(),
  458. })
  459. return
  460. }
  461. groups := setting.GetUserUsableGroups(user.Group)
  462. var models []string
  463. for group := range groups {
  464. for _, g := range model.GetGroupModels(group) {
  465. if !common.StringsContains(models, g) {
  466. models = append(models, g)
  467. }
  468. }
  469. }
  470. c.JSON(http.StatusOK, gin.H{
  471. "success": true,
  472. "message": "",
  473. "data": models,
  474. })
  475. return
  476. }
  477. func UpdateUser(c *gin.Context) {
  478. var updatedUser model.User
  479. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  480. if err != nil || updatedUser.Id == 0 {
  481. c.JSON(http.StatusOK, gin.H{
  482. "success": false,
  483. "message": "无效的参数",
  484. })
  485. return
  486. }
  487. if updatedUser.Password == "" {
  488. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  489. }
  490. if err := common.Validate.Struct(&updatedUser); err != nil {
  491. c.JSON(http.StatusOK, gin.H{
  492. "success": false,
  493. "message": "输入不合法 " + err.Error(),
  494. })
  495. return
  496. }
  497. originUser, err := model.GetUserById(updatedUser.Id, false)
  498. if err != nil {
  499. c.JSON(http.StatusOK, gin.H{
  500. "success": false,
  501. "message": err.Error(),
  502. })
  503. return
  504. }
  505. myRole := c.GetInt("role")
  506. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  507. c.JSON(http.StatusOK, gin.H{
  508. "success": false,
  509. "message": "无权更新同权限等级或更高权限等级的用户信息",
  510. })
  511. return
  512. }
  513. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  514. c.JSON(http.StatusOK, gin.H{
  515. "success": false,
  516. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  517. })
  518. return
  519. }
  520. if updatedUser.Password == "$I_LOVE_U" {
  521. updatedUser.Password = "" // rollback to what it should be
  522. }
  523. updatePassword := updatedUser.Password != ""
  524. if err := updatedUser.Edit(updatePassword); err != nil {
  525. c.JSON(http.StatusOK, gin.H{
  526. "success": false,
  527. "message": err.Error(),
  528. })
  529. return
  530. }
  531. if originUser.Quota != updatedUser.Quota {
  532. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", common.LogQuota(originUser.Quota), common.LogQuota(updatedUser.Quota)))
  533. }
  534. c.JSON(http.StatusOK, gin.H{
  535. "success": true,
  536. "message": "",
  537. })
  538. return
  539. }
  540. func UpdateSelf(c *gin.Context) {
  541. var user model.User
  542. err := json.NewDecoder(c.Request.Body).Decode(&user)
  543. if err != nil {
  544. c.JSON(http.StatusOK, gin.H{
  545. "success": false,
  546. "message": "无效的参数",
  547. })
  548. return
  549. }
  550. if user.Password == "" {
  551. user.Password = "$I_LOVE_U" // make Validator happy :)
  552. }
  553. if err := common.Validate.Struct(&user); err != nil {
  554. c.JSON(http.StatusOK, gin.H{
  555. "success": false,
  556. "message": "输入不合法 " + err.Error(),
  557. })
  558. return
  559. }
  560. cleanUser := model.User{
  561. Id: c.GetInt("id"),
  562. Username: user.Username,
  563. Password: user.Password,
  564. DisplayName: user.DisplayName,
  565. }
  566. if user.Password == "$I_LOVE_U" {
  567. user.Password = "" // rollback to what it should be
  568. cleanUser.Password = ""
  569. }
  570. updatePassword := user.Password != ""
  571. if err := cleanUser.Update(updatePassword); err != nil {
  572. c.JSON(http.StatusOK, gin.H{
  573. "success": false,
  574. "message": err.Error(),
  575. })
  576. return
  577. }
  578. c.JSON(http.StatusOK, gin.H{
  579. "success": true,
  580. "message": "",
  581. })
  582. return
  583. }
  584. func DeleteUser(c *gin.Context) {
  585. id, err := strconv.Atoi(c.Param("id"))
  586. if err != nil {
  587. c.JSON(http.StatusOK, gin.H{
  588. "success": false,
  589. "message": err.Error(),
  590. })
  591. return
  592. }
  593. originUser, err := model.GetUserById(id, false)
  594. if err != nil {
  595. c.JSON(http.StatusOK, gin.H{
  596. "success": false,
  597. "message": err.Error(),
  598. })
  599. return
  600. }
  601. myRole := c.GetInt("role")
  602. if myRole <= originUser.Role {
  603. c.JSON(http.StatusOK, gin.H{
  604. "success": false,
  605. "message": "无权删除同权限等级或更高权限等级的用户",
  606. })
  607. return
  608. }
  609. err = model.HardDeleteUserById(id)
  610. if err != nil {
  611. c.JSON(http.StatusOK, gin.H{
  612. "success": true,
  613. "message": "",
  614. })
  615. return
  616. }
  617. }
  618. func DeleteSelf(c *gin.Context) {
  619. id := c.GetInt("id")
  620. user, _ := model.GetUserById(id, false)
  621. if user.Role == common.RoleRootUser {
  622. c.JSON(http.StatusOK, gin.H{
  623. "success": false,
  624. "message": "不能删除超级管理员账户",
  625. })
  626. return
  627. }
  628. err := model.DeleteUserById(id)
  629. if err != nil {
  630. c.JSON(http.StatusOK, gin.H{
  631. "success": false,
  632. "message": err.Error(),
  633. })
  634. return
  635. }
  636. c.JSON(http.StatusOK, gin.H{
  637. "success": true,
  638. "message": "",
  639. })
  640. return
  641. }
  642. func CreateUser(c *gin.Context) {
  643. var user model.User
  644. err := json.NewDecoder(c.Request.Body).Decode(&user)
  645. user.Username = strings.TrimSpace(user.Username)
  646. if err != nil || user.Username == "" || user.Password == "" {
  647. c.JSON(http.StatusOK, gin.H{
  648. "success": false,
  649. "message": "无效的参数",
  650. })
  651. return
  652. }
  653. if err := common.Validate.Struct(&user); err != nil {
  654. c.JSON(http.StatusOK, gin.H{
  655. "success": false,
  656. "message": "输入不合法 " + err.Error(),
  657. })
  658. return
  659. }
  660. if user.DisplayName == "" {
  661. user.DisplayName = user.Username
  662. }
  663. myRole := c.GetInt("role")
  664. if user.Role >= myRole {
  665. c.JSON(http.StatusOK, gin.H{
  666. "success": false,
  667. "message": "无法创建权限大于等于自己的用户",
  668. })
  669. return
  670. }
  671. // Even for admin users, we cannot fully trust them!
  672. cleanUser := model.User{
  673. Username: user.Username,
  674. Password: user.Password,
  675. DisplayName: user.DisplayName,
  676. }
  677. if err := cleanUser.Insert(0); err != nil {
  678. c.JSON(http.StatusOK, gin.H{
  679. "success": false,
  680. "message": err.Error(),
  681. })
  682. return
  683. }
  684. c.JSON(http.StatusOK, gin.H{
  685. "success": true,
  686. "message": "",
  687. })
  688. return
  689. }
  690. type ManageRequest struct {
  691. Id int `json:"id"`
  692. Action string `json:"action"`
  693. }
  694. // ManageUser Only admin user can do this
  695. func ManageUser(c *gin.Context) {
  696. var req ManageRequest
  697. err := json.NewDecoder(c.Request.Body).Decode(&req)
  698. if err != nil {
  699. c.JSON(http.StatusOK, gin.H{
  700. "success": false,
  701. "message": "无效的参数",
  702. })
  703. return
  704. }
  705. user := model.User{
  706. Id: req.Id,
  707. }
  708. // Fill attributes
  709. model.DB.Unscoped().Where(&user).First(&user)
  710. if user.Id == 0 {
  711. c.JSON(http.StatusOK, gin.H{
  712. "success": false,
  713. "message": "用户不存在",
  714. })
  715. return
  716. }
  717. myRole := c.GetInt("role")
  718. if myRole <= user.Role && myRole != common.RoleRootUser {
  719. c.JSON(http.StatusOK, gin.H{
  720. "success": false,
  721. "message": "无权更新同权限等级或更高权限等级的用户信息",
  722. })
  723. return
  724. }
  725. switch req.Action {
  726. case "disable":
  727. user.Status = common.UserStatusDisabled
  728. if user.Role == common.RoleRootUser {
  729. c.JSON(http.StatusOK, gin.H{
  730. "success": false,
  731. "message": "无法禁用超级管理员用户",
  732. })
  733. return
  734. }
  735. case "enable":
  736. user.Status = common.UserStatusEnabled
  737. case "delete":
  738. if user.Role == common.RoleRootUser {
  739. c.JSON(http.StatusOK, gin.H{
  740. "success": false,
  741. "message": "无法删除超级管理员用户",
  742. })
  743. return
  744. }
  745. if err := user.Delete(); err != nil {
  746. c.JSON(http.StatusOK, gin.H{
  747. "success": false,
  748. "message": err.Error(),
  749. })
  750. return
  751. }
  752. case "promote":
  753. if myRole != common.RoleRootUser {
  754. c.JSON(http.StatusOK, gin.H{
  755. "success": false,
  756. "message": "普通管理员用户无法提升其他用户为管理员",
  757. })
  758. return
  759. }
  760. if user.Role >= common.RoleAdminUser {
  761. c.JSON(http.StatusOK, gin.H{
  762. "success": false,
  763. "message": "该用户已经是管理员",
  764. })
  765. return
  766. }
  767. user.Role = common.RoleAdminUser
  768. case "demote":
  769. if user.Role == common.RoleRootUser {
  770. c.JSON(http.StatusOK, gin.H{
  771. "success": false,
  772. "message": "无法降级超级管理员用户",
  773. })
  774. return
  775. }
  776. if user.Role == common.RoleCommonUser {
  777. c.JSON(http.StatusOK, gin.H{
  778. "success": false,
  779. "message": "该用户已经是普通用户",
  780. })
  781. return
  782. }
  783. user.Role = common.RoleCommonUser
  784. }
  785. if err := user.Update(false); err != nil {
  786. c.JSON(http.StatusOK, gin.H{
  787. "success": false,
  788. "message": err.Error(),
  789. })
  790. return
  791. }
  792. clearUser := model.User{
  793. Role: user.Role,
  794. Status: user.Status,
  795. }
  796. c.JSON(http.StatusOK, gin.H{
  797. "success": true,
  798. "message": "",
  799. "data": clearUser,
  800. })
  801. return
  802. }
  803. func EmailBind(c *gin.Context) {
  804. email := c.Query("email")
  805. code := c.Query("code")
  806. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  807. c.JSON(http.StatusOK, gin.H{
  808. "success": false,
  809. "message": "验证码错误或已过期",
  810. })
  811. return
  812. }
  813. session := sessions.Default(c)
  814. id := session.Get("id")
  815. user := model.User{
  816. Id: id.(int),
  817. }
  818. err := user.FillUserById()
  819. if err != nil {
  820. c.JSON(http.StatusOK, gin.H{
  821. "success": false,
  822. "message": err.Error(),
  823. })
  824. return
  825. }
  826. user.Email = email
  827. // no need to check if this email already taken, because we have used verification code to check it
  828. err = user.Update(false)
  829. if err != nil {
  830. c.JSON(http.StatusOK, gin.H{
  831. "success": false,
  832. "message": err.Error(),
  833. })
  834. return
  835. }
  836. c.JSON(http.StatusOK, gin.H{
  837. "success": true,
  838. "message": "",
  839. })
  840. return
  841. }
  842. type topUpRequest struct {
  843. Key string `json:"key"`
  844. }
  845. var topUpLock = sync.Mutex{}
  846. func TopUp(c *gin.Context) {
  847. topUpLock.Lock()
  848. defer topUpLock.Unlock()
  849. req := topUpRequest{}
  850. err := c.ShouldBindJSON(&req)
  851. if err != nil {
  852. c.JSON(http.StatusOK, gin.H{
  853. "success": false,
  854. "message": err.Error(),
  855. })
  856. return
  857. }
  858. id := c.GetInt("id")
  859. quota, err := model.Redeem(req.Key, id)
  860. if err != nil {
  861. c.JSON(http.StatusOK, gin.H{
  862. "success": false,
  863. "message": err.Error(),
  864. })
  865. return
  866. }
  867. c.JSON(http.StatusOK, gin.H{
  868. "success": true,
  869. "message": "",
  870. "data": quota,
  871. })
  872. return
  873. }
  874. type UpdateUserSettingRequest struct {
  875. QuotaWarningType string `json:"notify_type"`
  876. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  877. WebhookUrl string `json:"webhook_url,omitempty"`
  878. WebhookSecret string `json:"webhook_secret,omitempty"`
  879. NotificationEmail string `json:"notification_email,omitempty"`
  880. }
  881. func UpdateUserSetting(c *gin.Context) {
  882. var req UpdateUserSettingRequest
  883. if err := c.ShouldBindJSON(&req); err != nil {
  884. c.JSON(http.StatusOK, gin.H{
  885. "success": false,
  886. "message": "无效的参数",
  887. })
  888. return
  889. }
  890. // 验证预警类型
  891. if req.QuotaWarningType != constant.NotifyTypeEmail && req.QuotaWarningType != constant.NotifyTypeWebhook {
  892. c.JSON(http.StatusOK, gin.H{
  893. "success": false,
  894. "message": "无效的预警类型",
  895. })
  896. return
  897. }
  898. // 验证预警阈值
  899. if req.QuotaWarningThreshold <= 0 {
  900. c.JSON(http.StatusOK, gin.H{
  901. "success": false,
  902. "message": "预警阈值必须大于0",
  903. })
  904. return
  905. }
  906. // 如果是webhook类型,验证webhook地址
  907. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  908. if req.WebhookUrl == "" {
  909. c.JSON(http.StatusOK, gin.H{
  910. "success": false,
  911. "message": "Webhook地址不能为空",
  912. })
  913. return
  914. }
  915. // 验证URL格式
  916. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  917. c.JSON(http.StatusOK, gin.H{
  918. "success": false,
  919. "message": "无效的Webhook地址",
  920. })
  921. return
  922. }
  923. }
  924. // 如果是邮件类型,验证邮箱地址
  925. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  926. // 验证邮箱格式
  927. if !strings.Contains(req.NotificationEmail, "@") {
  928. c.JSON(http.StatusOK, gin.H{
  929. "success": false,
  930. "message": "无效的邮箱地址",
  931. })
  932. return
  933. }
  934. }
  935. userId := c.GetInt("id")
  936. user, err := model.GetUserById(userId, true)
  937. if err != nil {
  938. c.JSON(http.StatusOK, gin.H{
  939. "success": false,
  940. "message": err.Error(),
  941. })
  942. return
  943. }
  944. // 构建设置
  945. settings := map[string]interface{}{
  946. constant.UserSettingNotifyType: req.QuotaWarningType,
  947. constant.UserSettingQuotaWarningThreshold: req.QuotaWarningThreshold,
  948. }
  949. // 如果是webhook类型,添加webhook相关设置
  950. if req.QuotaWarningType == constant.NotifyTypeWebhook {
  951. settings[constant.UserSettingWebhookUrl] = req.WebhookUrl
  952. if req.WebhookSecret != "" {
  953. settings[constant.UserSettingWebhookSecret] = req.WebhookSecret
  954. }
  955. }
  956. // 如果提供了通知邮箱,添加到设置中
  957. if req.QuotaWarningType == constant.NotifyTypeEmail && req.NotificationEmail != "" {
  958. settings[constant.UserSettingNotificationEmail] = req.NotificationEmail
  959. }
  960. // 更新用户设置
  961. user.SetSetting(settings)
  962. if err := user.Update(false); err != nil {
  963. c.JSON(http.StatusOK, gin.H{
  964. "success": false,
  965. "message": "更新设置失败: " + err.Error(),
  966. })
  967. return
  968. }
  969. c.JSON(http.StatusOK, gin.H{
  970. "success": true,
  971. "message": "设置已更新",
  972. })
  973. }