CapabilityTokens

Build Status

This gem generates, stores, and helps you retrieve short-lived tokens with payloads. It is intended to be part of a capability link system, which allows users to perform actions without explicitly logging in.

Installation

Add this line to your application's Gemfile:

gem 'capability_tokens'

And then execute:

$ bundle

Then, install the migrations:

$ rake capability_tokens:install:migrations

And you're set! If you need to put the table this engine creates in a schema, create an initializer:

# config/initializers/capability_tokens.rb

CapabilityTokens.configure do |c|
  c.schema_name = 'my_stuff'
end

Usage

Generate a new token:

requester = 'customer-service'
payload   = { account_id: 1, action: 'login' }
cap_token = CapabilityTokens.generate(payload, requester, Time.now + 72.hours)

cap_token.token # => "82264468-6d50-454f-a257-007a89afa18b"

Disseminate the token as you see fit; e.g., in a link, like http://yourapp.com/do_it/82264468-6d50-454f-a257-007a89afa18b.

When a user follows that link, your controller might do:

begin
  token = CapabilityTokens.retrieve(params[:token])
  (token.payload[:account_id])
rescue CapabilityTokens::ExpiredToken
  raise "Too late!"
rescue CapabilityTokens::InvalidToken
  raise "Hacker!"
end

Note that CapabilityTokens::retrieve will always raise an exception if the retrieved token is either nonexistant or expired. You can rescue CapabilityTokens::BadToken to catch all errors.

FYI, "requester" is required as a very basic audit trail. If your needs are more complex, please open an issue and I'll investigate how to accomodate.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request