Using Omniauth github to login and restricting depending on the organization

Using Omniauth github to login and restricting depending on the organization

First you need to create your personal Api and developer application in the follow url in github.com site:

https://github.com/settings/applications

restricting github organization

restricting github organization

The gems required in Gemfile:

gem 'omniauth-github'
gem 'httparty'

config/initializers/omniauth.rb

API_CONFIG = YAML.load_file("#{Rails.root}/config/api_config.yml")[Rails.env]
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :developer unless Rails.env.production?
  provider :github, API_CONFIG['key'], API_CONFIG['token']
end

The fileconfig/api_config.yml and its content:

github_key: &github_key
  token: ENV['token']
  key: ENV['key']
  organization: hackd
staging:<
  <<: *github_key
development:
  <<: *github_key
production:
  <<: *github_key
test:
  <<: *github_key
&#91;/ruby&#93;

the file app/controllers/sessions_controller.rb
the content:

&#91;ruby&#93;
require 'net/http'
class SessionsController < ApplicationController
  def new
  end
  def create
    reset_session # see http://guides.rubyonrails.org/security.html#session-fixation
    info = request.env&#91;"omniauth.auth"&#93;
    belongs_to_organization? info&#91;"credentials"&#93;&#91;"token"&#93;
    session&#91;:name&#93; = info&#91;"info"&#93;&#91;"name"&#93; || info&#91;"info"&#93;&#91;"email"&#93; || info&#91;"info"&#93;&#91;"nickname"&#93; || "fellow Ruby on Rails enthusiast"
    redirect_to events_path, :notice => "Welcome #{session[:name]}!"
  end

  def failure
    redirect_to login_url, :alert => 'Sorry, there was something wrong with your login attempt. Please try again.'
  end

  def destroy
    reset_session
    flash[:notice] = "Logged out."
    redirect_to events_path
  end

  private
  def belongs_to_organization? token
    url = "https://api.github.com/user/orgs?access_token=#{token}"
    @organizations = HTTParty.get(url)
    @organizations.map!{|x| x["login"]}.include? API_CONFIG['organization']
  end
end
1 Comment

Post A Comment