Skip to content

Commit

Permalink
OAuth2: expires_in field of AccessToken is optional. Fixes #4041
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Feb 16, 2017
1 parent dbe0a29 commit 2114dc0
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 7 deletions.
10 changes: 10 additions & 0 deletions spec/std/oauth2/access_token_spec.cr
Expand Up @@ -46,6 +46,16 @@ class OAuth2::AccessToken
token.authenticate request, false
request.headers["Authorization"].should eq("Bearer access token")
end

it "builds from json without expires_in (#4041)" do
access_token = AccessToken.from_json(%({
"access_token" : "foo",
"token_type" : "Bearer",
"refresh_token" : "bar",
"scope" : "baz"
}))
access_token.expires_in.should be_nil
end
end

describe Mac do
Expand Down
7 changes: 3 additions & 4 deletions src/oauth2/access_token/access_token.cr
Expand Up @@ -26,7 +26,6 @@ abstract class OAuth2::AccessToken
end

access_token = access_token.not_nil!
expires_in = expires_in.not_nil!

if token_type
case token_type.downcase
Expand All @@ -43,12 +42,12 @@ abstract class OAuth2::AccessToken
end

property access_token : String
property expires_in : Int64
property expires_in : Int64?
property refresh_token : String?
property scope : String?

def initialize(@access_token : String, expires_in : Int, @refresh_token : String? = nil, @scope : String? = nil)
@expires_in = expires_in.to_i64
def initialize(@access_token : String, expires_in : Int?, @refresh_token : String? = nil, @scope : String? = nil)
@expires_in = expires_in.try &.to_i64
end

abstract def authenticate(request : HTTP::Request, tls)
Expand Down
18 changes: 15 additions & 3 deletions src/oauth2/session.cr
Expand Up @@ -3,7 +3,7 @@
class OAuth2::Session
getter oauth2_client : Client
getter access_token : AccessToken
getter expires_at : Time
getter expires_at : Time?

# Creates an `OAuth2::Session`.
#
Expand Down Expand Up @@ -32,13 +32,25 @@ class OAuth2::Session
end

private def access_token_expired?
Time.utc_now >= @expires_at
if expires_at = @expires_at
Time.utc_now >= expires_at
else
false
end
end

private def refresh_access_token
old_access_token = @access_token
@access_token = @oauth2_client.get_access_token_using_refresh_token(@access_token.refresh_token)
@expires_at = Time.utc_now + @access_token.expires_in.seconds

expires_in = @access_token.expires_in
if expires_in
@expires_at = Time.utc_now + expires_in.seconds
else
# If there's no expires_in in the access token, we assume it never expires
@expires_at = nil
end

@access_token.refresh_token ||= old_access_token.refresh_token
end
end

0 comments on commit 2114dc0

Please sign in to comment.