Exemplo n.º 1
0
Arquivo: user.go Projeto: pbochis/api
func GetCompanyByUser(ctx context.Context, w http.ResponseWriter, r *http.Request) (int, error) {
	if r.Method != "GET" {
		return http.StatusMethodNotAllowed, nil
	}

	p, ok := passenger.FromContext(ctx)
	if !ok {
		return http.StatusUnauthorized, nil
	}

	var u model.User
	if err := datastore.Get(ctx, p.User, &u); err != nil {
		return http.StatusInternalServerError, nil
	}

	if u.Company == nil {
		return http.StatusUnauthorized, nil
	}

	// The account is associated with a company, so we return it.
	var company model.Company
	if err := datastore.Get(ctx, u.Company, &company); err != nil {
		return http.StatusInternalServerError, err
	}

	json.NewEncoder(w).Encode(company.Key(u.Company))
	return http.StatusOK, nil
}
Exemplo n.º 2
0
// PostCompany creates a new company after validating by key.
func PostCompany(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
	if r.Method != "POST" {
		return http.StatusMethodNotAllowed, nil
	}

	var company model.Company
	if err = json.NewDecoder(r.Body).Decode(&company); err != nil {
		return http.StatusBadRequest, err
	}

	var companies model.Companys
	_, err = model.NewQueryForCompany().
		Filter("Address =", company.Address.Address).
		Limit(1).
		GetAll(ctx, &companies)

	if err != nil {
		return http.StatusInternalServerError, err
	}

	if len(companies) > 0 {
		return http.StatusConflict, errors.New("already registered")
	}

	var key *datastore.Key
	if key, err = company.Put(ctx, nil); err != nil {
		return http.StatusInternalServerError, err
	}

	// TODO(flowlo): Respond with HTTP 201 and include a
	// location header and caching information.

	json.NewEncoder(w).Encode(company.Key(key))
	return http.StatusOK, nil
}
Exemplo n.º 3
0
func GetCompanyByUser(ctx context.Context, w http.ResponseWriter, r *http.Request) (int, error) {
	if !util.CheckMethod(r, "GET") {
		return http.StatusMethodNotAllowed, nil
	}
	p, ok := passenger.FromContext(ctx)

	if !ok {
		return http.StatusUnauthorized, nil
	}
	key := p.UserKey.Parent()
	if key == nil {
		return http.StatusUnauthorized, nil
	}
	// The account is associated with a company, so we return it.
	var company model.Company
	if err := datastore.Get(ctx, key, &company); err != nil {
		return http.StatusInternalServerError, err
	}
	json.NewEncoder(w).Encode(company.Key(key))
	return http.StatusOK, nil
}
Exemplo n.º 4
0
// CreateAndSaveCompany creates a new Company and saves it to datastore using the provided context
func CreateAndSaveCompany(t *testing.T, ctx context.Context, name, email string) (model.Company, *datastore.Key) {
	if name == "" {
		name = "Example Company"
	}
	if email == "" {
		email = "*****@*****.**"
	}
	company := model.Company{
		Address: mail.Address{
			Name:    name,
			Address: email,
		},
	}
	var err error
	var key *datastore.Key

	key, err = company.Put(ctx, nil)
	if err != nil {
		t.Fatal(err)
	}
	return company, key
}