applicake/doorkeeper — Issue #39: AuthorizationRequest can return expired access token, even if valid one is available
Author: GoldsteinTechPartners
Created: 2012-01-15 04:55:39+00:00
State: open

There is an issue with the access_token method in Authorization Request

```ruby
def access_token
AccessToken.accessible.where(:application_id => client.id, :resource_owner_id => resource_owner.id).first
end
```

There are two potentially issues here:

i) The query itself doesn't exclude expired tokens. That is, a token where (created_at + expires_in) < Time.now, but that hasn't been explicitly revoked. That token will still be in the database and can (and often will) be returned in this query. While this is checked in the request itself, it is possible that this query will return an expired token even if a valid, unexpired token exists in the table.

ii) This method doesn't have an explicit sort, defaulting to the sort of the underlying data store. As most common databases (MySQL, PostgreSQL, Oracle, etc.) don't guarantee sort results unless an order is specified, this return value is non-deterministic for many data sets.

Handling this in a data-store independent way is a little tricky, as there's no explicit 'expires_at' column in the table on which we can sort. So the easiest way to do it is probably something like this:

```ruby
def access_token
AccessToken.accessible.where(:application_id => client.id, :resource_owner_id => resource_owner.id).where("created_at >= ?", Time.now - expires_in.seconds).order("created_at DESC").first
end
```

This could also be moved into the AccessToken class itself, as a factory method.

Thoughts?