分享 使用 Github 的 Organization & Team 作認證

xdite · 2013年05月11日 · 最后由 bhuztez 回复于 2013年05月11日 · 3423 次阅读

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 取得 Application 註冊

填入設定到 config/config.yml 裡面

github_client_id: ""
github_client_secret: ""
github_organization: "rocodev"
github_team: 
   name: "tech"
   id: ""

註冊 OAuth Application

client_id / client_secretGithub Application 註冊頁取得

註冊內容

image

設定 warden-github-rails

新增一個檔案 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

設定 Rails Routing

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

設定 Admin::BaseController

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

在 User model 裡加上 find_or_create_from_github 選項

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

LDAP 哭了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号