From b8738e9b522c4a86102f4ada689d548b3add60ae Mon Sep 17 00:00:00 2001 From: konrad Date: Wed, 8 Nov 2017 17:06:06 +0100 Subject: [PATCH] Implemented method to accept user login as json --- models/user.go | 8 ++++---- routes/login.go | 14 +++++++++++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/models/user.go b/models/user.go index 74ebba0..8101ad6 100644 --- a/models/user.go +++ b/models/user.go @@ -3,6 +3,7 @@ package models import ( "fmt" "golang.org/x/crypto/bcrypt" + "git.mowie.cc/konrad/Library/routes" ) // User holds information about an user @@ -28,11 +29,10 @@ func HashPassword(password string) (string, error) { } // CheckUserCredentials checks user credentials -func CheckUserCredentials(username, password string) (User, error) { +func CheckUserCredentials(u routes.UserLogin) (User, error) { - fmt.Println(username, password) // Check if the user exists - var user = User{Username: username} + var user = User{Username: u.Username} exists, err := x.Get(&user) if err != nil { return User{}, err @@ -43,7 +43,7 @@ func CheckUserCredentials(username, password string) (User, error) { } // Check the users password - err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) + err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(u.Password)) if err != nil { return User{}, err diff --git a/routes/login.go b/routes/login.go index 2c05b82..c82a4d2 100644 --- a/routes/login.go +++ b/routes/login.go @@ -8,13 +8,21 @@ import ( "time" ) +// User Login-Object to recive user credentials in JSON format +type UserLogin struct { + Username string `json:"username" form:"username"` + Password string `json:"password" form:"password"` +} + // Login is the login handler func Login(c echo.Context) error { - username := c.FormValue("username") - password := c.FormValue("password") + u := new(UserLogin) + if err := c.Bind(u); err != nil { + return c.JSON(http.StatusBadRequest, models.Message{"Please provide a username and password."}) + } // Check user - user, err := models.CheckUserCredentials(username, password) + user, err := models.CheckUserCredentials(u) if err != nil { return c.JSON(http.StatusUnauthorized, models.Message{"Wrong username or password."})