Skip to content

Commit

Permalink
Refactoring a little
Browse files Browse the repository at this point in the history
  • Loading branch information
marstr committed Sep 13, 2017
1 parent 2a863db commit 3124dd5
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 30 deletions.
13 changes: 5 additions & 8 deletions autorest/adal/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ import (
"strings"
"time"

"github.com/Azure/go-autorest/autorest/date"
"github.com/dgrijalva/jwt-go"
)

const (
defaultRefresh = 5 * time.Minute
tokenBaseDate = "1970-01-01T00:00:00Z"

// OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow
OAuthGrantTypeDeviceCode = "device_code"
Expand All @@ -35,12 +35,6 @@ const (
managedIdentitySettingsPath = "/var/lib/waagent/ManagedIdentity-Settings"
)

var ExpirationBase time.Time

func init() {
ExpirationBase, _ = time.Parse(time.RFC3339, tokenBaseDate)
}

// OAuthTokenProvider is an interface which should be implemented by an access token retriever
type OAuthTokenProvider interface {
OAuthToken() string
Expand Down Expand Up @@ -76,7 +70,10 @@ func (t Token) Expires() time.Time {
if err != nil {
s = -3600
}
return ExpirationBase.Add(time.Duration(s) * time.Second).UTC()

expiration := date.NewUnixTimeFromSeconds(float64(s))

return time.Time(expiration).UTC()
}

// IsExpired returns true if the Token is expired, false otherwise.
Expand Down
9 changes: 5 additions & 4 deletions autorest/adal/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"testing"
"time"

"github.com/Azure/go-autorest/autorest/date"
"github.com/Azure/go-autorest/autorest/mocks"
)

Expand Down Expand Up @@ -342,7 +343,7 @@ func TestServicePrincipalTokenRefreshReturnsErrorIfNotOk(t *testing.T) {
func TestServicePrincipalTokenRefreshUnmarshals(t *testing.T) {
spt := newServicePrincipalToken()

expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(expirationBase).Seconds()))
expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(date.UnixEpoch()).Seconds()))
j := newTokenJSON(expiresOn, "resource")
resp := mocks.NewResponseWithContent(j)
c := mocks.NewSender()
Expand Down Expand Up @@ -430,7 +431,7 @@ func TestRefreshCallback(t *testing.T) {
return nil
})

expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(expirationBase).Seconds()))
expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(date.UnixEpoch()).Seconds()))

sender := mocks.NewSender()
j := newTokenJSON(expiresOn, "resource")
Expand All @@ -451,7 +452,7 @@ func TestRefreshCallbackErrorPropagates(t *testing.T) {
return fmt.Errorf(errorText)
})

expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(expirationBase).Seconds()))
expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(date.UnixEpoch()).Seconds()))

sender := mocks.NewSender()
j := newTokenJSON(expiresOn, "resource")
Expand Down Expand Up @@ -554,7 +555,7 @@ func expireToken(t *Token) *Token {

func setTokenToExpireAt(t *Token, expireAt time.Time) *Token {
t.ExpiresIn = "3600"
t.ExpiresOn = strconv.Itoa(int(expireAt.Sub(expirationBase).Seconds()))
t.ExpiresOn = strconv.Itoa(int(expireAt.Sub(date.UnixEpoch()).Seconds()))
t.NotBefore = t.ExpiresOn
return t
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,19 @@ func LoadCLIProfile(path string) (AzureCLIProfile, error) {
return profile, nil
}

// LoadCLITokens restores a set of AzureCLIToken objects from a file located at 'path'.
func LoadCLITokens(path string) ([]AzureCLIToken, error) {
// LoadCLITokens restores a set of Token objects from a file located at 'path'.
func LoadCLITokens(path string) ([]Token, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
}
defer file.Close()

var tokens []AzureCLIToken
var tokens []Token

dec := json.NewDecoder(file)
if err = dec.Decode(&tokens); err != nil {
return nil, fmt.Errorf("failed to decode contents of file (%s) into a AzureCLIToken representation: %v", path, err)
return nil, fmt.Errorf("failed to decode contents of file (%s) into a `cli.Token` representation: %v", path, err)
}

return tokens, nil
Expand Down
File renamed without changes.
31 changes: 17 additions & 14 deletions autorest/adal/cli/token.go → autorest/azure/cli/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import (
"time"

"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/date"
"github.com/mitchellh/go-homedir"
)

// AzureCLIToken represents an AccessToken from the Azure CLI
type AzureCLIToken struct {
// Token represents an AccessToken from the Azure CLI
type Token struct {
AccessToken string `json:"accessToken"`
Authority string `json:"_authority"`
ClientID string `json:"_clientId"`
Expand All @@ -23,37 +24,39 @@ type AzureCLIToken struct {
UserID string `json:"userId"`
}

// ToToken converts an AzureCLIToken to a Token
func (t AzureCLIToken) ToToken() (*adal.Token, error) {
tokenExpirationDate, err := ParseAzureCLIExpirationDate(t.ExpiresOn)
// ToADALToken converts an Azure CLI `Token`` to an `adal.Token``
func (t Token) ToADALToken() (converted adal.Token, err error) {
tokenExpirationDate, err := ParseExpirationDate(t.ExpiresOn)
if err != nil {
return nil, fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err)
err = fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err)
return
}

difference := tokenExpirationDate.Sub(adal.ExpirationBase)
token := adal.Token{
difference := tokenExpirationDate.Sub(date.UnixEpoch())

converted = adal.Token{
AccessToken: t.AccessToken,
Type: t.TokenType,
ExpiresIn: "3600",
ExpiresOn: strconv.Itoa(int(difference.Seconds())),
RefreshToken: t.RefreshToken,
Resource: t.Resource,
}
return &token, nil
return
}

// AzureCLIAccessTokensPath returns the path where access tokens are stored from the Azure CLI
func AzureCLIAccessTokensPath() (string, error) {
// AccessTokensPath returns the path where access tokens are stored from the Azure CLI
func AccessTokensPath() (string, error) {
return homedir.Expand("~/.azure/accessTokens.json")
}

// ParseAzureCLIExpirationDate parses either a Azure CLI or CloudShell date into a time object
func ParseAzureCLIExpirationDate(input string) (*time.Time, error) {
// ParseExpirationDate parses either a Azure CLI or CloudShell date into a time object
func ParseExpirationDate(input string) (*time.Time, error) {
// CloudShell (and potentially the Azure CLI in future)
expirationDate, cloudShellErr := time.Parse(time.RFC3339, input)
if cloudShellErr != nil {
// Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone)
cliFormat := "2006-01-02 15:04:05.999999"
const cliFormat = "2006-01-02 15:04:05.999999"
expirationDate, cliErr := time.ParseInLocation(cliFormat, input, time.Local)
if cliErr == nil {
return &expirationDate, nil
Expand Down

0 comments on commit 3124dd5

Please sign in to comment.