Code Monkey home page Code Monkey logo

warden-github's Introduction

warden-github

A warden strategy that provides OAuth authentication to GitHub.

The Extension in Action

To play with the extension, follow these steps:

  1. Check out a copy of the source.

  2. Create an application on GitHub and set the callback URL to http://localhost:9292

  3. Run the following command with the client id and client secret obtained from the previous step:

    GITHUB_CLIENT_ID="<from GH>" GITHUB_CLIENT_SECRET="<from GH>" bundle exec rackup
    

    This will run the example app example/simple_app.rb.

    If you wish to see multiple user scopes in action, run the above command with an additional variable:

    MULTI_SCOPE_APP=1 GITHUB_CLIENT_ID="<from GH>" GITHUB_CLIENT_SECRET="<from GH>" bundle exec rackup
    

    This will run the example app example/multi_scope_app.rb.

  4. Point your browser at http://localhost:9292/ and enjoy!

Configuration

In order to use this strategy, simply tell warden about it. This is done by using Warden::Manager as a rack middleware and passing a config block to it. Read more about warden setup at the warden wiki.

For simple usage without customization, simply specify it as the default strategy.

use Warden::Manager do |config|
  config.failure_app = BadAuthentication
  config.default_strategies :github
end

In order to pass custom configurations, you need to configure a warden scope. Note that the default warden scope (i.e. when not specifying any explicit scope) is :default.

Here's an example that specifies configs for the default scope and a custom admin scope. Using multiple scopes allows you to have different user types.

use Warden::Manager do |config|
  config.failure_app = BadAuthentication
  config.default_strategies :github

  config.scope_defaults :default, config: { scope: 'user:email' }
  config.scope_defaults :admin, config: { client_id:     'foobar',
                                          client_secret: 'barfoo',
                                          scope:         'user,repo',
                                          redirect_uri:  '/admin/oauth/callback' }

  config.serialize_from_session { |key| Warden::GitHub::Verifier.load(key) }
  config.serialize_into_session { |user| Warden::GitHub::Verifier.dump(user) }
end

The two serialization methods store the API token in the session securely via the WARDEN_GITHUB_VERIFIER_SECRET environmental variable.

Parameters

The config parameters and their defaults are listed below. Please refer to the GitHub OAuth documentation for an explanation of their meaning.

  • client_id: Defaults to ENV['GITHUB_CLIENT_ID'] and raises if not present.
  • client_secret: Defaults to ENV['GITHUB_CLIENT_SECRET'] and raises if not present.
  • scope: Defaults to nil.
  • redirect_uri: Defaults to the current path. Note that paths will be expanded to a valid URL using the request url's host.

Using with GitHub Enterprise

GitHub API communication is done entirely through the octokit gem. For the OAuth process (which uses another endpoint than the API), the web endpoint is read from octokit. In order to configure octokit for GitHub Enterprise you can either define the two environment variables OCTOKIT_API_ENDPOINT and OCTOKIT_WEB_ENDPOINT, or configure the Octokit module as specified in their README.

JSON Dependency

This gem and its dependencies do not explicitly depend on any JSON library. If you're on ruby 1.8.7 you'll have to include one explicitly. ruby 1.9 comes with a json library that will be used if no other is specified.

Usage

Some warden methods that you will need:

env['warden'].authenticate!                   # => Uses the configs from the default scope.
env['warden'].authenticate!(:scope => :admin) # => Uses the configs from the admin scope.

# Analogous to previous lines, but does not halt if authentication does not succeed.
env['warden'].authenticate
env['warden'].authenticate(:scope => :admin)

env['warden'].authenticated?         # => Checks whether the default scope is logged in.
env['warden'].authenticated?(:admin) # => Checks whether the admin scope is logged in.

env['warden'].user         # => The user for the default scope.
env['warden'].user(:admin) # => The user for the admin scope.

env['warden'].session         # => Namespaced session accessor for the default scope.
env['warden'].session(:admin) # => Namespaced session accessor for the admin scope.

env['warden'].logout           # => Logs out all scopes.
env['warden'].logout(:default) # => Logs out the default scope.
env['warden'].logout(:admin)   # => Logs out the admin scope.

For further documentation, refer to the warden wiki.

The user object (Warden::GitHub::User) responds to the following methods:

user = env['warden'].user

user.id          # => The GitHub user id.
user.login       # => The GitHub username.
user.name
user.gravatar_id # => The md5 email hash to construct a gravatar image.
user.avatar_url
user.email       # => Requires user:email or user scope.
user.company

# These require user scope.
user.organization_member?('rails')         # => Checks 'rails' organization membership.
user.organization_public_member?('github') # => Checks publicly disclosed 'github' organization membership.
user.team_member?(1234)                    # => Checks membership in team with id 1234.

# API access
user.api # => Authenticated Octokit::Client for the user.

For more information on API access, refer to the octokit documentation.

Framework Adapters

If you're looking for an easy way to integrate this into a Sinatra or Rails application, take a look at the following gems:

Single Sign Out

OAuth applications owned by the GitHub organization are sent an extra browser parameter to ensure that the user remains logged in to github.com. Taking advantage of this is provided by a small module you include into your controller and a before filter. Your ApplicationController should resemble something like this.

class ApplicationController < ActionController::Base
  include Warden::GitHub::SSO

  protect_from_forgery with: :exception

  before_filter :verify_logged_in_user

  private

  def verify_logged_in_user
    unless github_user && warden_github_sso_session_valid?(github_user, 120)
      request.env['warden'].logout
      request.env['warden'].authenticate!
    end
  end
end

You can also see single sign out in action in the example app.

Additional Information

warden-github's People

Contributors

atmos avatar booch avatar btoews avatar chobie avatar defunkt avatar eugeneius avatar fphilipe avatar juno avatar laurentgo avatar pengwynn avatar pitr avatar sethvargo avatar sj26 avatar tclem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

warden-github's Issues

Warden::GitHub::User and Rails 4.1.0.rc2

I created a new Rails app using version 4.1.0.rc2, the latest warden-github release 1.0.1 and Ruby-2.1.1. After performing warden.authenticate! within my controller env['warden'].user results in an string class. Instead of a struct the result looks like a marshaled (Warden::GitHub::User) struct. I tried changing the ruby and warden-github version, but the only way to fix this problem was using the current Rails Version 4.0.4. Don't know if its the new Rails Version / dependencies. Anyone has the same Problem?

Please push a new gem

Y'all deprecated gravatar_id in the v3 api but you haven't pushed a new version of this gem after someone updated the warden user to include the avatar_url

Please push a new version

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can imagine, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

Bundler could not find compatible versions for gem "addressable"

Trying bundle install on master (dae6b8e) I get

$ bundle
Fetching gem metadata from https://rubygems.org/.........
Fetching additional metadata from https://rubygems.org/..
Resolving dependencies...
Bundler could not find compatible versions for gem "addressable":
  In Gemfile:
    webmock (~> 1.9) ruby depends on
      addressable (>= 2.2.7) ruby

    addressable (2.2.0)

Redirect URI Mismatch

@fphilipe running the example app gives me a 404 now. Any ideas?

127.0.0.1 - - [05/Feb/2013 00:51:32] "GET /auth/github/callback?error=redirect_uri_mismatch HTTP/1.1" 404 456 0.0020

Hard to handle GitHub API errors

I'm using this with your Sinatra gem.

After many debug prints, I found a bug here on this line:
https://github.com/atmos/warden-github/blob/master/lib/warden/github/oauth.rb#L50

That's basically assuming that any time we fail to get exactly what we want in response to authentication, we claim it's a Bad Verification Code, when really, any of the GitHub OAUTH errors will get pushed through there.

My workaround to figure out my problem was to split the line before the rescue into

params = decode_params(response.body)
params.fetch('access_token')

I could then look at the params in the rescue section, which revealed the problem I was having and the easiest way to test this:

I had my GitHub client secret wrong.

Specifically, I was getting the Invalid Client Credentials error from this page:
https://developer.github.com/v3/oauth/#common-errors-for-the-access-token-request

Wrong web endpoint used for enterprise github

For enterprise github instances, if octokit is directly configured instead of using environment variables OCTOKIT_ to specify the web domain and the API domain, warden-github may end up using the wrong domain name for authentication. The cause is that Octokit::Configuration::DEFAULT_WEB_DOMAIN is relying on environment only.

callbacks for after_set_user authentication event is being prevented from called

I wanted to add a logic to my app that gets triggered by authentication to certain scope.
I added a callback via Warden::Manager.after_set_user, but after_set_user callbacks never get triggered with :authentication event; I'm only seeing :fetch events.

It turned out that the first callback for after_set_user is this one (lib/warden/github/hook.rb) and it throws(:warden) in finalize_flow! which prematurely exits the entire stack of Warden::Proxy#authenticate!Warden::Proxy#_perform_authenticationWarden::Proxy#set_userWarden::Manager#_run_callbacks, most importantly skipping the rest of after_set_user callbacks in _run_callbacks.

Not sure if this is a bug or by design, but it would be nice to fix it or document/provide an alternative such that a process can be performed upon authentication (at the beginning of the session).

Right now, I'm using Warden::Manager.prepend_after_authentication to force my callback to come before the one above. It's not a very clean solution but probably an acceptable one if documented.

Membership data not being cached between requests

It looks like the membership data that is supposed to be cached between requests for 5 minutes is not being cached at all.

It looks like it was assumed that the User object would be serialized after each request, storing the modified membership cache in the session. Turns out that the user is only serialized once from Warden::Proxy#set_user that gets called when authentication is successfully performed the first time.

The solution would be to store the membership data (more precisely, any data potentially changing between requests) in Warden::Proxy#session, which "provides a scoped session data for authenticated users". In order to have access to that scoped session data, the User object needs to receive it at time of first initialization and deserialization. It can be retrieved from warden as follows (in both situations env is available): env['warden'].session(scope)

I'll open a PR for this. @atmos since this will need a minor version bump, should I already include it in the PR or would you like to handle that separately?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.