08 Aug 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
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
[/ruby]
the file app/controllers/sessions_controller.rb
the content:
[ruby]
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["omniauth.auth"]
belongs_to_organization? info["credentials"]["token"]
session[:name] = info["info"]["name"] || info["info"]["email"] || info["info"]["nickname"] || "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
Michael Grosser
Posted at 04:50h, 30 AugustThanks for sharing, exactly what I was looking for, ran into the same security issue :)