예제 #1
0
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)
}
예제 #2
0
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)
}
예제 #3
0
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)
}