Beispiel #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)
}
Beispiel #2
0
func (ur UserResource) updatePassword(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
	}

	data := make(map[string]string)
	err = req.ReadEntity(&data)

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

	password, ok := data["password"]

	if !ok {
		resp.WriteHeaderAndEntity(http.StatusBadRequest, errorMsg("bad request missing password"))
		return
	}

	// hash the password
	pass, err := util.HashPassword(password)

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

	cusr.Password = models.String(pass)

	err = ur.store.Update(cusr)

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

	resp.WriteHeader(http.StatusOK)
}