func login(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() req := loginReq{} if err := util.ParseJSON(r.Body, w, &req); err != nil { // ParseJSON handles error reponse return } user, err := models.GetUser("", req.Email) if err != nil { logger.Debug.Println("User not found") util.JSONResponse(w, incorectEmailOrPassword, 401) return } if !user.CheckPass(req.Password) { logger.Debug.Println("Incorrect Password") util.JSONResponse(w, incorectEmailOrPassword, 401) return } token, err := userToken.New(user.ID, time.Now().Add(userTokenExp)) if err != nil { logger.Error.Print(err) w.WriteHeader(500) return } util.JSONResponse(w, loginRes{Token: token}, 200) }
func register(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() req := registerReq{} if err := util.ParseJSON(r.Body, w, &req); err != nil { return } _, msg, err := models.NewUser(req.Email, req.Password) if err != nil { w.WriteHeader(500) return } if len(msg) > 0 { util.JSONResponse(w, validate.ValidationMsgsToJSON(msg), 400) return } w.WriteHeader(201) }
func updateUser(w http.ResponseWriter, r *http.Request, u *models.User) { defer r.Body.Close() req := registerReq{} if err := util.ParseJSON(r.Body, w, &req); err != nil { return } msg, err := u.Update(req.Email, req.Password) if err != nil { w.WriteHeader(500) return } if len(msg) > 0 { util.JSONResponse(w, validate.ValidationMsgsToJSON(msg), 400) return } util.JSONResponse(w, u, 200) }