http://blog.rocodev.com/posts/14-using-github-organization
前幾天在 Ruby5 上看到介紹 wwarden-github-rails 這個 gem,覺得很酷,就幫他寫了一篇文章了。主要的想法是使用 Github 的 Team 和 Organization 和 Team 作 Application 認證。
特別適合早期 application 開發與內部工具
https://github.com/fphilipe/warden-github-rails/
gem "warden-github-rails"
github_client_id: ""
github_client_secret: ""
github_organization: "rocodev"
github_team:
name: "tech"
id: ""
client_id
/ client_secret
到 Github Application 註冊頁取得
註冊內容
新增一個檔案 config/initializers/warden_github_rails.rb
內容如下:
Warden::GitHub::Rails.setup do |config|
config.add_scope :admin, :client_id => Setting.github_client_id,
:client_secret => Setting.github_client_secret ,
:scope => 'repo'
config.default_scope = :admin
config.add_team Setting.github_team.name, Setting.github_team.id
end
config/routes.rb
github_authenticate(:org => Setting.github_organization, :team => Setting.github_team.name ) do
namespace :admin do
root :to => "base#index"
match '/logout' , :to => "base#logout", :as => :logout
end
end
app/controllers/admin/base_controller.rb
class Admin::BaseController < ApplicationController
def index
@is_admin = github_authenticated?(:admin)
sign_user_from_github(github_user)
end
def logout
github_logout
sign_out current_user
redirect_to root_path
end
protected
def sign_user_from_github(github_user)
user = User.find_or_create_from_github(github_user)
sign_in user
end
end
class User < ActiveRecord::Base
def self.find_or_create_from_github(github_user)
user = User.where(:email => github_user.email).first
if !user
user = User.new
user.email = github_user.email
user.name = github_user.name
user.password = Devise.friendly_token[0,20]
user.save!
end
return user
end
end