Ejemplo n.º 1
0
func (ur UserResource) createUser(req *restful.Request, resp *restful.Response) {

	usr := new(models.User)
	err := req.ReadEntity(usr)

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	allErrs := validation.ValidateUserRegister(usr)

	if len(allErrs) != 0 {
		resp.WriteHeaderAndEntity(http.StatusBadRequest, validationErrors("validation failed", allErrs))
		return
	}

	exists, err := ur.store.Exists(models.StringValue(usr.Login))

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	if exists {
		resp.WriteHeaderAndEntity(http.StatusConflict, errorMsg("User already exists."))
		return
	}

	// hash the password
	pass := models.StringValue(usr.Password)

	pass, err = util.HashPassword(pass)

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	usr.Password = models.String(pass)

	nusr, err := ur.store.Create(usr)

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	nusr.Password = nil

	resp.WriteHeaderAndEntity(http.StatusCreated, nusr)
}
Ejemplo n.º 2
0
func (ur UserResource) updateUser(req *restful.Request, resp *restful.Response) {

	userid, ok := req.Attribute("user_id").(string)

	if !ok {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	cusr, err := ur.store.GetByID(userid)

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusNotFound, errorMsg("User not found."))
		return
	}

	usr := new(models.User)
	err = req.ReadEntity(usr)
	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	// ensure the userid is trusted
	usr.ID = models.String(userid)

	allErrs := validation.ValidateUserUpdate(usr, cusr)

	if len(allErrs) != 0 {
		resp.WriteHeaderAndEntity(http.StatusBadRequest, validationErrors("validation failed", allErrs))
		return
	}

	err = ur.store.Update(usr)
	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	usr.Password = nil

	resp.WriteEntity(usr)
}