login.go 1.3 KB

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