Kaynağa Gözat

login endpoint -> body params

Alexander Belanger 5 yıl önce
ebeveyn
işleme
657a8c94af
2 değiştirilmiş dosya ile 43 ekleme ve 12 silme
  1. 25 0
      internal/forms/user.go
  2. 18 12
      server/api/user_handler.go

+ 25 - 0
internal/forms/user.go

@@ -33,6 +33,31 @@ func (cuf *CreateUserForm) ToUser() (*models.User, error) {
 	}, nil
 }
 
+// LoginUserForm represents the accepted values for logging a user in
+type LoginUserForm struct {
+	WriteUserForm
+	ID       uint   `form:"required"`
+	Email    string `json:"email" form:"required,max=255,email"`
+	Password string `json:"password" form:"required,max=255"`
+}
+
+// ToUser converts a LoginUserForm to models.User
+func (luf *LoginUserForm) ToUser() (*models.User, error) {
+	hashed, err := bcrypt.GenerateFromPassword([]byte(luf.Password), 8)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return &models.User{
+		Model: gorm.Model{
+			ID: luf.ID,
+		},
+		Email:    luf.Email,
+		Password: string(hashed),
+	}, nil
+}
+
 // UpdateUserForm represents the accepted values for updating a user
 //
 // ID is a query parameter, the other two are sent in JSON body

+ 18 - 12
server/api/user_handler.go

@@ -47,25 +47,31 @@ func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
 // HandleLoginUser checks the request header for cookie and validates the user.
 func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
 	session, _ := app.store.Get(r, "cookie-name")
+	form := &forms.LoginUserForm{}
 
-	// read in email and password from request
-	email := chi.URLParam(r, "email")
-	password := chi.URLParam(r, "password")
+	// decode from JSON to form value
+	if err := json.NewDecoder(r.Body).Decode(form); err != nil {
+		app.handleErrorFormDecoding(err, ErrUserDecode, w)
+		return
+	}
 
-	// Authentication goes here
-	// Select User by Username (app.repo.User.ReadUserByUsername) and return storedCreds object that has Password.
-	storedUser, readErr := app.repo.User.ReadUserByEmail(email)
+	storedUser, readErr := app.repo.User.ReadUserByEmail(form.Email)
 
 	if readErr != nil {
-		// You're not registered error
-		app.logger.Warn().Err(readErr)
-		w.WriteHeader(http.StatusUnauthorized)
+		app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
+			Errors: []string{"email not registered"},
+			Code:   http.StatusUnauthorized,
+		}, w)
+
 		return
 	}
 
-	if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(password)); err != nil {
-		// If the two passwords don't match, return a 401 status
-		w.WriteHeader(http.StatusUnauthorized)
+	if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
+		app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
+			Errors: []string{"incorrect password"},
+			Code:   http.StatusUnauthorized,
+		}, w)
+
 		return
 	}