Jamie Hannaford | 8c072a3 | 2014-10-16 14:33:32 +0200 | [diff] [blame] | 1 | package tokens |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "time" |
| 6 | |
| 7 | "github.com/mitchellh/mapstructure" |
| 8 | "github.com/rackspace/gophercloud" |
| 9 | ) |
| 10 | |
| 11 | // commonResult is the deferred result of a Create or a Get call. |
| 12 | type commonResult struct { |
| 13 | gophercloud.CommonResult |
| 14 | |
| 15 | // header stores the headers from the original HTTP response because token responses are returned in an X-Subject-Token header. |
| 16 | header http.Header |
| 17 | } |
| 18 | |
| 19 | // Extract interprets a commonResult as a Token. |
| 20 | func (r commonResult) Extract() (*Token, error) { |
| 21 | if r.Err != nil { |
| 22 | return nil, r.Err |
| 23 | } |
| 24 | |
| 25 | var response struct { |
| 26 | Token struct { |
| 27 | ExpiresAt string `mapstructure:"expires_at"` |
| 28 | } `mapstructure:"token"` |
| 29 | } |
| 30 | |
| 31 | var token Token |
| 32 | |
| 33 | // Parse the token itself from the stored headers. |
| 34 | token.ID = r.header.Get("X-Subject-Token") |
| 35 | |
| 36 | err := mapstructure.Decode(r.Resp, &response) |
| 37 | if err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | |
| 41 | // Attempt to parse the timestamp. |
| 42 | token.ExpiresAt, err = time.Parse(gophercloud.RFC3339Milli, response.Token.ExpiresAt) |
| 43 | |
| 44 | return &token, err |
| 45 | } |
| 46 | |
| 47 | // CreateResult is the deferred response from a Create call. |
| 48 | type CreateResult struct { |
| 49 | commonResult |
| 50 | } |
| 51 | |
| 52 | // createErr quickly creates a CreateResult that reports an error. |
| 53 | func createErr(err error) CreateResult { |
| 54 | return CreateResult{ |
| 55 | commonResult: commonResult{ |
| 56 | CommonResult: gophercloud.CommonResult{Err: err}, |
| 57 | header: nil, |
| 58 | }, |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // GetResult is the deferred response from a Get call. |
| 63 | type GetResult struct { |
| 64 | commonResult |
| 65 | } |
| 66 | |
| 67 | // Token is a string that grants a user access to a controlled set of services in an OpenStack provider. |
| 68 | // Each Token is valid for a set length of time. |
| 69 | type Token struct { |
| 70 | // ID is the issued token. |
| 71 | ID string |
| 72 | |
| 73 | // ExpiresAt is the timestamp at which this token will no longer be accepted. |
| 74 | ExpiresAt time.Time |
| 75 | } |