user.go 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package controllers
  2. import (
  3. "wechat-conf/models/model"
  4. "wechat-conf/service/user"
  5. "wechat-conf/utils"
  6. "github.com/astaxie/beego"
  7. )
  8. // UserController 用户
  9. type UserController struct {
  10. serv *user.UserServ
  11. BaseController
  12. }
  13. // Constructor 初始化 Controller
  14. // @Title Constructor
  15. // @Description 初始化 Controller, 系统自动调用
  16. func (c *UserController) Constructor() {
  17. c.serv = user.NewUserServ(c.Context)
  18. }
  19. // Login 用户登录
  20. func (c *UserController) Login() {
  21. var user *model.SysUser
  22. var err error
  23. // 如果有 session 就算已经登录
  24. userId := c.GetSession(SESSION_USER)
  25. if userId != nil {
  26. c.ResponseError(utils.LogError("用户已经登录!"))
  27. }
  28. userName := c.GetString("UserName")
  29. pwd := c.GetString("UserPass")
  30. if userName == "" || pwd == "" {
  31. c.ResponseError(utils.LogError("用户名或密码不能为空!"))
  32. }
  33. user, err = c.serv.ValidUserNameLogin(userName, pwd)
  34. if err != nil {
  35. beego.Error("用户登录失败, ", err)
  36. c.ResponseError(utils.LogError("用户名或密码错误"))
  37. }
  38. // 密码不能送到前端
  39. user.Pwd = ""
  40. c.SetSession(SESSION_USER, user.UserId)
  41. c.ResponseJSON(user)
  42. }
  43. // SignOut 登出
  44. // @Title 登出
  45. // @Description 登出
  46. // @Success 200 string ok-string
  47. // @Failure >300 error message
  48. func (c *UserController) SignOut() {
  49. c.Context.Set("user", nil)
  50. c.DestroySession()
  51. c.ResponseJSON("ok")
  52. }
  53. // UpdatePassword 更新用户密码
  54. // @Title 更新用户密码
  55. // @Description 更新用户密码
  56. // @Param oriPasswd form string true "旧密码"
  57. // @Param newPasswd form string true "新密码"
  58. // @Success 200 string ok-string
  59. // @Failure >300 error message
  60. func (c *UserController) UpdatePassword() {
  61. oriPasswd := c.GetString("oriPasswd")
  62. newPasswd := c.GetString("newPasswd")
  63. user := c.Context.Get("user").(*model.SysUser)
  64. if !c.serv.ValidatePassword(user, oriPasswd) {
  65. c.ResponseError(utils.LogError("原始密码不正确"))
  66. }
  67. if err := c.serv.UpdatePassword(user.UserId, newPasswd); err != nil {
  68. c.ResponseError(err)
  69. }
  70. c.ResponseJSON("ok")
  71. }
  72. // GetUser 获取用户信息
  73. func (c *UserController) GetUser() {
  74. user := c.Context.Get("user").(*model.SysUser)
  75. c.ResponseJSON(user)
  76. }