Skip to content

Instantly share code, notes, and snippets.

@linux08
Last active May 4, 2019 11:47
Show Gist options
  • Save linux08/5429266b7290aac1106ea5b91e17c842 to your computer and use it in GitHub Desktop.
Save linux08/5429266b7290aac1106ea5b91e17c842 to your computer and use it in GitHub Desktop.
func Login(w http.ResponseWriter, r *http.Request) {
user := &models.User{}
err := json.NewDecoder(r.Body).Decode(user)
if err != nil {
var resp = map[string]interface{}{"status": false, "message": "Invalid request"}
json.NewEncoder(w).Encode(resp)
return
}
resp := FindOne(user.Email, user.Password)
json.NewEncoder(w).Encode(resp)
}
func FindOne(email, password string) map[string]interface{} {
user := &models.User{}
if err := db.Where("Email = ?", email).First(user).Error; err != nil {
var resp = map[string]interface{}{"status": false, "message": "Email address not found"}
return resp
}
expiresAt := time.Now().Add(time.Minute * 100000).Unix()
errf := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if errf != nil && errf == bcrypt.ErrMismatchedHashAndPassword { //Password does not match!
var resp = map[string]interface{}{"status": false, "message": "Invalid login credentials. Please try again"}
return resp
}
tk := &models.Token{
UserID: user.ID,
Name: user.Name,
Email: user.Email,
StandardClaims: &jwt.StandardClaims{
ExpiresAt: expiresAt,
},
}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
tokenString, error := token.SignedString([]byte("secret"))
if error != nil {
fmt.Println(error)
}
var resp = map[string]interface{}{"status": false, "message": "logged in"}
resp["token"] = tokenString //Store the token in the response
resp["user"] = user
return resp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment