Create User Service Handler and SDK (#106)

* Create user handler stuff.

* Fixing Not Found errors from DB.

* Fixing param names.

* Update the proto's go package generation.

* Generate the user resource.

* Adding SDK methods for users.

* Fix the base type of Users and add tests.

* Connect user service to the controller handler.

* Attach the default org to the Test Controller's client.

* Take into account the provided request paths when the client builds the org/project path prefix.

* Adding comments to the API.

* rename repo function to repoFn.

* Fix typo in update mask errors.

* Clean up tests.

* Remove special checks for request url content in the api client and fix CORS test.
This commit is contained in:
Todd Knight authored and GitHub committed 2020-06-09 11:20:59 -07:00
1 parent 2c3fbe3024
commit df6ca5289f
25 files changed
+3845 -9

No files matched your search

+1 -1
View File
@@ -66,7 +66,7 @@ func TestCatalogs_Crud(t *testing.T) {
}
// TODO: Get better coverage for expected errors and error formats.
func TestProject_Errors(t *testing.T) {
func TestCatalogs_Errors(t *testing.T) {
assert := assert.New(t)
tc := controller.NewTestController(t, nil)
defer tc.Shutdown()
+5
View File
@@ -34,6 +34,11 @@ var createFuncs = map[string][]*createInfo{
targetType: "Project",
path: `"projects"`,
},
{
baseType: "Organization",
targetType: "users.User",
path: `"users"`,
},
{
baseType: "Project",
targetType: "hosts.HostCatalog",
+5
View File
@@ -22,6 +22,11 @@ var deleteFuncs = map[string][]*deleteInfo{
"Project",
"projects",
},
{
"Organization",
"users.User",
"users",
},
{
"Project",
"hosts.HostCatalog",
+11
View File
@@ -103,6 +103,17 @@ var inputStructs = []*structInfo{
"",
templateTypeResource,
},
{
os.Getenv("GEN_BASEPATH") + "/internal/gen/controller/api/resources/users/user.pb.go",
"User",
os.Getenv("GEN_BASEPATH") + "/api/users/user.gen.go",
"User",
"users",
"",
"",
"",
templateTypeResource,
},
{
os.Getenv("GEN_BASEPATH") + "/internal/gen/controller/api/resources/hosts/host_catalog.pb.go",
"StaticHostCatalogDetails",
+5
View File
@@ -22,6 +22,11 @@ var readFuncs = map[string][]*readInfo{
targetType: "Project",
path: "projects",
},
{
baseType: "Organization",
targetType: "users.User",
path: "users",
},
{
baseType: "Project",
targetType: "hosts.HostCatalog",
+5
View File
@@ -22,6 +22,11 @@ var updateFuncs = map[string][]*updateInfo{
targetType: "Project",
path: "projects",
},
{
baseType: "Organization",
targetType: "users.User",
path: "users",
},
{
baseType: "Project",
targetType: "hosts.HostCatalog",
+39
View File
@@ -7,6 +7,7 @@ import (
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/hosts"
"github.com/hashicorp/watchtower/api/users"
)
func (s Organization) CreateProject(ctx context.Context, r *Project) (*Project, *api.Error, error) {
@@ -48,6 +49,44 @@ func (s Organization) CreateProject(ctx context.Context, r *Project) (*Project,
return target, apiErr, nil
}
func (s Organization) CreateUser(ctx context.Context, r *users.User) (*users.User, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in Createusers.User request")
}
if s.Id == "" {
// Assume the client has been configured with organization already and
// move on
} else {
// If it's explicitly set here, override anything that might be in the
// client
ctx = context.WithValue(ctx, "org", s.Id)
}
req, err := s.Client.NewRequest(ctx, "POST", "users", r)
if err != nil {
return nil, nil, fmt.Errorf("error creating Createusers.User request: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Createusers.User call: %w", err)
}
target := new(users.User)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Createusers.User repsonse: %w", err)
}
target.Client = s.Client
return target, apiErr, nil
}
func (s Project) CreateHostCatalog(ctx context.Context, r *hosts.HostCatalog) (*hosts.HostCatalog, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in Createhosts.HostCatalog request")
+45
View File
@@ -7,6 +7,7 @@ import (
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/hosts"
"github.com/hashicorp/watchtower/api/users"
)
// DeleteProject returns true iff the Project existed when the delete attempt was made.
@@ -53,6 +54,50 @@ func (s Organization) DeleteProject(ctx context.Context, r *Project) (bool, *api
return target.Existed, apiErr, nil
}
// DeleteUser returns true iff the users.User existed when the delete attempt was made.
func (s Organization) DeleteUser(ctx context.Context, r *users.User) (bool, *api.Error, error) {
if s.Client == nil {
return false, nil, fmt.Errorf("nil client in DeleteUser request")
}
if s.Id == "" {
// Assume the client has been configured with organization already and
// move on
} else {
// If it's explicitly set here, override anything that might be in the
// client
ctx = context.WithValue(ctx, "org", s.Id)
}
if r.Id == "" {
return false, nil, fmt.Errorf("empty users.User ID field in DeleteUser request")
}
req, err := s.Client.NewRequest(ctx, "DELETE", fmt.Sprintf("%s/%s", "users", r.Id), nil)
if err != nil {
return false, nil, fmt.Errorf("error creating DeleteUser request: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return false, nil, fmt.Errorf("error performing client request during DeleteUser call: %w", err)
}
type deleteResponse struct {
Existed bool
}
target := &deleteResponse{}
apiErr, err := resp.Decode(target)
if err != nil {
return false, nil, fmt.Errorf("error decoding DeleteUser repsonse: %w", err)
}
return target.Existed, apiErr, nil
}
// DeleteHostCatalog returns true iff the hosts.HostCatalog existed when the delete attempt was made.
func (s Project) DeleteHostCatalog(ctx context.Context, r *hosts.HostCatalog) (bool, *api.Error, error) {
if s.Client == nil {
+42
View File
@@ -7,6 +7,7 @@ import (
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/hosts"
"github.com/hashicorp/watchtower/api/users"
)
func (s Organization) ReadProject(ctx context.Context, r *Project) (*Project, *api.Error, error) {
@@ -51,6 +52,47 @@ func (s Organization) ReadProject(ctx context.Context, r *Project) (*Project, *a
return target, apiErr, nil
}
func (s Organization) ReadUser(ctx context.Context, r *users.User) (*users.User, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in ReadUser request")
}
if s.Id == "" {
// Assume the client has been configured with organization already and
// move on
} else {
// If it's explicitly set here, override anything that might be in the
// client
ctx = context.WithValue(ctx, "org", s.Id)
}
if r.Id == "" {
return nil, nil, fmt.Errorf("empty users.User ID field in ReadUser request")
}
req, err := s.Client.NewRequest(ctx, "GET", fmt.Sprintf("%s/%s", "users", r.Id), r)
if err != nil {
return nil, nil, fmt.Errorf("error creating ReadUser request: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during ReadUser call: %w", err)
}
target := new(users.User)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding ReadUser repsonse: %w", err)
}
target.Client = s.Client
return target, apiErr, nil
}
func (s Project) ReadHostCatalog(ctx context.Context, r *hosts.HostCatalog) (*hosts.HostCatalog, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in ReadHostCatalog request")
+42
View File
@@ -7,6 +7,7 @@ import (
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/hosts"
"github.com/hashicorp/watchtower/api/users"
)
func (s Organization) UpdateProject(ctx context.Context, r *Project) (*Project, *api.Error, error) {
@@ -51,6 +52,47 @@ func (s Organization) UpdateProject(ctx context.Context, r *Project) (*Project,
return target, apiErr, nil
}
func (s Organization) UpdateUser(ctx context.Context, r *users.User) (*users.User, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in CreateUser request")
}
if s.Id == "" {
// Assume the client has been configured with organization already and
// move on
} else {
// If it's explicitly set here, override anything that might be in the
// client
ctx = context.WithValue(ctx, "org", s.Id)
}
id := r.Id
r.Id = ""
req, err := s.Client.NewRequest(ctx, "PATCH", fmt.Sprintf("%s/%s", "users", id), r)
if err != nil {
return nil, nil, fmt.Errorf("error creating CreateUser request: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during UpdateUser call: %w", err)
}
target := new(users.User)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding UpdateUser repsonse: %w", err)
}
target.Client = s.Client
return target, apiErr, nil
}
func (s Project) UpdateHostCatalog(ctx context.Context, r *hosts.HostCatalog) (*hosts.HostCatalog, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in CreateHostCatalog request")
+53
View File
@@ -0,0 +1,53 @@
// Code generated by "make api"; DO NOT EDIT.
package users
import (
"encoding/json"
"time"
"github.com/fatih/structs"
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/internal/strutil"
)
type User struct {
Client *api.Client `json:"-"`
defaultFields []string
// The ID of the Project
// Output only.
Id string `json:"id,omitempty"`
// Optional name for identification purposes
Name *string `json:"name,omitempty"`
// Optional user-set descripton for identification purposes
Description *string `json:"description,omitempty"`
// The time this resource was created
// Output only.
CreatedTime time.Time `json:"created_time,omitempty"`
// The time this resource was last updated.
// Output only.
UpdatedTime time.Time `json:"updated_time,omitempty"`
// Whether the resource is disabled
Disabled *bool `json:"disabled,omitempty"`
}
func (s *User) SetDefault(key string) {
s.defaultFields = strutil.AppendIfMissing(s.defaultFields, key)
}
func (s *User) UnsetDefault(key string) {
s.defaultFields = strutil.StrListDelete(s.defaultFields, key)
}
func (s User) MarshalJSON() ([]byte, error) {
m := structs.Map(s)
if m == nil {
m = make(map[string]interface{})
}
for _, k := range s.defaultFields {
m[k] = nil
}
return json.Marshal(m)
}
+98
View File
@@ -0,0 +1,98 @@
package users_test
import (
"net/http"
"testing"
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/scopes"
"github.com/hashicorp/watchtower/api/users"
"github.com/hashicorp/watchtower/internal/iam"
"github.com/hashicorp/watchtower/internal/servers/controller"
"github.com/stretchr/testify/assert"
)
func TestUser_Crud(t *testing.T) {
tc := controller.NewTestController(t, nil)
defer tc.Shutdown()
client := tc.Client()
org := &scopes.Organization{
Client: client,
}
checkUser := func(step string, u *users.User, apiErr *api.Error, err error, wantedName string) {
assert := assert.New(t)
assert.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != nil {
t.Errorf("ApiError message: %q", *apiErr.Message)
}
assert.NotNil(u, "returned project", step)
gotName := ""
if u.Name != nil {
gotName = *u.Name
}
assert.Equal(wantedName, gotName, step)
}
u, apiErr, err := org.CreateUser(tc.Context(), &users.User{Name: api.String("foo")})
checkUser("create", u, apiErr, err, "foo")
u, apiErr, err = org.ReadUser(tc.Context(), &users.User{Id: u.Id})
checkUser("read", u, apiErr, err, "foo")
u = &users.User{Id: u.Id}
u.Name = api.String("bar")
u, apiErr, err = org.UpdateUser(tc.Context(), u)
checkUser("update", u, apiErr, err, "bar")
u = &users.User{Id: u.Id}
u.SetDefault("name")
u, apiErr, err = org.UpdateUser(tc.Context(), u)
checkUser("update", u, apiErr, err, "")
existed, apiErr, err := org.DeleteUser(tc.Context(), u)
assert.NoError(t, err)
assert.True(t, existed, "Expected existing user when deleted, but it wasn't.")
existed, apiErr, err = org.DeleteUser(tc.Context(), u)
assert.NoError(t, err)
assert.False(t, existed, "Expected user to not exist when deleted, but it did.")
}
func TestUser_Errors(t *testing.T) {
assert := assert.New(t)
tc := controller.NewTestController(t, nil)
defer tc.Shutdown()
ctx := tc.Context()
client := tc.Client()
org := &scopes.Organization{
Client: client,
}
u, apiErr, err := org.CreateUser(ctx, &users.User{Name: api.String("first")})
assert.NoError(err)
assert.Nil(apiErr)
assert.NotNil(u)
// Create another resource with the same name.
_, apiErr, err = org.CreateUser(ctx, &users.User{Name: api.String("first")})
assert.NoError(err)
assert.NotNil(apiErr)
_, apiErr, err = org.ReadUser(ctx, &users.User{Id: iam.UserPrefix + "_doesntexis"})
assert.NoError(err)
assert.NotNil(apiErr)
assert.EqualValues(*apiErr.Status, http.StatusNotFound)
_, apiErr, err = org.ReadUser(ctx, &users.User{Id: "invalid id"})
assert.NoError(err)
assert.NotNil(apiErr)
assert.EqualValues(*apiErr.Status, http.StatusBadRequest)
_, apiErr, err = org.UpdateUser(ctx, &users.User{Id: u.Id})
assert.NoError(err)
assert.NotNil(apiErr)
assert.EqualValues(*apiErr.Status, http.StatusBadRequest)
}