[Rails]自分のメモ用としてユーザー登録をGemでやる。[2019年2月10日]
この記事で出来ること
・e-mail/passwordでのユーザー登録
準備
・必要なgemをインストールする。今回はOmniauthも使っていく。
gem 'devise'
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem 'omniauth-google-oauth2'
bundle install --path vendor/bundle
Deviseでユーザー登録
①Gemfileにdeviseを追加する。
gem 'devise'
②terminalにコマンドを実行する。
bundle install --path vendor/bundle
rails g devise:install #generator
rails g devise:views #deviseのviewをコピー
rails g devise User #モデルを作成
rails db:migrate #これ絶対に実行してね。
③ApplicationController.rbにauthenticate_user!を追記する。
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user! #追記(userの部分はmodel名)
end
④serverを起動してみてhtpp://localhost::3000/users/sign_upにアクセスして動作を確認する。
これでユーザー登録の機能を作ることができる。
OmniAuthの実装
OmniAuthの実装を行っていく
Railsの設定
①oauthに必要なカラムをuserテーブルに追加していく。
rails g migration AddOmniauthToUsers provider:string uid:string
rails db:migrate
②initializerにomniauth用の設定を追記していく。scopeなど必要に応じて変更していく。
config.omniauth :facebook, ENV['FACEBOOK_KEY'],ENV['FACEBOOK_SECRET'],scope: 'email',info_fields:'email',callback_url: "#{ENV['HOST']}/users/auth/facebook/calback"
config.omniauth :twitter, ENV['TWITTER_API_KEY'],ENV['TWITTER_API_SECRET'],scope:'email',oauth_callback: "#{ENV['HOST']}/users/auth/twitter/callback"
config.omniauth :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], scope: 'email', redirect_uri: "#{ENV['HOST']}/users/auth/google_oauth2/callback"
OmniAuth.config.logger = Rails.logger if Rails.env.development? # debug用
③userモデルにomniauthableを追記。コールバックメソッドのfrom_omniauthを追加します。
class User < ApplicationRecord
devise :omniauthable, omniauth_providers: %i[facebook twitter google_oauth2]
# omniauthのコールバック時に呼ばれるメソッド
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
end
④ config/routes.rbにrouteを追加します。
devise_for :users, controllers: {omniauth_callbacks: 'users/omniauth_callbacks'}
⑤ Users::OmniauthCallbacksControllerを作成します。
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
# callback for facebook
def facebook
callback_for(:facebook)
end
# callback for twitter
def twitter
callback_for(:twitter)
end
# callback for google
def google_oauth2
callback_for(:google)
end
# common callback method
def callback_for(provider)
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in_and_redirect @user, event: :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format?
else
session["devise.#{provider}_data"] = request.env["omniauth.auth"].except("extra")
redirect_to new_user_registration_url
end
end
def failure
redirect_to root_path
end
end
⑥ /app/view/devise/registrations/new.html.erbにコード追加。
<%= render "devise/shared/links" %>
Twitterの認証設定
①twitter app(https://developer.twitter.com/en/apps)にアクセスしてAPIKEYとSECRETをコピー.
②callback urlを設定。 privacy policy, terms of serviceも何か埋めておく。
③permissionはread only,ユーザー登録にメールアドレスが必要なので「Request email addresses from users」チェックする。
この記事が気に入ったらサポートをしてみませんか?