This repository provides a Hobby extension to authorize routes.
You are expected to pass your user models as arguments to Hobby::Auth.[]
:
require 'hobby'
require 'hobby/auth'
class YourApp
include Hobby
include Auth[*array_of_user_models]
# some route defining logic goes here, after 'includes'
end
A user model is any object that responds to these two methods:
-
.name
which returns aString
which might be in Module#name. -
.find_by_token
which takes one argument(a tokenString
), and returnsnil
(if no user were found) or a user(which can be any object you would like to consider a user in your application).
You can access that user via user
method.
Consider an example app where you need two user roles: managers and drivers.
You can define Manager
class as follows:
class Manager
def self.find_by_token token
new if token == 'the only valid token at the moment'
end
end
and Driver
class similarly.
Then, you can use them in your app:
class App
include Hobby
include Auth[Manager, Driver]
Manager post('/managers_route') {
# do something only managers can do
user # will return a `Manager` instance
}
Driver get('/drivers_route') {
# do something only drivers can do
user # will return a `Driver` instance
}
end
The token is expected to be passed via Authorization header. If no user were found, the response’s status will be set to 403.
Note
|
If your user models have same short names
(for example, Manager and SomeNamespace::Manager ),
a Hobby::Auth::SameNames error will be raised.
|