Auth Token Read/List/Delete handler and Go SDK (#199)

* Creating Auth Token Get List and Delete API.
This commit is contained in:
Todd Knight authored and GitHub committed 2020-07-23 09:53:37 -07:00
1 parent 65dc095fbc
commit 6de1f7ee16
26 files changed
+2331 -58

No files matched your search

+42
View File
@@ -2,12 +2,21 @@
package authtokens
import (
"encoding/json"
"strings"
"time"
"github.com/fatih/structs"
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/info"
"github.com/hashicorp/watchtower/api/internal/strutil"
)
type AuthToken struct {
Client *api.Client `json:"-"`
defaultFields []string
// The ID of the AuthToken
// Output only.
@@ -39,3 +48,36 @@ type AuthToken struct {
// Output only.
ExpirationTime time.Time `json:"expiration_time,omitempty"`
}
func (s *AuthToken) SetDefault(key string) {
lowerKey := strings.ToLower(key)
validMap := map[string]string{"approximatelastusedtime": "approximate_last_used_time", "authmethodid": "auth_method_id", "createdtime": "created_time", "expirationtime": "expiration_time", "id": "id", "scope": "scope", "token": "token", "updatedtime": "updated_time", "userid": "user_id"}
for k, v := range validMap {
if k == lowerKey || v == lowerKey {
s.defaultFields = strutil.AppendIfMissing(s.defaultFields, v)
return
}
}
}
func (s *AuthToken) UnsetDefault(key string) {
lowerKey := strings.ToLower(key)
validMap := map[string]string{"approximatelastusedtime": "approximate_last_used_time", "authmethodid": "auth_method_id", "createdtime": "created_time", "expirationtime": "expiration_time", "id": "id", "scope": "scope", "token": "token", "updatedtime": "updated_time", "userid": "user_id"}
for k, v := range validMap {
if k == lowerKey || v == lowerKey {
s.defaultFields = strutil.StrListDelete(s.defaultFields, v)
return
}
}
}
func (s AuthToken) 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)
}
+116
View File
@@ -0,0 +1,116 @@
package authtokens_test
/*
func TestAuthTokens_List(t *testing.T) {
assert := assert.New(t)
tc := controller.NewTestController(t, &controller.TestControllerOpts{DisableAuthorizationFailures: true})
defer tc.Shutdown()
client := tc.Client()
org := &scopes.Org{
Client: client,
}
ctx := context.Background()
atl, apiErr, err := org.ListAuthTokens(ctx)
assert.NoError(err)
assert.Nil(apiErr)
assert.Empty(atl)
var expected []*authtokens.AuthToken
at, apiErr, err := org.Authenticate(ctx, "am_1234567890", "name", "pw")
assert.NoError(err)
assert.Nil(apiErr)
expected = append(expected, at)
atl, apiErr, err = org.ListAuthTokens(ctx)
assert.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(atl))
for i := 1; i < 10; i++ {
at, apiErr, err = org.Authenticate(ctx, "am_1234567890", "name", "pw")
assert.NoError(err)
assert.Nil(apiErr)
expected = append(expected, at)
}
atl, apiErr, err = org.ListAuthTokens(ctx)
require.NoError(t, err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(atl))
}
func comparableResource(i *authtokens.AuthToken) authtokens.AuthToken {
return authtokens.AuthToken{
Id: i.Id,
UserId: i.UserId,
AuthMethodId: i.AuthMethodId,
CreatedTime: i.CreatedTime,
UpdatedTime: i.UpdatedTime,
ApproximateLastUsedTime: i.ApproximateLastUsedTime,
ExpirationTime: i.ExpirationTime,
}
}
func comparableSlice(in []*authtokens.AuthToken) []authtokens.AuthToken {
var filtered []authtokens.AuthToken
for _, i := range in {
filtered = append(filtered, comparableResource(i))
}
sort.Slice(filtered, func(i, j int) bool {
return filtered[i].Id < filtered[j].Id
})
return filtered
}
func TestAuthToken_Crud(t *testing.T) {
tc := controller.NewTestController(t, &controller.TestControllerOpts{DisableAuthorizationFailures: true})
defer tc.Shutdown()
client := tc.Client()
org := &scopes.Org{
Client: client,
}
want, apiErr, err := org.Authenticate(tc.Context(), "am_1234567890", "name", "pw")
at, apiErr, err := org.ReadAuthToken(tc.Context(), &authtokens.AuthToken{Id: want.Id})
require.NoError(t, err)
assert.Nil(t, apiErr)
at.Token = ""
assert.EqualValues(t, comparableResource(want), comparableResource(at))
existed, _, err := org.DeleteAuthToken(tc.Context(), at)
require.NoError(t, err)
assert.Nil(t, apiErr)
assert.True(t, existed, "Expected existing user when deleted, but it wasn't.")
existed, apiErr, err = org.DeleteAuthToken(tc.Context(), at)
require.NoError(t, err)
assert.Nil(t, apiErr)
assert.False(t, existed, "Expected user to not exist when deleted, but it did.")
}
func TestAuthToken_Errors(t *testing.T) {
assert := assert.New(t)
tc := controller.NewTestController(t, &controller.TestControllerOpts{DisableAuthorizationFailures: true})
defer tc.Shutdown()
ctx := tc.Context()
client := tc.Client()
org := &scopes.Org{
Client: client,
}
_, apiErr, err := org.ReadAuthToken(ctx, &authtokens.AuthToken{Id: authtoken.AuthTokenPrefix + "_doesntexis"})
assert.NoError(err)
assert.NotNil(apiErr)
assert.EqualValues(apiErr.Status, http.StatusNotFound)
_, apiErr, err = org.ReadAuthToken(ctx, &authtokens.AuthToken{Id: "invalid id"})
assert.NoError(err)
assert.NotNil(apiErr)
assert.EqualValues(apiErr.Status, http.StatusBadRequest)
}
*/
+49
View File
@@ -0,0 +1,49 @@
// Code generated by "make api"; DO NOT EDIT.
package authtokens
import (
"context"
"fmt"
"github.com/hashicorp/watchtower/api"
)
// DeleteAuthToken returns true iff the AuthToken existed when the delete attempt was made.
func (s AuthToken) DeleteAuthToken(ctx context.Context, id string) (bool, *api.Error, error) {
if id == "" {
return false, nil, fmt.Errorf("empty id provided to DeleteAuthToken request")
}
if s.Client == nil {
return false, nil, fmt.Errorf("nil client in DeleteAuthToken request")
}
var opts []api.Option
if s.Scope.Id != "" {
// If it's explicitly set here, override anything that might be in the
// client
opts = append(opts, api.WithScopeId(s.Scope.Id))
}
req, err := s.Client.NewRequest(ctx, "DELETE", fmt.Sprintf("%s/%s", "auth-tokens", id), nil, opts...)
if err != nil {
return false, nil, fmt.Errorf("error creating DeleteAuthToken request: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return false, nil, fmt.Errorf("error performing client request during DeleteAuthToken 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 DeleteAuthToken repsonse: %w", err)
}
return target.Existed, apiErr, nil
}
+50
View File
@@ -0,0 +1,50 @@
// Code generated by "make api"; DO NOT EDIT.
package authtokens
import (
"context"
"fmt"
"github.com/hashicorp/watchtower/api"
)
func (s AuthToken) ListAuthTokens(ctx context.Context) ([]*AuthToken, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in ListAuthToken request")
}
var opts []api.Option
if s.Scope.Id != "" {
// If it's explicitly set here, override anything that might be in the
// client
opts = append(opts, api.WithScopeId(s.Scope.Id))
}
req, err := s.Client.NewRequest(ctx, "GET", "auth-tokens", nil, opts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating ListAuthTokens request: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during ListAuthTokens call: %w", err)
}
type listResponse struct {
Items []*AuthToken
}
target := &listResponse{}
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding ListAuthTokens response: %w", err)
}
for _, t := range target.Items {
t.Client = s.Client
}
return target.Items, apiErr, nil
}
+46
View File
@@ -0,0 +1,46 @@
// Code generated by "make api"; DO NOT EDIT.
package authtokens
import (
"context"
"fmt"
"github.com/hashicorp/watchtower/api"
)
func (s AuthToken) ReadAuthToken(ctx context.Context, id string) (*AuthToken, *api.Error, error) {
if id == "" {
return nil, nil, fmt.Errorf("empty ID value passed into ReadAuthToken request")
}
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in ReadAuthToken request")
}
var opts []api.Option
if s.Scope.Id != "" {
// If it's explicitly set here, override anything that might be in the
// client
opts = append(opts, api.WithScopeId(s.Scope.Id))
}
req, err := s.Client.NewRequest(ctx, "GET", fmt.Sprintf("%s/%s", "auth-tokens", id), nil, opts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating ReadAuthToken request: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during ReadAuthToken call: %w", err)
}
target := new(AuthToken)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding ReadAuthToken repsonse: %w", err)
}
target.Client = s.Client
return target, apiErr, nil
}
+7
View File
@@ -23,6 +23,13 @@ var deleteFuncs = map[string][]*deleteInfo{
"scopes",
},
},
"authtokens": {
{
"AuthToken",
"AuthToken",
"auth-tokens",
},
},
"groups": {
{
"Group",
+5 -6
View File
@@ -63,12 +63,11 @@ var inputStructs = []*structInfo{
outPkg: "hosts",
},
{
inFile: os.Getenv("GEN_BASEPATH") + "/internal/gen/controller/api/resources/authtokens/authtoken.pb.go",
inName: "AuthToken",
outFile: os.Getenv("GEN_BASEPATH") + "/api/authtokens/authtoken.gen.go",
outName: "AuthToken",
outPkg: "authtokens",
outputOnly: true,
inFile: os.Getenv("GEN_BASEPATH") + "/internal/gen/controller/api/resources/authtokens/authtoken.pb.go",
inName: "AuthToken",
outFile: os.Getenv("GEN_BASEPATH") + "/api/authtokens/authtoken.gen.go",
outName: "AuthToken",
outPkg: "authtokens",
},
{
inFile: os.Getenv("GEN_BASEPATH") + "/internal/gen/controller/api/resources/scopes/scope.pb.go",
+7
View File
@@ -23,6 +23,13 @@ var listFuncs = map[string][]*listInfo{
path: "scopes",
},
},
"authtokens": {
{
baseType: "AuthToken",
targetType: "AuthToken",
path: "auth-tokens",
},
},
"groups": {
{
baseType: "Group",
+7
View File
@@ -23,6 +23,13 @@ var readFuncs = map[string][]*readInfo{
path: "scopes",
},
},
"authtokens": {
{
baseType: "AuthToken",
targetType: "AuthToken",
path: "auth-tokens",
},
},
"groups": {
{
baseType: "Group",