user.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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. user.Password = ""
  74. user.Token = ""
  75. c.JSON(http.StatusOK, gin.H{
  76. "message": "",
  77. "success": true,
  78. "data": user,
  79. })
  80. }
  81. func Logout(c *gin.Context) {
  82. session := sessions.Default(c)
  83. session.Clear()
  84. err := session.Save()
  85. if err != nil {
  86. c.JSON(http.StatusOK, gin.H{
  87. "message": err.Error(),
  88. "success": false,
  89. })
  90. return
  91. }
  92. c.JSON(http.StatusOK, gin.H{
  93. "message": "",
  94. "success": true,
  95. })
  96. }
  97. func Register(c *gin.Context) {
  98. if !common.RegisterEnabled {
  99. c.JSON(http.StatusOK, gin.H{
  100. "message": "管理员关闭了新用户注册",
  101. "success": false,
  102. })
  103. return
  104. }
  105. if !common.PasswordRegisterEnabled {
  106. c.JSON(http.StatusOK, gin.H{
  107. "message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
  108. "success": false,
  109. })
  110. return
  111. }
  112. var user model.User
  113. err := json.NewDecoder(c.Request.Body).Decode(&user)
  114. if err != nil {
  115. c.JSON(http.StatusOK, gin.H{
  116. "success": false,
  117. "message": "无效的参数",
  118. })
  119. return
  120. }
  121. if err := common.Validate.Struct(&user); err != nil {
  122. c.JSON(http.StatusOK, gin.H{
  123. "success": false,
  124. "message": "输入不合法 " + err.Error(),
  125. })
  126. return
  127. }
  128. if common.EmailVerificationEnabled {
  129. if user.Email == "" || user.VerificationCode == "" {
  130. c.JSON(http.StatusOK, gin.H{
  131. "success": false,
  132. "message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
  133. })
  134. return
  135. }
  136. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  137. c.JSON(http.StatusOK, gin.H{
  138. "success": false,
  139. "message": "验证码错误或已过期",
  140. })
  141. return
  142. }
  143. }
  144. cleanUser := model.User{
  145. Username: user.Username,
  146. Password: user.Password,
  147. DisplayName: user.Username,
  148. }
  149. if common.EmailVerificationEnabled {
  150. cleanUser.Email = user.Email
  151. }
  152. if err := cleanUser.Insert(); err != nil {
  153. c.JSON(http.StatusOK, gin.H{
  154. "success": false,
  155. "message": err.Error(),
  156. })
  157. return
  158. }
  159. c.JSON(http.StatusOK, gin.H{
  160. "success": true,
  161. "message": "",
  162. })
  163. return
  164. }
  165. func GetAllUsers(c *gin.Context) {
  166. p, _ := strconv.Atoi(c.Query("p"))
  167. if p < 0 {
  168. p = 0
  169. }
  170. users, err := model.GetAllUsers(p*common.ItemsPerPage, common.ItemsPerPage)
  171. if err != nil {
  172. c.JSON(http.StatusOK, gin.H{
  173. "success": false,
  174. "message": err.Error(),
  175. })
  176. return
  177. }
  178. c.JSON(http.StatusOK, gin.H{
  179. "success": true,
  180. "message": "",
  181. "data": users,
  182. })
  183. return
  184. }
  185. func SearchUsers(c *gin.Context) {
  186. keyword := c.Query("keyword")
  187. users, err := model.SearchUsers(keyword)
  188. if err != nil {
  189. c.JSON(http.StatusOK, gin.H{
  190. "success": false,
  191. "message": err.Error(),
  192. })
  193. return
  194. }
  195. c.JSON(http.StatusOK, gin.H{
  196. "success": true,
  197. "message": "",
  198. "data": users,
  199. })
  200. return
  201. }
  202. func GetUser(c *gin.Context) {
  203. id, err := strconv.Atoi(c.Param("id"))
  204. if err != nil {
  205. c.JSON(http.StatusOK, gin.H{
  206. "success": false,
  207. "message": err.Error(),
  208. })
  209. return
  210. }
  211. user, err := model.GetUserById(id, false)
  212. if err != nil {
  213. c.JSON(http.StatusOK, gin.H{
  214. "success": false,
  215. "message": err.Error(),
  216. })
  217. return
  218. }
  219. myRole := c.GetInt("role")
  220. if myRole <= user.Role {
  221. c.JSON(http.StatusOK, gin.H{
  222. "success": false,
  223. "message": "无权获取同级或更高等级用户的信息",
  224. })
  225. return
  226. }
  227. c.JSON(http.StatusOK, gin.H{
  228. "success": true,
  229. "message": "",
  230. "data": user,
  231. })
  232. return
  233. }
  234. func GenerateToken(c *gin.Context) {
  235. id := c.GetInt("id")
  236. user, err := model.GetUserById(id, true)
  237. if err != nil {
  238. c.JSON(http.StatusOK, gin.H{
  239. "success": false,
  240. "message": err.Error(),
  241. })
  242. return
  243. }
  244. user.Token = uuid.New().String()
  245. user.Token = strings.Replace(user.Token, "-", "", -1)
  246. if model.DB.Where("token = ?", user.Token).First(user).RowsAffected != 0 {
  247. c.JSON(http.StatusOK, gin.H{
  248. "success": false,
  249. "message": "请重试,系统生成的 UUID 竟然重复了!",
  250. })
  251. return
  252. }
  253. if err := user.Update(false); err != nil {
  254. c.JSON(http.StatusOK, gin.H{
  255. "success": false,
  256. "message": err.Error(),
  257. })
  258. return
  259. }
  260. c.JSON(http.StatusOK, gin.H{
  261. "success": true,
  262. "message": "",
  263. "data": user.Token,
  264. })
  265. return
  266. }
  267. func GetSelf(c *gin.Context) {
  268. id := c.GetInt("id")
  269. user, err := model.GetUserById(id, false)
  270. if err != nil {
  271. c.JSON(http.StatusOK, gin.H{
  272. "success": false,
  273. "message": err.Error(),
  274. })
  275. return
  276. }
  277. c.JSON(http.StatusOK, gin.H{
  278. "success": true,
  279. "message": "",
  280. "data": user,
  281. })
  282. return
  283. }
  284. func UpdateUser(c *gin.Context) {
  285. var updatedUser model.User
  286. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  287. if err != nil || updatedUser.Id == 0 {
  288. c.JSON(http.StatusOK, gin.H{
  289. "success": false,
  290. "message": "无效的参数",
  291. })
  292. return
  293. }
  294. if updatedUser.Password == "" {
  295. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  296. }
  297. if err := common.Validate.Struct(&updatedUser); err != nil {
  298. c.JSON(http.StatusOK, gin.H{
  299. "success": false,
  300. "message": "输入不合法 " + err.Error(),
  301. })
  302. return
  303. }
  304. originUser, err := model.GetUserById(updatedUser.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 <= originUser.Role {
  314. c.JSON(http.StatusOK, gin.H{
  315. "success": false,
  316. "message": "无权更新同权限等级或更高权限等级的用户信息",
  317. })
  318. return
  319. }
  320. if myRole <= updatedUser.Role {
  321. c.JSON(http.StatusOK, gin.H{
  322. "success": false,
  323. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  324. })
  325. return
  326. }
  327. if updatedUser.Password == "$I_LOVE_U" {
  328. updatedUser.Password = "" // rollback to what it should be
  329. }
  330. // We only allow admin change those fields.
  331. cleanUser := model.User{
  332. Id: updatedUser.Id,
  333. Username: updatedUser.Username,
  334. Password: updatedUser.Password,
  335. DisplayName: updatedUser.DisplayName,
  336. }
  337. updatePassword := cleanUser.Password != ""
  338. if err := cleanUser.Update(updatePassword); err != nil {
  339. c.JSON(http.StatusOK, gin.H{
  340. "success": false,
  341. "message": err.Error(),
  342. })
  343. return
  344. }
  345. c.JSON(http.StatusOK, gin.H{
  346. "success": true,
  347. "message": "",
  348. })
  349. return
  350. }
  351. func UpdateSelf(c *gin.Context) {
  352. var user model.User
  353. err := json.NewDecoder(c.Request.Body).Decode(&user)
  354. if err != nil {
  355. c.JSON(http.StatusOK, gin.H{
  356. "success": false,
  357. "message": "无效的参数",
  358. })
  359. return
  360. }
  361. if user.Password == "" {
  362. user.Password = "$I_LOVE_U" // make Validator happy :)
  363. }
  364. if err := common.Validate.Struct(&user); err != nil {
  365. c.JSON(http.StatusOK, gin.H{
  366. "success": false,
  367. "message": "输入不合法 " + err.Error(),
  368. })
  369. return
  370. }
  371. originUser, err := model.GetUserById(c.GetInt("id"), true)
  372. if err != nil {
  373. c.JSON(http.StatusOK, gin.H{
  374. "success": false,
  375. "message": err.Error(),
  376. })
  377. return
  378. }
  379. cleanUser := model.User{
  380. Id: c.GetInt("id"),
  381. Username: user.Username,
  382. Password: user.Password,
  383. DisplayName: user.DisplayName,
  384. Token: user.Token,
  385. Channel: user.Channel,
  386. WeChatTestAccountId: user.WeChatTestAccountId,
  387. WeChatTestAccountSecret: user.WeChatTestAccountSecret,
  388. WeChatTestAccountTemplateId: user.WeChatTestAccountTemplateId,
  389. WeChatTestAccountOpenId: user.WeChatTestAccountOpenId,
  390. WeChatTestAccountVerificationToken: user.WeChatTestAccountVerificationToken,
  391. WeChatCorpAccountId: user.WeChatCorpAccountId,
  392. WeChatCorpAccountAgentSecret: user.WeChatCorpAccountAgentSecret,
  393. WeChatCorpAccountAgentId: user.WeChatCorpAccountAgentId,
  394. WeChatCorpAccountUserId: user.WeChatCorpAccountUserId,
  395. WeChatCorpAccountClientType: user.WeChatCorpAccountClientType,
  396. LarkWebhookURL: user.LarkWebhookURL,
  397. LarkWebhookSecret: user.LarkWebhookSecret,
  398. DingWebhookURL: user.DingWebhookURL,
  399. DingWebhookSecret: user.DingWebhookSecret,
  400. BarkServer: user.BarkServer,
  401. BarkSecret: user.BarkSecret,
  402. }
  403. channel.TokenStoreUpdateUser(&cleanUser, originUser)
  404. if user.Password == "$I_LOVE_U" {
  405. user.Password = "" // rollback to what it should be
  406. cleanUser.Password = ""
  407. }
  408. updatePassword := user.Password != ""
  409. if err := cleanUser.Update(updatePassword); err != nil {
  410. c.JSON(http.StatusOK, gin.H{
  411. "success": false,
  412. "message": err.Error(),
  413. })
  414. return
  415. }
  416. c.JSON(http.StatusOK, gin.H{
  417. "success": true,
  418. "message": "",
  419. })
  420. return
  421. }
  422. func DeleteUser(c *gin.Context) {
  423. id, err := strconv.Atoi(c.Param("id"))
  424. if err != nil {
  425. c.JSON(http.StatusOK, gin.H{
  426. "success": false,
  427. "message": err.Error(),
  428. })
  429. return
  430. }
  431. originUser, err := model.GetUserById(id, false)
  432. if err != nil {
  433. c.JSON(http.StatusOK, gin.H{
  434. "success": false,
  435. "message": err.Error(),
  436. })
  437. return
  438. }
  439. myRole := c.GetInt("role")
  440. if myRole <= originUser.Role {
  441. c.JSON(http.StatusOK, gin.H{
  442. "success": false,
  443. "message": "无权删除同权限等级或更高权限等级的用户",
  444. })
  445. return
  446. }
  447. channel.TokenStoreRemoveUser(originUser)
  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.User{Id: id}
  460. user.FillUserById()
  461. channel.TokenStoreRemoveUser(&user)
  462. err := model.DeleteUserById(id)
  463. if err != nil {
  464. c.JSON(http.StatusOK, gin.H{
  465. "success": false,
  466. "message": err.Error(),
  467. })
  468. return
  469. }
  470. c.JSON(http.StatusOK, gin.H{
  471. "success": true,
  472. "message": "",
  473. })
  474. return
  475. }
  476. func CreateUser(c *gin.Context) {
  477. var user model.User
  478. err := json.NewDecoder(c.Request.Body).Decode(&user)
  479. if err != nil || user.Username == "" || user.Password == "" {
  480. c.JSON(http.StatusOK, gin.H{
  481. "success": false,
  482. "message": "无效的参数",
  483. })
  484. return
  485. }
  486. if user.DisplayName == "" {
  487. user.DisplayName = user.Username
  488. }
  489. myRole := c.GetInt("role")
  490. if user.Role >= myRole {
  491. c.JSON(http.StatusOK, gin.H{
  492. "success": false,
  493. "message": "无法创建权限大于等于自己的用户",
  494. })
  495. return
  496. }
  497. // Even for admin users, we cannot fully trust them!
  498. cleanUser := model.User{
  499. Username: user.Username,
  500. Password: user.Password,
  501. DisplayName: user.DisplayName,
  502. }
  503. if err := cleanUser.Insert(); err != nil {
  504. c.JSON(http.StatusOK, gin.H{
  505. "success": false,
  506. "message": err.Error(),
  507. })
  508. return
  509. }
  510. c.JSON(http.StatusOK, gin.H{
  511. "success": true,
  512. "message": "",
  513. })
  514. return
  515. }
  516. type ManageRequest struct {
  517. Username string `json:"username"`
  518. Action string `json:"action"`
  519. }
  520. // ManageUser Only admin user can do this
  521. func ManageUser(c *gin.Context) {
  522. var req ManageRequest
  523. err := json.NewDecoder(c.Request.Body).Decode(&req)
  524. if err != nil {
  525. c.JSON(http.StatusOK, gin.H{
  526. "success": false,
  527. "message": "无效的参数",
  528. })
  529. return
  530. }
  531. user := model.User{
  532. Username: req.Username,
  533. }
  534. // Fill attributes
  535. model.DB.Where(&user).First(&user)
  536. if user.Id == 0 {
  537. c.JSON(http.StatusOK, gin.H{
  538. "success": false,
  539. "message": "用户不存在",
  540. })
  541. return
  542. }
  543. myRole := c.GetInt("role")
  544. if myRole <= user.Role {
  545. c.JSON(http.StatusOK, gin.H{
  546. "success": false,
  547. "message": "无权更新同权限等级或更高权限等级的用户信息",
  548. })
  549. return
  550. }
  551. switch req.Action {
  552. case "disable":
  553. user.Status = common.UserStatusDisabled
  554. case "enable":
  555. user.Status = common.UserStatusEnabled
  556. case "delete":
  557. if err := user.Delete(); err != nil {
  558. c.JSON(http.StatusOK, gin.H{
  559. "success": false,
  560. "message": err.Error(),
  561. })
  562. return
  563. }
  564. case "promote":
  565. if myRole != common.RoleRootUser {
  566. c.JSON(http.StatusOK, gin.H{
  567. "success": false,
  568. "message": "普通管理员用户无法提升其他用户为管理员",
  569. })
  570. return
  571. }
  572. user.Role = common.RoleAdminUser
  573. case "demote":
  574. user.Role = common.RoleCommonUser
  575. }
  576. if err := user.Update(false); err != nil {
  577. c.JSON(http.StatusOK, gin.H{
  578. "success": false,
  579. "message": err.Error(),
  580. })
  581. return
  582. }
  583. clearUser := model.User{
  584. Role: user.Role,
  585. Status: user.Status,
  586. }
  587. c.JSON(http.StatusOK, gin.H{
  588. "success": true,
  589. "message": "",
  590. "data": clearUser,
  591. })
  592. return
  593. }
  594. func EmailBind(c *gin.Context) {
  595. email := c.Query("email")
  596. code := c.Query("code")
  597. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  598. c.JSON(http.StatusOK, gin.H{
  599. "success": false,
  600. "message": "验证码错误或已过期",
  601. })
  602. return
  603. }
  604. id := c.GetInt("id")
  605. user := model.User{
  606. Id: id,
  607. }
  608. user.FillUserById()
  609. user.Email = email
  610. // no need to check if this email already taken, because we have used verification code to check it
  611. err := user.Update(false)
  612. if err != nil {
  613. c.JSON(http.StatusOK, gin.H{
  614. "success": false,
  615. "message": err.Error(),
  616. })
  617. return
  618. }
  619. c.JSON(http.StatusOK, gin.H{
  620. "success": true,
  621. "message": "",
  622. })
  623. return
  624. }