認証の習作: OmniAuth Google OAuth2 Strategy
外観
目的
ローカルの開発環境でGoogle OAuth2認証を行いたいと思います。
deviseなしでGoogle OAuth認証のサインインという投稿を参考にさせていただきました。
環境
macOS 10.15.4
Ruby 2.7.1
Rails 6.0.3.1
Yarn 1.22.4
Node 13.12.0
omniauth-google-oauth2 0.8.0
参照
リポジトリ
https://github.com/usutani/try_omniauth_google
Google APIs
参照先の手順通りに設定します。本家の説明に画像がなかったためとても参考になりました。感謝です。
実装
rails new -TM --skip-active-storage try_omniauth_google
cd try_omniauth_google
bundle add omniauth-google-oauth2
EDITOR=vim bin/rails credentials:edit
google:
client_id: Google APIsの認証情報で発行されたクライアントID
client_secret: Google APIsの認証情報で発行されたクライアントシークレット
bin/rails credentials:show
touch config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
google = Rails.application.credentials.google
provider :google_oauth2, google[:client_id], google[:client_secret]
end
bin/rails g model User provider uid name email image oauth_token oauth_expires_at:datetime
bin/rails db:migrate
bin/rails g controller Home index
bin/rails g controller Sessions new create destroy
config/routes.rb
Rails.application.routes.draw do
root to: 'home#index'
get 'auth/:provider/callback', to: 'sessions#create'
get 'auth/failure', to: redirect('/')
get 'signout', to: 'sessions#destroy', as: 'signout'
resources :sessions, only: %i[new create destroy]
resources :home, only: %i[index]
end
app/models/user.rb
class User < ApplicationRecord
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.email = auth.info.email
user.image = auth.info.image
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
return user
end
end
end
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.from_omniauth(request.env['omniauth.auth'])
if user.save
cookies.encrypted[:user_id] = user.id
redirect_to root_url
else
redirect_to new_session_url
end
end
def destroy
cookies.delete(:user_id)
redirect_to new_session_url
end
end
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
helper_method :current_user
def current_user
User.find(cookies.encrypted[:user_id]) if cookies.encrypted[:user_id]
end
end
app/views/layouts/application.html.erb
<body>
<div>
<% if current_user %>
Signed in as <strong><%= current_user.name %></strong>!
<%= link_to "Sign out", signout_path, id: "sign_out" %>
<% end %>
</div>
app/views/sessions/new.html.erb
<%= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in" %>
bin/rails s
open http://localhost:3000/sessions/new
以上です。
この記事が気に入ったらサポートをしてみませんか?