user.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/model"
  8. "strconv"
  9. "github.com/gin-contrib/sessions"
  10. "github.com/gin-gonic/gin"
  11. )
  12. type LoginRequest struct {
  13. Username string `json:"username"`
  14. Password string `json:"password"`
  15. }
  16. func Login(c *gin.Context) {
  17. if !common.PasswordLoginEnabled {
  18. c.JSON(http.StatusOK, gin.H{
  19. "message": "管理员关闭了密码登录",
  20. "success": false,
  21. })
  22. return
  23. }
  24. var loginRequest LoginRequest
  25. err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
  26. if err != nil {
  27. c.JSON(http.StatusOK, gin.H{
  28. "message": "无效的参数",
  29. "success": false,
  30. })
  31. return
  32. }
  33. username := loginRequest.Username
  34. password := loginRequest.Password
  35. if username == "" || password == "" {
  36. c.JSON(http.StatusOK, gin.H{
  37. "message": "无效的参数",
  38. "success": false,
  39. })
  40. return
  41. }
  42. user := model.User{
  43. Username: username,
  44. Password: password,
  45. }
  46. err = user.ValidateAndFill()
  47. if err != nil {
  48. c.JSON(http.StatusOK, gin.H{
  49. "message": err.Error(),
  50. "success": false,
  51. })
  52. return
  53. }
  54. setupLogin(&user, c)
  55. }
  56. // setup session & cookies and then return user info
  57. func setupLogin(user *model.User, c *gin.Context) {
  58. session := sessions.Default(c)
  59. session.Set("id", user.Id)
  60. session.Set("username", user.Username)
  61. session.Set("role", user.Role)
  62. session.Set("status", user.Status)
  63. err := session.Save()
  64. if err != nil {
  65. c.JSON(http.StatusOK, gin.H{
  66. "message": "无法保存会话信息,请重试",
  67. "success": false,
  68. })
  69. return
  70. }
  71. cleanUser := model.User{
  72. Id: user.Id,
  73. Username: user.Username,
  74. DisplayName: user.DisplayName,
  75. Role: user.Role,
  76. Status: user.Status,
  77. }
  78. c.JSON(http.StatusOK, gin.H{
  79. "message": "",
  80. "success": true,
  81. "data": cleanUser,
  82. })
  83. }
  84. func Logout(c *gin.Context) {
  85. session := sessions.Default(c)
  86. session.Clear()
  87. err := session.Save()
  88. if err != nil {
  89. c.JSON(http.StatusOK, gin.H{
  90. "message": err.Error(),
  91. "success": false,
  92. })
  93. return
  94. }
  95. c.JSON(http.StatusOK, gin.H{
  96. "message": "",
  97. "success": true,
  98. })
  99. }
  100. func Register(c *gin.Context) {
  101. if !common.RegisterEnabled {
  102. c.JSON(http.StatusOK, gin.H{
  103. "message": "管理员关闭了新用户注册",
  104. "success": false,
  105. })
  106. return
  107. }
  108. if !common.PasswordRegisterEnabled {
  109. c.JSON(http.StatusOK, gin.H{
  110. "message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
  111. "success": false,
  112. })
  113. return
  114. }
  115. var user model.User
  116. err := json.NewDecoder(c.Request.Body).Decode(&user)
  117. if err != nil {
  118. c.JSON(http.StatusOK, gin.H{
  119. "success": false,
  120. "message": "无效的参数",
  121. })
  122. return
  123. }
  124. if err := common.Validate.Struct(&user); err != nil {
  125. c.JSON(http.StatusOK, gin.H{
  126. "success": false,
  127. "message": "输入不合法 " + err.Error(),
  128. })
  129. return
  130. }
  131. if common.EmailVerificationEnabled {
  132. if user.Email == "" || user.VerificationCode == "" {
  133. c.JSON(http.StatusOK, gin.H{
  134. "success": false,
  135. "message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
  136. })
  137. return
  138. }
  139. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  140. c.JSON(http.StatusOK, gin.H{
  141. "success": false,
  142. "message": "验证码错误或已过期",
  143. })
  144. return
  145. }
  146. }
  147. affCode := user.AffCode // this code is the inviter's code, not the user's own code
  148. inviterId, _ := model.GetUserIdByAffCode(affCode)
  149. cleanUser := model.User{
  150. Username: user.Username,
  151. Password: user.Password,
  152. DisplayName: user.Username,
  153. InviterId: inviterId,
  154. }
  155. if common.EmailVerificationEnabled {
  156. cleanUser.Email = user.Email
  157. }
  158. if err := cleanUser.Insert(inviterId); err != nil {
  159. c.JSON(http.StatusOK, gin.H{
  160. "success": false,
  161. "message": err.Error(),
  162. })
  163. return
  164. }
  165. c.JSON(http.StatusOK, gin.H{
  166. "success": true,
  167. "message": "",
  168. })
  169. return
  170. }
  171. func GetAllUsers(c *gin.Context) {
  172. p, _ := strconv.Atoi(c.Query("p"))
  173. if p < 0 {
  174. p = 0
  175. }
  176. users, err := model.GetAllUsers(p*common.ItemsPerPage, common.ItemsPerPage)
  177. if err != nil {
  178. c.JSON(http.StatusOK, gin.H{
  179. "success": false,
  180. "message": err.Error(),
  181. })
  182. return
  183. }
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": true,
  186. "message": "",
  187. "data": users,
  188. })
  189. return
  190. }
  191. func SearchUsers(c *gin.Context) {
  192. keyword := c.Query("keyword")
  193. users, err := model.SearchUsers(keyword)
  194. if err != nil {
  195. c.JSON(http.StatusOK, gin.H{
  196. "success": false,
  197. "message": err.Error(),
  198. })
  199. return
  200. }
  201. c.JSON(http.StatusOK, gin.H{
  202. "success": true,
  203. "message": "",
  204. "data": users,
  205. })
  206. return
  207. }
  208. func GetUser(c *gin.Context) {
  209. id, err := strconv.Atoi(c.Param("id"))
  210. if err != nil {
  211. c.JSON(http.StatusOK, gin.H{
  212. "success": false,
  213. "message": err.Error(),
  214. })
  215. return
  216. }
  217. user, err := model.GetUserById(id, false)
  218. if err != nil {
  219. c.JSON(http.StatusOK, gin.H{
  220. "success": false,
  221. "message": err.Error(),
  222. })
  223. return
  224. }
  225. myRole := c.GetInt("role")
  226. if myRole <= user.Role && myRole != common.RoleRootUser {
  227. c.JSON(http.StatusOK, gin.H{
  228. "success": false,
  229. "message": "无权获取同级或更高等级用户的信息",
  230. })
  231. return
  232. }
  233. c.JSON(http.StatusOK, gin.H{
  234. "success": true,
  235. "message": "",
  236. "data": user,
  237. })
  238. return
  239. }
  240. func GenerateAccessToken(c *gin.Context) {
  241. id := c.GetInt("id")
  242. user, err := model.GetUserById(id, true)
  243. if err != nil {
  244. c.JSON(http.StatusOK, gin.H{
  245. "success": false,
  246. "message": err.Error(),
  247. })
  248. return
  249. }
  250. user.AccessToken = common.GetUUID()
  251. if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
  252. c.JSON(http.StatusOK, gin.H{
  253. "success": false,
  254. "message": "请重试,系统生成的 UUID 竟然重复了!",
  255. })
  256. return
  257. }
  258. if err := user.Update(false); err != nil {
  259. c.JSON(http.StatusOK, gin.H{
  260. "success": false,
  261. "message": err.Error(),
  262. })
  263. return
  264. }
  265. c.JSON(http.StatusOK, gin.H{
  266. "success": true,
  267. "message": "",
  268. "data": user.AccessToken,
  269. })
  270. return
  271. }
  272. func GetAffCode(c *gin.Context) {
  273. id := c.GetInt("id")
  274. user, err := model.GetUserById(id, true)
  275. if err != nil {
  276. c.JSON(http.StatusOK, gin.H{
  277. "success": false,
  278. "message": err.Error(),
  279. })
  280. return
  281. }
  282. if user.AffCode == "" {
  283. user.AffCode = common.GetRandomString(4)
  284. if err := user.Update(false); err != nil {
  285. c.JSON(http.StatusOK, gin.H{
  286. "success": false,
  287. "message": err.Error(),
  288. })
  289. return
  290. }
  291. }
  292. c.JSON(http.StatusOK, gin.H{
  293. "success": true,
  294. "message": "",
  295. "data": user.AffCode,
  296. })
  297. return
  298. }
  299. func GetSelf(c *gin.Context) {
  300. id := c.GetInt("id")
  301. user, err := model.GetUserById(id, false)
  302. if err != nil {
  303. c.JSON(http.StatusOK, gin.H{
  304. "success": false,
  305. "message": err.Error(),
  306. })
  307. return
  308. }
  309. c.JSON(http.StatusOK, gin.H{
  310. "success": true,
  311. "message": "",
  312. "data": user,
  313. })
  314. return
  315. }
  316. func UpdateUser(c *gin.Context) {
  317. var updatedUser model.User
  318. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  319. if err != nil || updatedUser.Id == 0 {
  320. c.JSON(http.StatusOK, gin.H{
  321. "success": false,
  322. "message": "无效的参数",
  323. })
  324. return
  325. }
  326. if updatedUser.Password == "" {
  327. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  328. }
  329. if err := common.Validate.Struct(&updatedUser); err != nil {
  330. c.JSON(http.StatusOK, gin.H{
  331. "success": false,
  332. "message": "输入不合法 " + err.Error(),
  333. })
  334. return
  335. }
  336. originUser, err := model.GetUserById(updatedUser.Id, false)
  337. if err != nil {
  338. c.JSON(http.StatusOK, gin.H{
  339. "success": false,
  340. "message": err.Error(),
  341. })
  342. return
  343. }
  344. myRole := c.GetInt("role")
  345. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  346. c.JSON(http.StatusOK, gin.H{
  347. "success": false,
  348. "message": "无权更新同权限等级或更高权限等级的用户信息",
  349. })
  350. return
  351. }
  352. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  353. c.JSON(http.StatusOK, gin.H{
  354. "success": false,
  355. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  356. })
  357. return
  358. }
  359. if updatedUser.Password == "$I_LOVE_U" {
  360. updatedUser.Password = "" // rollback to what it should be
  361. }
  362. updatePassword := updatedUser.Password != ""
  363. if err := updatedUser.Update(updatePassword); err != nil {
  364. c.JSON(http.StatusOK, gin.H{
  365. "success": false,
  366. "message": err.Error(),
  367. })
  368. return
  369. }
  370. if originUser.Quota != updatedUser.Quota {
  371. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", common.LogQuota(originUser.Quota), common.LogQuota(updatedUser.Quota)))
  372. }
  373. c.JSON(http.StatusOK, gin.H{
  374. "success": true,
  375. "message": "",
  376. })
  377. return
  378. }
  379. func UpdateSelf(c *gin.Context) {
  380. var user model.User
  381. err := json.NewDecoder(c.Request.Body).Decode(&user)
  382. if err != nil {
  383. c.JSON(http.StatusOK, gin.H{
  384. "success": false,
  385. "message": "无效的参数",
  386. })
  387. return
  388. }
  389. if user.Password == "" {
  390. user.Password = "$I_LOVE_U" // make Validator happy :)
  391. }
  392. if err := common.Validate.Struct(&user); err != nil {
  393. c.JSON(http.StatusOK, gin.H{
  394. "success": false,
  395. "message": "输入不合法 " + err.Error(),
  396. })
  397. return
  398. }
  399. cleanUser := model.User{
  400. Id: c.GetInt("id"),
  401. Username: user.Username,
  402. Password: user.Password,
  403. DisplayName: user.DisplayName,
  404. }
  405. if user.Password == "$I_LOVE_U" {
  406. user.Password = "" // rollback to what it should be
  407. cleanUser.Password = ""
  408. }
  409. updatePassword := user.Password != ""
  410. if err := cleanUser.Update(updatePassword); err != nil {
  411. c.JSON(http.StatusOK, gin.H{
  412. "success": false,
  413. "message": err.Error(),
  414. })
  415. return
  416. }
  417. c.JSON(http.StatusOK, gin.H{
  418. "success": true,
  419. "message": "",
  420. })
  421. return
  422. }
  423. func DeleteUser(c *gin.Context) {
  424. id, err := strconv.Atoi(c.Param("id"))
  425. if err != nil {
  426. c.JSON(http.StatusOK, gin.H{
  427. "success": false,
  428. "message": err.Error(),
  429. })
  430. return
  431. }
  432. originUser, err := model.GetUserById(id, false)
  433. if err != nil {
  434. c.JSON(http.StatusOK, gin.H{
  435. "success": false,
  436. "message": err.Error(),
  437. })
  438. return
  439. }
  440. myRole := c.GetInt("role")
  441. if myRole <= originUser.Role {
  442. c.JSON(http.StatusOK, gin.H{
  443. "success": false,
  444. "message": "无权删除同权限等级或更高权限等级的用户",
  445. })
  446. return
  447. }
  448. err = model.DeleteUserById(id)
  449. if err != nil {
  450. c.JSON(http.StatusOK, gin.H{
  451. "success": true,
  452. "message": "",
  453. })
  454. return
  455. }
  456. }
  457. func DeleteSelf(c *gin.Context) {
  458. id := c.GetInt("id")
  459. user, _ := model.GetUserById(id, false)
  460. if user.Role == common.RoleRootUser {
  461. c.JSON(http.StatusOK, gin.H{
  462. "success": false,
  463. "message": "不能删除超级管理员账户",
  464. })
  465. return
  466. }
  467. err := model.DeleteUserById(id)
  468. if err != nil {
  469. c.JSON(http.StatusOK, gin.H{
  470. "success": false,
  471. "message": err.Error(),
  472. })
  473. return
  474. }
  475. c.JSON(http.StatusOK, gin.H{
  476. "success": true,
  477. "message": "",
  478. })
  479. return
  480. }
  481. func CreateUser(c *gin.Context) {
  482. var user model.User
  483. err := json.NewDecoder(c.Request.Body).Decode(&user)
  484. if err != nil || user.Username == "" || user.Password == "" {
  485. c.JSON(http.StatusOK, gin.H{
  486. "success": false,
  487. "message": "无效的参数",
  488. })
  489. return
  490. }
  491. if err := common.Validate.Struct(&user); err != nil {
  492. c.JSON(http.StatusOK, gin.H{
  493. "success": false,
  494. "message": "输入不合法 " + err.Error(),
  495. })
  496. return
  497. }
  498. if user.DisplayName == "" {
  499. user.DisplayName = user.Username
  500. }
  501. myRole := c.GetInt("role")
  502. if user.Role >= myRole {
  503. c.JSON(http.StatusOK, gin.H{
  504. "success": false,
  505. "message": "无法创建权限大于等于自己的用户",
  506. })
  507. return
  508. }
  509. // Even for admin users, we cannot fully trust them!
  510. cleanUser := model.User{
  511. Username: user.Username,
  512. Password: user.Password,
  513. DisplayName: user.DisplayName,
  514. }
  515. if err := cleanUser.Insert(0); err != nil {
  516. c.JSON(http.StatusOK, gin.H{
  517. "success": false,
  518. "message": err.Error(),
  519. })
  520. return
  521. }
  522. c.JSON(http.StatusOK, gin.H{
  523. "success": true,
  524. "message": "",
  525. })
  526. return
  527. }
  528. type ManageRequest struct {
  529. Username string `json:"username"`
  530. Action string `json:"action"`
  531. }
  532. // ManageUser Only admin user can do this
  533. func ManageUser(c *gin.Context) {
  534. var req ManageRequest
  535. err := json.NewDecoder(c.Request.Body).Decode(&req)
  536. if err != nil {
  537. c.JSON(http.StatusOK, gin.H{
  538. "success": false,
  539. "message": "无效的参数",
  540. })
  541. return
  542. }
  543. user := model.User{
  544. Username: req.Username,
  545. }
  546. // Fill attributes
  547. model.DB.Where(&user).First(&user)
  548. if user.Id == 0 {
  549. c.JSON(http.StatusOK, gin.H{
  550. "success": false,
  551. "message": "用户不存在",
  552. })
  553. return
  554. }
  555. myRole := c.GetInt("role")
  556. if myRole <= user.Role && myRole != common.RoleRootUser {
  557. c.JSON(http.StatusOK, gin.H{
  558. "success": false,
  559. "message": "无权更新同权限等级或更高权限等级的用户信息",
  560. })
  561. return
  562. }
  563. switch req.Action {
  564. case "disable":
  565. user.Status = common.UserStatusDisabled
  566. if user.Role == common.RoleRootUser {
  567. c.JSON(http.StatusOK, gin.H{
  568. "success": false,
  569. "message": "无法禁用超级管理员用户",
  570. })
  571. return
  572. }
  573. case "enable":
  574. user.Status = common.UserStatusEnabled
  575. case "delete":
  576. if user.Role == common.RoleRootUser {
  577. c.JSON(http.StatusOK, gin.H{
  578. "success": false,
  579. "message": "无法删除超级管理员用户",
  580. })
  581. return
  582. }
  583. if err := user.Delete(); err != nil {
  584. c.JSON(http.StatusOK, gin.H{
  585. "success": false,
  586. "message": err.Error(),
  587. })
  588. return
  589. }
  590. case "promote":
  591. if myRole != common.RoleRootUser {
  592. c.JSON(http.StatusOK, gin.H{
  593. "success": false,
  594. "message": "普通管理员用户无法提升其他用户为管理员",
  595. })
  596. return
  597. }
  598. if user.Role >= common.RoleAdminUser {
  599. c.JSON(http.StatusOK, gin.H{
  600. "success": false,
  601. "message": "该用户已经是管理员",
  602. })
  603. return
  604. }
  605. user.Role = common.RoleAdminUser
  606. case "demote":
  607. if user.Role == common.RoleRootUser {
  608. c.JSON(http.StatusOK, gin.H{
  609. "success": false,
  610. "message": "无法降级超级管理员用户",
  611. })
  612. return
  613. }
  614. if user.Role == common.RoleCommonUser {
  615. c.JSON(http.StatusOK, gin.H{
  616. "success": false,
  617. "message": "该用户已经是普通用户",
  618. })
  619. return
  620. }
  621. user.Role = common.RoleCommonUser
  622. }
  623. if err := user.Update(false); err != nil {
  624. c.JSON(http.StatusOK, gin.H{
  625. "success": false,
  626. "message": err.Error(),
  627. })
  628. return
  629. }
  630. clearUser := model.User{
  631. Role: user.Role,
  632. Status: user.Status,
  633. }
  634. c.JSON(http.StatusOK, gin.H{
  635. "success": true,
  636. "message": "",
  637. "data": clearUser,
  638. })
  639. return
  640. }
  641. func EmailBind(c *gin.Context) {
  642. email := c.Query("email")
  643. code := c.Query("code")
  644. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  645. c.JSON(http.StatusOK, gin.H{
  646. "success": false,
  647. "message": "验证码错误或已过期",
  648. })
  649. return
  650. }
  651. id := c.GetInt("id")
  652. user := model.User{
  653. Id: id,
  654. }
  655. err := user.FillUserById()
  656. if err != nil {
  657. c.JSON(http.StatusOK, gin.H{
  658. "success": false,
  659. "message": err.Error(),
  660. })
  661. return
  662. }
  663. user.Email = email
  664. // no need to check if this email already taken, because we have used verification code to check it
  665. err = user.Update(false)
  666. if err != nil {
  667. c.JSON(http.StatusOK, gin.H{
  668. "success": false,
  669. "message": err.Error(),
  670. })
  671. return
  672. }
  673. if user.Role == common.RoleRootUser {
  674. common.RootUserEmail = email
  675. }
  676. c.JSON(http.StatusOK, gin.H{
  677. "success": true,
  678. "message": "",
  679. })
  680. return
  681. }
  682. type topUpRequest struct {
  683. Key string `json:"key"`
  684. }
  685. func TopUp(c *gin.Context) {
  686. req := topUpRequest{}
  687. err := c.ShouldBindJSON(&req)
  688. if err != nil {
  689. c.JSON(http.StatusOK, gin.H{
  690. "success": false,
  691. "message": err.Error(),
  692. })
  693. return
  694. }
  695. id := c.GetInt("id")
  696. quota, err := model.Redeem(req.Key, id)
  697. if err != nil {
  698. c.JSON(http.StatusOK, gin.H{
  699. "success": false,
  700. "message": err.Error(),
  701. })
  702. return
  703. }
  704. c.JSON(http.StatusOK, gin.H{
  705. "success": true,
  706. "message": "",
  707. "data": quota,
  708. })
  709. return
  710. }