Skip to content
This repository was archived by the owner on Aug 1, 2023. It is now read-only.

Commit 0a866d9

Browse files
committed
Merge pull request #514 from chaolou/bug-fix-reauth
Bug fix reauth and add extract user from token
2 parents 9c901fb + 0454360 commit 0a866d9

File tree

7 files changed

+147
-1
lines changed

7 files changed

+147
-1
lines changed

acceptance/openstack/identity/v2/token_test.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import (
99
th "github.com/rackspace/gophercloud/testhelper"
1010
)
1111

12-
func TestAuthenticate(t *testing.T) {
12+
func TestAuthenticateAndValidate(t *testing.T) {
13+
// 1. TestAuthenticate
1314
ao := v2AuthOptions(t)
1415
service := unauthenticatedClient(t)
1516

@@ -35,4 +36,19 @@ func TestAuthenticate(t *testing.T) {
3536
t.Logf(" - region=[%s] publicURL=[%s]", endpoint.Region, endpoint.PublicURL)
3637
}
3738
}
39+
40+
// 2. TestValidate
41+
client := authenticatedClient(t)
42+
43+
// Validate Token!
44+
getResult := tokens2.Get(client, token.ID)
45+
46+
// Extract and print the user.
47+
user, err := getResult.ExtractUser()
48+
th.AssertNoErr(t, err)
49+
50+
t.Logf("Acquired User: [%s]", user.Name)
51+
t.Logf("The User id: [%s]", user.ID)
52+
t.Logf("The User username: [%s]", user.UserName)
53+
t.Logf("The User roles: [%#v]", user.Roles)
3854
}

openstack/client.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ func v3auth(client *gophercloud.ProviderClient, endpoint string, options gopherc
167167

168168
if options.AllowReauth {
169169
client.ReauthFunc = func() error {
170+
client.TokenID = ""
170171
return AuthenticateV3(client, options)
171172
}
172173
}

openstack/identity/v2/tokens/fixtures.go

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010

1111
"github.com/rackspace/gophercloud/openstack/identity/v2/tenants"
1212
th "github.com/rackspace/gophercloud/testhelper"
13+
thclient "github.com/rackspace/gophercloud/testhelper/client"
1314
)
1415

1516
// ExpectedToken is the token that should be parsed from TokenCreationResponse.
@@ -54,6 +55,14 @@ var ExpectedServiceCatalog = &ServiceCatalog{
5455
},
5556
}
5657

58+
// ExpectedUser is the token that should be parsed from TokenGetResponse.
59+
var ExpectedUser = &User{
60+
ID: "a530fefc3d594c4ba2693a4ecd6be74e",
61+
Name: "apiserver",
62+
Roles: []Role{{"member"}, {"service"}},
63+
UserName: "apiserver",
64+
}
65+
5766
// TokenCreationResponse is a JSON response that contains ExpectedToken and ExpectedServiceCatalog.
5867
const TokenCreationResponse = `
5968
{
@@ -99,6 +108,39 @@ const TokenCreationResponse = `
99108
}
100109
`
101110

111+
// TokenGetResponse is a JSON response that contains ExpectedToken and ExpectedUser.
112+
const TokenGetResponse = `
113+
{
114+
"access": {
115+
"token": {
116+
"issued_at": "2014-01-30T15:30:58.000000Z",
117+
"expires": "2014-01-31T15:30:58Z",
118+
"id": "aaaabbbbccccdddd",
119+
"tenant": {
120+
"description": "There are many tenants. This one is yours.",
121+
"enabled": true,
122+
"id": "fc394f2ab2df4114bde39905f800dc57",
123+
"name": "test"
124+
}
125+
},
126+
"serviceCatalog": [],
127+
"user": {
128+
"id": "a530fefc3d594c4ba2693a4ecd6be74e",
129+
"name": "apiserver",
130+
"roles": [
131+
{
132+
"name": "member"
133+
},
134+
{
135+
"name": "service"
136+
}
137+
],
138+
"roles_links": [],
139+
"username": "apiserver"
140+
}
141+
}
142+
}`
143+
102144
// HandleTokenPost expects a POST against a /tokens handler, ensures that the request body has been
103145
// constructed properly given certain auth options, and returns the result.
104146
func HandleTokenPost(t *testing.T, requestJSON string) {
@@ -115,6 +157,19 @@ func HandleTokenPost(t *testing.T, requestJSON string) {
115157
})
116158
}
117159

160+
// HandleTokenGet expects a Get against a /tokens handler, ensures that the request body has been
161+
// constructed properly given certain auth options, and returns the result.
162+
func HandleTokenGet(t *testing.T, token string) {
163+
th.Mux.HandleFunc("/tokens/"+token, func(w http.ResponseWriter, r *http.Request) {
164+
th.TestMethod(t, r, "GET")
165+
th.TestHeader(t, r, "Accept", "application/json")
166+
th.TestHeader(t, r, "X-Auth-Token", thclient.TokenID)
167+
168+
w.WriteHeader(http.StatusOK)
169+
fmt.Fprintf(w, TokenGetResponse)
170+
})
171+
}
172+
118173
// IsSuccessful ensures that a CreateResult was successful and contains the correct token and
119174
// service catalog.
120175
func IsSuccessful(t *testing.T, result CreateResult) {
@@ -126,3 +181,15 @@ func IsSuccessful(t *testing.T, result CreateResult) {
126181
th.AssertNoErr(t, err)
127182
th.CheckDeepEquals(t, ExpectedServiceCatalog, serviceCatalog)
128183
}
184+
185+
// GetIsSuccessful ensures that a GetResult was successful and contains the correct token and
186+
// User Info.
187+
func GetIsSuccessful(t *testing.T, result GetResult) {
188+
token, err := result.ExtractToken()
189+
th.AssertNoErr(t, err)
190+
th.CheckDeepEquals(t, ExpectedToken, token)
191+
192+
user, err := result.ExtractUser()
193+
th.AssertNoErr(t, err)
194+
th.CheckDeepEquals(t, ExpectedUser, user)
195+
}

openstack/identity/v2/tokens/requests.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,12 @@ func Create(client *gophercloud.ServiceClient, auth AuthOptionsBuilder) CreateRe
8888
})
8989
return result
9090
}
91+
92+
// Validates and retrieves information for user's token.
93+
func Get(client *gophercloud.ServiceClient, token string) GetResult {
94+
var result GetResult
95+
_, result.Err = client.Get(GetURL(client, token), &result.Body, &gophercloud.RequestOpts{
96+
OkCodes: []int{200, 203},
97+
})
98+
return result
99+
}

openstack/identity/v2/tokens/requests_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,14 @@ func TestRequirePassword(t *testing.T) {
139139

140140
tokenPostErr(t, options, ErrPasswordRequired)
141141
}
142+
143+
func tokenGet(t *testing.T, tokenId string) GetResult {
144+
th.SetupHTTP()
145+
defer th.TeardownHTTP()
146+
HandleTokenGet(t, tokenId)
147+
return Get(client.ServiceClient(), tokenId)
148+
}
149+
150+
func TestGetWithToken(t *testing.T) {
151+
GetIsSuccessful(t, tokenGet(t, "db22caf43c934e6c829087c41ff8d8d6"))
152+
}

openstack/identity/v2/tokens/results.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,17 @@ type Token struct {
2525
Tenant tenants.Tenant
2626
}
2727

28+
// Authorization need user info which can get from token authentication's response
29+
type Role struct {
30+
Name string `mapstructure:"name"`
31+
}
32+
type User struct {
33+
ID string `mapstructure:"id"`
34+
Name string `mapstructure:"name"`
35+
UserName string `mapstructure:"username"`
36+
Roles []Role `mapstructure:"roles"`
37+
}
38+
2839
// Endpoint represents a single API endpoint offered by a service.
2940
// It provides the public and internal URLs, if supported, along with a region specifier, again if provided.
3041
// The significance of the Region field will depend upon your provider.
@@ -74,6 +85,12 @@ type CreateResult struct {
7485
gophercloud.Result
7586
}
7687

88+
// GetResult is the deferred response from a Get call, which is the same with a Created token.
89+
// Use ExtractUser() to interpret it as a User.
90+
type GetResult struct {
91+
CreateResult
92+
}
93+
7794
// ExtractToken returns the just-created Token from a CreateResult.
7895
func (result CreateResult) ExtractToken() (*Token, error) {
7996
if result.Err != nil {
@@ -131,3 +148,23 @@ func (result CreateResult) ExtractServiceCatalog() (*ServiceCatalog, error) {
131148
func createErr(err error) CreateResult {
132149
return CreateResult{gophercloud.Result{Err: err}}
133150
}
151+
152+
// ExtractUser returns the User from a GetResult.
153+
func (result GetResult) ExtractUser() (*User, error) {
154+
if result.Err != nil {
155+
return nil, result.Err
156+
}
157+
158+
var response struct {
159+
Access struct {
160+
User User `mapstructure:"user"`
161+
} `mapstructure:"access"`
162+
}
163+
164+
err := mapstructure.Decode(result.Body, &response)
165+
if err != nil {
166+
return nil, err
167+
}
168+
169+
return &response.Access.User, nil
170+
}

openstack/identity/v2/tokens/urls.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,8 @@ import "github.com/rackspace/gophercloud"
66
func CreateURL(client *gophercloud.ServiceClient) string {
77
return client.ServiceURL("tokens")
88
}
9+
10+
// GetURL generates the URL used to Validate Tokens.
11+
func GetURL(client *gophercloud.ServiceClient, token string) string {
12+
return client.ServiceURL("tokens", token)
13+
}

0 commit comments

Comments
 (0)