loading...

Omniauth GitHub on Rails

yutagoto profile image Yuta Goto ・2 min read

omniauth-githubでRuby on Railsのログイン機構を作るときに何度も検索したりすることがあるので、ざっくりやりかたをまとめました。

作業リポジトリ

README

This README would normally document whatever steps are necessary to get the application up and running.

Things you may want to cover:

  • Ruby version

  • System dependencies

  • Configuration

  • Database creation

  • Database initialization

  • How to run the test suite

  • Services (job queues, cache servers, search engines, etc.)

  • Deployment instructions

  • ...




環境

  • Ruby: 2.6.5
  • Rails: 6.0.2.2
  • omniauth-github: 1.4.0

使用したGem

GitHub logo omniauth / omniauth-github

GitHub strategy for OmniAuth

Ruby

OmniAuth GitHub

This is the official OmniAuth strategy for authenticating to GitHub. To use it, you'll need to sign up for an OAuth2 Application ID and Secret on the GitHub Applications Page.

Installation

gem 'omniauth-github', github: 'omniauth/omniauth-github', branch: 'master'

Basic Usage

use OmniAuth::Builder do
  provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
end

Github Enterprise Usage

provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
    {
      :client_options => {
        :site => 'https://github.YOURDOMAIN.com/api/v3'
        :authorize_url => 'https://github.YOURDOMAIN.com/login/oauth/authorize'
        :token_url => 'https://github.YOURDOMAIN.com/login/oauth/access_token',
      }
    }

Scopes

GitHub API v3 lets you set scopes to provide granular access to different types of data:

use OmniAuth::Builder do
  provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'], 

ざっくり手順

Gemfile に書き加える

gem 'omniauth-github'

bundle installする

GitHub Applicationを作る

https://github.com/settings/apps

上記リンクにアクセスして新規で作成する。

ぎてゅb

ざっくり編集する

開発用で設定するときは Homepage URLを http://localhost:3000、User authorization callback URLを http://localhost:3000/auth/github/callback にする。

Permissionの設定はユーザ登録だけであれば、User permissionsのEmail AddressesをRead-onlyにする

ぎっとはぶ

作成し終えたら Client IDとClient secretを控える

環境変数にセットする

EDITOR="vim" bin/rails credentials:edit
github_omniauth:
  client_id: hoge
  client_secret: hogehoge

yaml形式で設定する。実際に反映されるているか確認するときは、 rails console を使用する

$ rails c
Loading development environment (Rails 6.0.2.2)
irb(main):001:0> Rails.application.credentials.github_omniauth
=> {:client_id=>"hoge", :client_secret=>"hogehoge"}

Userモデルを作る

rails g model user name:string provider:string uid:text oauth_token:string
rails db:create
rails db:migrate
# app/models/user.rb
class User < ApplicationRecord
  def self.find_or_create_with_omniauth!(auth)
    user = find_by(uid: auth['uid'])
    return user if user.present?
    create! do |user|
      user.provider = auth['provider']
      user.uid = auth['uid']
      user.name = auth['info']['nickname']
      user.oauth_token = auth['credentials']['token']
    end
  end
end

Routingを設定する

# config/routes.rb
Rails.application.routes.draw do
  get 'auth/github/callback', to: 'sessions#callback'
  get '/sign_out', to: 'sessions#destroy'

  root 'homes#top'
end

SessionsControllerを作る

rails g controller sessions
# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  def callback
    user = User.find_or_create_with_omniauth!(request.env['omniauth.auth'])
    session[:user_id] = user.id
    redirect_to root_path
  end

  def destroy
    reset_session # セッションをリセットする
    redirect_to root_path
  end
end

HelperMethodを作る

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  helper_method :current_user, :logged_in?

  private

  def current_user
    return unless session[:user_id]
    @current_user ||= User.find(session[:user_id])
  end

  def logged_in?
    !!session[:user_id]
  end

  def authenticate
    return if logged_in?
    redirect_to root_path, alert: 'ログインしてください'
  end
end

Viewを作る

<%# app/views/homes/top.html.erb %>
<% if logged_in? %>
  <%= link_to 'Sign out', '/sign_out' %>
  <ul>
    <li>ID: <%= current_user.id %></li>
    <li>NAME: <%= current_user.name %></li>
    <li>PROVIDER: <%= current_user.provider %></li>
  </ul>
<% else %>
  <%= link_to 'Githubアカウントでサインイン', '/auth/github' %>
<% end %>

Omniauthの設定ファイルを作成する

touch config/initializers/omniauth.rb
# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :developer unless Rails.env.production?
  provider :github, Rails.application.credentials.github_omniauth[:client_id], Rails.application.credentials.github_omniauth[:client_secret], scope: "user"
end

実際に確認する

rails s

サインイン前

ro-karu

サインイン後

login

テストコード

途中

https://github.com/omniauth/omniauth/wiki/Integration-Testing

これを参考にすすめると良さそう

Posted on by:

Discussion

markdown guide