Skip to content

ismasan/rack-oauth2utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rack OAuth Utils

Simple Rack middleware that catches OAuth2 access tokens and validates identity

This gem only covers the simple use of "using a token". You must implement the authorization and "getting a token" part in your app.

USAGE

class API < Sinatra::Base

  use Rack::OAuth2Utils::Middleware do |access_token|
    AccessToken.find_by_token(access_token).try :account_id
  end
  
  helpers do
      
    def authorized?
      !!identity
    end
    
    def identity
     requets.env['oauth.identity']
    end
    
    def current_account
     Account.find(identity) if authorized?
    end
     
  end
  
  get '/private' do
    if authorized?
      content_type 'application/json'
      current_account.to_json
    else
      halt 403, 'Access forbidden'
    end
  end
  
end

Rack::OAuth2Utils::Middleware takes a block with the request's access token. YOu can use it to resolve it to an identity string (ie a user or account id).

There is a test store based on PStore (filesystem. Do no use in production):

STORE = Rack::OAuth2Utils::TestStore.new('tmp/access_tokens.store')

STORE['foobar'] = 'some_identity'

use Rack::OAuth2Utils::Middleware do |access_token|
  STORE[access_token]
end

It is up to you how you store tokens and identities.

See test/middlewate_test.rb for details

About

Middleware for catching OAuth2 access tokens in Rack apps

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages