user.go 15 KB

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