Skip to content

Commit

Permalink
Rename (Re)Authorization to (Re)Authentication
Browse files Browse the repository at this point in the history
Now, the Authentication method requires a token which can be obtained
through ObtainAccessToken() method on the client. Reauthentication
does not need any extra parameters, as the state is kept in the client.
  • Loading branch information
Nenad Stojanovikj authored and Nenad Stojanovikj committed Dec 16, 2018
1 parent ca80f72 commit f2f4b02
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 15 deletions.
31 changes: 24 additions & 7 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const (
OpenSourceClientId = "X245A4XAIBGVM"
)

// StartAuthentication starts the authentication flow for the service
// RealDebrid API information: https://api.real-debrid.com/#device_auth_no_secret
func (c *Client) StartAuthentication(clientID string) (v Verification, err error) {
authUrl, err := url.Parse(DeviceUrl)
if err != nil {
Expand All @@ -37,6 +39,8 @@ func (c *Client) StartAuthentication(clientID string) (v Verification, err error
return v, err
}

// ObtainSecret returns the Client ID and Client secret that are used for
// obtaining a valid token in the next step
func (c *Client) ObtainSecret(deviceCode, clientID string) (secrets Secrets, err error) {
authUrl, err := url.Parse(CredentialsUrl)
if err != nil {
Expand All @@ -60,7 +64,8 @@ func (c *Client) ObtainSecret(deviceCode, clientID string) (secrets Secrets, err
return secrets, err
}

func (c *Client) Authorize(clientID, secret, code string) (err error) {
// ObtainAccessToken tries to get the client ID
func (c *Client) ObtainAccessToken(clientID, secret, code string) (t Token, err error) {
resp, err := c.postForm(TokenUrl, url.Values{
"client_id": {clientID},
"client_secret": {secret},
Expand All @@ -69,17 +74,22 @@ func (c *Client) Authorize(clientID, secret, code string) (err error) {
})

if err != nil {
return err
return t, err
}

t := Token{}
t.obtainedAt = time.Now()
err = json.NewDecoder(resp.Body).Decode(&t)
return t, err
}

// Authenticate sets a given token for authentication for further requests
func (c *Client) Authenticate(t Token) {
c.token = t
return err
}

func (c *Client) Reauthorize() error {
// Reauthenticate tries to get a new token from the service, and if successful
// it sets the new token
func (c *Client) Reauthenticate() error {
if c.token.RefreshToken == "" {
return fmt.Errorf("cannot reauthorize without refresh token")
}
Expand All @@ -89,15 +99,22 @@ func (c *Client) Reauthorize() error {
return err
}

return c.Authorize(secrets.ClientID, secrets.ClientSecret, c.token.RefreshToken)
t, err := c.ObtainAccessToken(secrets.ClientID, secrets.ClientSecret, c.token.RefreshToken)
if err != nil {
return err
}

c.Authenticate(t)
return nil
}

// IsAuthorized checks if the current token is still valid
func (c *Client) IsAuthorized() bool {
if c.token.AccessToken == "" || c.token.RefreshToken == "" {
return false
}

// We expire the token 10 seconds before, so we don't send a request and risk to have it failed mid-transport
// We expire the token 10 seconds before, so we don't send a request and risk to have it failing during transport
tokenExpiry := c.token.obtainedAt.Add(time.Second * time.Duration(c.token.ExpiresIn-10))
return time.Now().Before(tokenExpiry)
}
19 changes: 11 additions & 8 deletions auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ func TestClient_AuthorizeSuccess(t *testing.T) {
}
})

err := client.Authorize("0N2RHHK5OKNIX", "135d1b6dc60dddbcaa2e5dc1772c85d56c5479ba", "ZD7HNOMEXOJY7P2FP4XIJA5E634RWZKWWQ6RZNJJT235G4RNCAOP")
token, err := client.ObtainAccessToken("0N2RHHK5OKNIX", "135d1b6dc60dddbcaa2e5dc1772c85d56c5479ba", "ZD7HNOMEXOJY7P2FP4XIJA5E634RWZKWWQ6RZNJJT235G4RNCAOP")
client.Authenticate(token)
assert.NoError(t, err)
expectedToken := Token{
ExpiresIn: 3600,
Expand All @@ -107,10 +108,10 @@ func TestClient_AuthorizeSuccess(t *testing.T) {
RefreshToken: "ZD7HNOMEXOJY7P2FP4XIJA5E634RWZKWWQ6RZNJJT235G4RNCAOP",
}

assert.Equal(t, expectedToken.ExpiresIn, client.token.ExpiresIn)
assert.Equal(t, expectedToken.AccessToken, client.token.AccessToken)
assert.Equal(t, expectedToken.TokenType, client.token.TokenType)
assert.Equal(t, expectedToken.RefreshToken, client.token.RefreshToken)
assert.Equal(t, expectedToken.ExpiresIn, token.ExpiresIn)
assert.Equal(t, expectedToken.AccessToken, token.AccessToken)
assert.Equal(t, expectedToken.TokenType, token.TokenType)
assert.Equal(t, expectedToken.RefreshToken, token.RefreshToken)
assert.True(t, client.IsAuthorized())
}

Expand All @@ -132,7 +133,9 @@ func TestClient_AuthorizeFailure(t *testing.T) {
}
})

err := client.Authorize("0N2RHHK5OKNIX", "135d1b6dc60dddbcaa2e5dc1772c85d56c5479ba", "ZD7HNOMEXOJY7P2FP4XIJA5E634RWZKWWQ6RZNJJT235G4RNCAOP")
token, err := client.ObtainAccessToken("0N2RHHK5OKNIX", "135d1b6dc60dddbcaa2e5dc1772c85d56c5479ba", "ZD7HNOMEXOJY7P2FP4XIJA5E634RWZKWWQ6RZNJJT235G4RNCAOP")
client.Authenticate(token)
assert.Empty(t, token)
assert.EqualError(t, err, "error_message: wrong_parameter\nerror_code: 2 - Unknown error\nerror_details: \nstatus_code: 400\n")
assert.False(t, client.IsAuthorized())
}
Expand All @@ -159,7 +162,7 @@ func TestClient_Reauthorize(t *testing.T) {

return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewBufferString(`{"access_token": "QMUJ32Q4S3X57D3NC354V4OI62JZ74KV5H3DZX7JJEOZSLXCWVYA", "expires_in": 3600, "refresh_token": "ZD7HNOMEXOJY7P2FP4XIJA5E634RWZKWWQ6RZNJJT235G4RNCAOP", "token_type": "Bearer" }`)),
Body: ioutil.NopCloser(bytes.NewBufferString(`{"access_token": "ZMUJ32Q4S3X57D3NC354V4OI62JZ74KV5H3DZX7JJEOZSLXCWVYA", "expires_in": 3600, "refresh_token": "QD7HNOMEXOJY7P2FP4XIJA5E634RWZKWWQ6RZNJJT235G4RNCAOP", "token_type": "Bearer" }`)),
Header: map[string][]string{
"Content-Type": {"application/json"},
},
Expand All @@ -169,7 +172,7 @@ func TestClient_Reauthorize(t *testing.T) {
return nil
})

err := client.Reauthorize()
err := client.Reauthenticate()
assert.NoError(t, err)
assert.True(t, client.IsAuthorized())
}
Expand Down

0 comments on commit f2f4b02

Please sign in to comment.