login.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package controllers
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. log "github.com/sirupsen/logrus"
  6. "io"
  7. "net/http"
  8. "pmail/db"
  9. "pmail/dto"
  10. "pmail/dto/response"
  11. "pmail/i18n"
  12. "pmail/models"
  13. "pmail/session"
  14. "pmail/utils/password"
  15. )
  16. type loginRequest struct {
  17. Account string `json:"account"`
  18. Password string `json:"password"`
  19. }
  20. func Login(ctx *dto.Context, w http.ResponseWriter, req *http.Request) {
  21. reqBytes, err := io.ReadAll(req.Body)
  22. if err != nil {
  23. log.Errorf("%+v", err)
  24. }
  25. var reqData loginRequest
  26. err = json.Unmarshal(reqBytes, &reqData)
  27. if err != nil {
  28. log.Errorf("%+v", err)
  29. }
  30. var user models.User
  31. encodePwd := password.Encode(reqData.Password)
  32. err = db.Instance.Get(&user, db.WithContext(ctx, "select * from user where account =? and password =?"),
  33. reqData.Account, encodePwd)
  34. if err != nil && err != sql.ErrNoRows {
  35. log.Errorf("%+v", err)
  36. }
  37. if user.ID != 0 {
  38. userStr, _ := json.Marshal(user)
  39. session.Instance.Put(req.Context(), "user", string(userStr))
  40. response.NewSuccessResponse("").FPrint(w)
  41. } else {
  42. response.NewErrorResponse(response.ParamsError, i18n.GetText(ctx.Lang, "aperror"), "").FPrint(w)
  43. }
  44. }