doorkeeper-gem/doorkeeper — pull request #492 by iangreenleaf (2014-10-11 07:45:47+00:00)
Title: Hook for custom validation rules in pre-authorization

This is an alternative solution to #317. It lays less responsibility on Doorkeeper than #469, so I'm hoping @tute will find this a reasonable thing for the gem to support. This PR doesn't make any assumptions about the persistence of the application-specific scopes, or the logic determining when scopes are valid. In fact, it isn't even limited to that exact use case - for example, my application cares less about limiting scopes to a certain application, and more about limiting scopes to users with certain privileges.

This simply adds a hook that runs during the `PreAuthorization` validations. The hook can perform whatever checks are desired, fail the validation if needed, and optionally provide a custom error message.

To use it, you put something like this into the initializer:

```ruby
validate_on_authorize do |validator, resource_owner, client, scopes|
false if scopes.include?('admin') && !resource_owner.admin?
end
```

Or to provide a custom error message, attach it to `validator.error`:

```ruby
validate_on_authorize do |validator, resource_owner, client, scopes|
if scopes.include?('admin') && !resource_owner.admin?
validator.error = :user_not_admin
end
end
```
And then provide a translation in your locale file:
```yml
en:
doorkeeper:
errors:
messages:
user_not_admin: You're not allowed admin powers
```