blob: c25a72b1abcd7b67acf37d948db92b8b69372c6f [file] [log] [blame]
Jamie Hannaford8c072a32014-10-16 14:33:32 +02001package tokens
2
3import (
4 "github.com/racker/perigee"
5 "github.com/rackspace/gophercloud"
6)
7
8// AuthOptionsBuilder describes any argument that may be passed to the Create call.
9type AuthOptionsBuilder interface {
10
11 // ToTokenCreateMap assembles the Create request body, returning an error if parameters are
12 // missing or inconsistent.
13 ToTokenCreateMap() (map[string]interface{}, error)
14}
15
16// AuthOptions wraps a gophercloud AuthOptions in order to adhere to the AuthOptionsBuilder
17// interface.
18type AuthOptions struct {
19 gophercloud.AuthOptions
20}
21
22// WrapOptions embeds a root AuthOptions struct in a package-specific one.
23func WrapOptions(original gophercloud.AuthOptions) AuthOptions {
24 return AuthOptions{AuthOptions: original}
25}
26
27// ToTokenCreateMap converts AuthOptions into nested maps that can be serialized into a JSON
28// request.
29func (auth AuthOptions) ToTokenCreateMap() (map[string]interface{}, error) {
30 // Error out if an unsupported auth option is present.
31 if auth.UserID != "" {
32 return nil, ErrUserIDProvided
33 }
34 if auth.APIKey != "" {
35 return nil, ErrAPIKeyProvided
36 }
37 if auth.DomainID != "" {
38 return nil, ErrDomainIDProvided
39 }
40 if auth.DomainName != "" {
41 return nil, ErrDomainNameProvided
42 }
43
44 // Username and Password are always required.
45 if auth.Username == "" {
46 return nil, ErrUsernameRequired
47 }
48 if auth.Password == "" {
49 return nil, ErrPasswordRequired
50 }
51
52 // Populate the request map.
53 authMap := make(map[string]interface{})
54
55 authMap["passwordCredentials"] = map[string]interface{}{
56 "username": auth.Username,
57 "password": auth.Password,
58 }
59
60 if auth.TenantID != "" {
61 authMap["tenantId"] = auth.TenantID
62 }
63 if auth.TenantName != "" {
64 authMap["tenantName"] = auth.TenantName
65 }
66
67 return map[string]interface{}{"auth": authMap}, nil
68}
69
70// Create authenticates to the identity service and attempts to acquire a Token.
71// If successful, the CreateResult
72// Generally, rather than interact with this call directly, end users should call openstack.AuthenticatedClient(),
73// which abstracts all of the gory details about navigating service catalogs and such.
74func Create(client *gophercloud.ServiceClient, auth AuthOptionsBuilder) CreateResult {
75 request, err := auth.ToTokenCreateMap()
76 if err != nil {
77 return CreateResult{gophercloud.CommonResult{Err: err}}
78 }
79
80 var result CreateResult
81 _, result.Err = perigee.Request("POST", CreateURL(client), perigee.Options{
82 ReqBody: &request,
83 Results: &result.Resp,
84 OkCodes: []int{200, 203},
85 })
86 return result
87}