user.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. originUser, err := model.GetUserById(c.GetInt("id"), true)
  377. if err != nil {
  378. c.JSON(http.StatusOK, gin.H{
  379. "success": false,
  380. "message": err.Error(),
  381. })
  382. return
  383. }
  384. // White list mode. For safe :)
  385. cleanUser := model.User{
  386. Id: c.GetInt("id"),
  387. Username: user.Username,
  388. Password: user.Password,
  389. DisplayName: user.DisplayName,
  390. Token: user.Token,
  391. Channel: user.Channel,
  392. WeChatTestAccountId: user.WeChatTestAccountId,
  393. WeChatTestAccountSecret: user.WeChatTestAccountSecret,
  394. WeChatTestAccountTemplateId: user.WeChatTestAccountTemplateId,
  395. WeChatTestAccountOpenId: user.WeChatTestAccountOpenId,
  396. WeChatTestAccountVerificationToken: user.WeChatTestAccountVerificationToken,
  397. WeChatCorpAccountId: user.WeChatCorpAccountId,
  398. WeChatCorpAccountAgentSecret: user.WeChatCorpAccountAgentSecret,
  399. WeChatCorpAccountAgentId: user.WeChatCorpAccountAgentId,
  400. WeChatCorpAccountUserId: user.WeChatCorpAccountUserId,
  401. WeChatCorpAccountClientType: user.WeChatCorpAccountClientType,
  402. CorpWebhookURL: user.CorpWebhookURL,
  403. LarkWebhookURL: user.LarkWebhookURL,
  404. LarkWebhookSecret: user.LarkWebhookSecret,
  405. DingWebhookURL: user.DingWebhookURL,
  406. DingWebhookSecret: user.DingWebhookSecret,
  407. BarkServer: user.BarkServer,
  408. BarkSecret: user.BarkSecret,
  409. ClientSecret: user.ClientSecret,
  410. TelegramBotToken: user.TelegramBotToken,
  411. TelegramChatId: user.TelegramChatId,
  412. DiscordWebhookURL: user.DiscordWebhookURL,
  413. }
  414. channel.TokenStoreUpdateUser(&cleanUser, originUser)
  415. if user.Password == "$I_LOVE_U" {
  416. user.Password = "" // rollback to what it should be
  417. cleanUser.Password = ""
  418. }
  419. updatePassword := user.Password != ""
  420. if err := cleanUser.Update(updatePassword); err != nil {
  421. c.JSON(http.StatusOK, gin.H{
  422. "success": false,
  423. "message": err.Error(),
  424. })
  425. return
  426. }
  427. c.JSON(http.StatusOK, gin.H{
  428. "success": true,
  429. "message": "",
  430. })
  431. return
  432. }
  433. func DeleteUser(c *gin.Context) {
  434. id, err := strconv.Atoi(c.Param("id"))
  435. if err != nil {
  436. c.JSON(http.StatusOK, gin.H{
  437. "success": false,
  438. "message": err.Error(),
  439. })
  440. return
  441. }
  442. originUser, err := model.GetUserById(id, false)
  443. if err != nil {
  444. c.JSON(http.StatusOK, gin.H{
  445. "success": false,
  446. "message": err.Error(),
  447. })
  448. return
  449. }
  450. myRole := c.GetInt("role")
  451. if myRole <= originUser.Role {
  452. c.JSON(http.StatusOK, gin.H{
  453. "success": false,
  454. "message": "无权删除同权限等级或更高权限等级的用户",
  455. })
  456. return
  457. }
  458. channel.TokenStoreRemoveUser(originUser)
  459. err = model.DeleteUserById(id)
  460. if err != nil {
  461. c.JSON(http.StatusOK, gin.H{
  462. "success": true,
  463. "message": "",
  464. })
  465. return
  466. }
  467. }
  468. func DeleteSelf(c *gin.Context) {
  469. id := c.GetInt("id")
  470. user := model.User{Id: id}
  471. err := user.FillUserById()
  472. if err != nil {
  473. c.JSON(http.StatusOK, gin.H{
  474. "success": false,
  475. "message": err.Error(),
  476. })
  477. return
  478. }
  479. channel.TokenStoreRemoveUser(&user)
  480. err = model.DeleteUserById(id)
  481. if err != nil {
  482. c.JSON(http.StatusOK, gin.H{
  483. "success": false,
  484. "message": err.Error(),
  485. })
  486. return
  487. }
  488. c.JSON(http.StatusOK, gin.H{
  489. "success": true,
  490. "message": "",
  491. })
  492. return
  493. }
  494. func CreateUser(c *gin.Context) {
  495. var user model.User
  496. err := json.NewDecoder(c.Request.Body).Decode(&user)
  497. if err != nil || user.Username == "" || user.Password == "" {
  498. c.JSON(http.StatusOK, gin.H{
  499. "success": false,
  500. "message": "无效的参数",
  501. })
  502. return
  503. }
  504. if user.DisplayName == "" {
  505. user.DisplayName = user.Username
  506. }
  507. myRole := c.GetInt("role")
  508. if user.Role >= myRole {
  509. c.JSON(http.StatusOK, gin.H{
  510. "success": false,
  511. "message": "无法创建权限大于等于自己的用户",
  512. })
  513. return
  514. }
  515. // Even for admin users, we cannot fully trust them!
  516. cleanUser := model.User{
  517. Username: user.Username,
  518. Password: user.Password,
  519. DisplayName: user.DisplayName,
  520. }
  521. if err := cleanUser.Insert(); err != nil {
  522. c.JSON(http.StatusOK, gin.H{
  523. "success": false,
  524. "message": err.Error(),
  525. })
  526. return
  527. }
  528. c.JSON(http.StatusOK, gin.H{
  529. "success": true,
  530. "message": "",
  531. })
  532. return
  533. }
  534. type ManageRequest struct {
  535. Username string `json:"username"`
  536. Action string `json:"action"`
  537. }
  538. // ManageUser Only admin user can do this
  539. func ManageUser(c *gin.Context) {
  540. var req ManageRequest
  541. err := json.NewDecoder(c.Request.Body).Decode(&req)
  542. if err != nil {
  543. c.JSON(http.StatusOK, gin.H{
  544. "success": false,
  545. "message": "无效的参数",
  546. })
  547. return
  548. }
  549. user := model.User{
  550. Username: req.Username,
  551. }
  552. // Fill attributes
  553. model.DB.Where(&user).First(&user)
  554. if user.Id == 0 {
  555. c.JSON(http.StatusOK, gin.H{
  556. "success": false,
  557. "message": "用户不存在",
  558. })
  559. return
  560. }
  561. myRole := c.GetInt("role")
  562. if myRole <= user.Role {
  563. c.JSON(http.StatusOK, gin.H{
  564. "success": false,
  565. "message": "无权更新同权限等级或更高权限等级的用户信息",
  566. })
  567. return
  568. }
  569. switch req.Action {
  570. case "disable":
  571. if user.Status == common.UserStatusDisabled {
  572. c.JSON(http.StatusOK, gin.H{
  573. "success": false,
  574. "message": "该账户已经是封禁状态",
  575. })
  576. return
  577. }
  578. channel.TokenStoreRemoveUser(&user)
  579. user.Status = common.UserStatusDisabled
  580. case "enable":
  581. if user.Status == common.UserStatusEnabled {
  582. c.JSON(http.StatusOK, gin.H{
  583. "success": false,
  584. "message": "该账户已经是启用状态",
  585. })
  586. return
  587. }
  588. channel.TokenStoreAddUser(&user)
  589. user.Status = common.UserStatusEnabled
  590. case "delete":
  591. if err := user.Delete(); err != nil {
  592. c.JSON(http.StatusOK, gin.H{
  593. "success": false,
  594. "message": err.Error(),
  595. })
  596. return
  597. }
  598. case "promote":
  599. if myRole != common.RoleRootUser {
  600. c.JSON(http.StatusOK, gin.H{
  601. "success": false,
  602. "message": "普通管理员用户无法提升其他用户为管理员",
  603. })
  604. return
  605. }
  606. user.Role = common.RoleAdminUser
  607. case "demote":
  608. user.Role = common.RoleCommonUser
  609. }
  610. if err := user.Update(false); err != nil {
  611. c.JSON(http.StatusOK, gin.H{
  612. "success": false,
  613. "message": err.Error(),
  614. })
  615. return
  616. }
  617. clearUser := model.User{
  618. Role: user.Role,
  619. Status: user.Status,
  620. }
  621. c.JSON(http.StatusOK, gin.H{
  622. "success": true,
  623. "message": "",
  624. "data": clearUser,
  625. })
  626. return
  627. }
  628. func EmailBind(c *gin.Context) {
  629. email := c.Query("email")
  630. code := c.Query("code")
  631. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  632. c.JSON(http.StatusOK, gin.H{
  633. "success": false,
  634. "message": "验证码错误或已过期",
  635. })
  636. return
  637. }
  638. id := c.GetInt("id")
  639. user := model.User{
  640. Id: id,
  641. }
  642. err := user.FillUserById()
  643. if err != nil {
  644. c.JSON(http.StatusOK, gin.H{
  645. "success": false,
  646. "message": err.Error(),
  647. })
  648. return
  649. }
  650. user.Email = email
  651. // no need to check if this email already taken, because we have used verification code to check it
  652. err = user.Update(false)
  653. if err != nil {
  654. c.JSON(http.StatusOK, gin.H{
  655. "success": false,
  656. "message": err.Error(),
  657. })
  658. return
  659. }
  660. c.JSON(http.StatusOK, gin.H{
  661. "success": true,
  662. "message": "",
  663. })
  664. return
  665. }