user.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "github.com/astaxie/beego/logs"
  5. "github.com/astaxie/beego/orm"
  6. "server/models"
  7. "server/utils"
  8. )
  9. type UserController struct {
  10. BaseController
  11. }
  12. // Login 登录
  13. func (c *UserController) Login() {
  14. var user models.User
  15. err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
  16. if err != nil {
  17. logs.Error(err, string(c.Ctx.Input.RequestBody))
  18. c.ErrorJson(err)
  19. return
  20. }
  21. cipherPassword := user.Password
  22. o := orm.NewOrm()
  23. err = o.Read(&user, "Account")
  24. if err != nil {
  25. c.ErrorJson(err)
  26. return
  27. }
  28. encryptPassword := utils.GetSHA256HashCode(cipherPassword)
  29. if encryptPassword != user.Password {
  30. c.setCode(-1).setMsg("用户名或者密码不正确!").json()
  31. return
  32. }
  33. user.Password = ""
  34. c.SetSession("user", user)
  35. c.setData(user).json()
  36. }
  37. func (c *UserController) User() {
  38. user := c.RequiredUser()
  39. if user == nil {
  40. return
  41. }
  42. c.setData(user).json()
  43. }
  44. // Register 用户注册
  45. func (c *UserController) Register() {
  46. var user models.User
  47. err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
  48. if err != nil {
  49. logs.Error(err, string(c.Ctx.Input.RequestBody))
  50. c.ErrorJson(err)
  51. return
  52. }
  53. if len(user.Account) == 0 || len(user.Password) == 0 {
  54. c.setCode(-1).setMsg("账号或者密码不能为空!")
  55. c.json()
  56. return
  57. }
  58. if len(user.Nickname) == 0 {
  59. user.Nickname = user.Account
  60. }
  61. user.Password = utils.GetSHA256HashCode(user.Password)
  62. o := orm.NewOrm()
  63. _, err = o.Insert(&user)
  64. if err != nil {
  65. c.ErrorJson(err)
  66. return
  67. }
  68. c.setMsg("注册成功!").json()
  69. }