LoginSignup
8
8

More than 5 years have passed since last update.

padrino で omniauth-github を使用して github 認証

Last updated at Posted at 2015-01-03

http://www.padrinorb.com/blog/padrino-and-omniauth-overview
上記を参考にして行いました。

対象読者

padrino で CRUD 開発が出来る方。

github 側

まず github 上で application の設定を行います。
https://github.com/settings/applications/
→ Register new application

Authorization callback URL は以下のように設定します。
http://******/auth/github/callback

設定が終わると、
Client ID と Client Secret が取得できます。

padrino 側

Gemfile に以下を追加します。

gem 'omniauth-github'

bundele します。

app.rb
module AuthProject
  class App < Padrino::Application
    use ConnectionPoolManagement
    register Padrino::Mailer
    register Padrino::Helpers
    use OmniAuth::Builder do
      provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
    end

github で取得した Client ID を ENV['GITHUB_KEY'] に
Client Secret を ENV['GITHUB_SECRET'] に記述します。
今回は、設定ファイルでの設定を割愛します。

controllers/auth.rb
AuthProject::App.controllers :auth do
  get :index do
    render :index
  end

  get :destroy do
    set_current_account(nil)
    redirect url(:auth, :index)
  end

  get :callback, :map => '/auth/:provider/callback' do
    auth = request.env['omniauth.auth']
    account = Account.find_by_provider_and_uid(auth['provider'], auth['uid']) ||
    Account.create_with_omniauth(auth)
    set_current_account(account)
    redirect 'http://' + request.env['HTTP_HOST'] + url(:account, :profile)
  end
end

controllers/account.rb
AuthProject::App.controllers :account do
  get :profile do
    content_type :text
    current_account.to_yaml
  end
end
views/auth/index.erb
<!DOCTYPE html>
<html>
<head>
  <title>github認証</title>
</head>
<body>
  <% if logged_in? %>
    <%= link_to 'sign out', '/auth/destroy/' %>
  <% else %>
    <%= link_to 'sign in with github', '/auth/github/' %>
  <% end %>
</body>
</html>

model を作成します。

$ padrino g model Account name:string email:string role:string uid:string provider:string
$ padrino rake ar:migrate
models/account.rb
class Account < ActiveRecord::Base
  def self.create_with_omniauth(auth)
    create!(
      provider: auth['provider'],
      uid: auth['uid'],
      name: auth['name'],
      role: 'users'
    )
  end
end

githubユーザの情報でアカウントを作成するようにします。

これで認証が行えるようになりました。

認証でのアクセス制限を行う場合は以下のように設定します。

app.rb
register Padrino::Admin::AccessControl

set :login_page, '/auth'
access_control.roles_for :any do |role|
  role.protect "/account"
end

# now we add a role for users
access_control.roles_for :users do |role|
  role.allow "/account/profile"
end

以上です。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8