Help us understand the problem. What is going on with this article?

RailsでFacebook認証を使う方法.(omniauth-facebookを使って)

More than 5 years have passed since last update.

Facebook認証をRailsアプリに使う方法を簡単にまとめたいと思います.
使うgemは omniauth-facebookです.

開発環境

  • Rails
    • 4.1.0
  • Ruby
    • 2.0.0
  • omniauth-facebook
    • 1.6.0

それでは書いていきましょう!

Gemfileにgemを記載する.

gem 'omniauth-facebook'
$ bundle install

モデルを作ります!

モデルを作って,メソッド書きます.

$ rails g model User provider uid name token
$ rake db:migrate
models/user.rb
def self.create_omniauth(auth)
    where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.name = auth.info.name
        user.token = auth.credentials.token
        user.save!
end

セッションを管理するコントローラを作る

$ rails g controller Sessions

ルーティング!

config.routes.rb
get 'auth/:provider/callback', to: 'sessions#create'
get 'auth/failure', to: redirect('/')
get 'signout', to: 'sessiongs#destroy', as: 'signout'

sessionsコントローラにcreateメソッドとdestroyメソッドを追加する

sessions_controller.rb
def create
    user = User.create_omniauth(env['omniauth.auth'])
    session[:user_id] = user.id
    redirect_to root_url
end

def destroy
    session[:user_id] = nil
    redirect_to root_url
end

ログイン中のユーザの情報を取れるように...

application_controller.rb
helper_method :current_user

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

サインインとサインアウトリンクをビューに表示させる

layouts/application.html.erb
<% if current_user %>
    <%= link_to 'Sign out,', signout_path %>
<% else %>
    <%= link_to 'Sign in with Facebook', '/auth/facebook' %>
<% end %>

終わり

これでRailsアプリにFacebook認証でログインさせる事が出来ます.
ただこれだとログインしていなくてもログイン後に表示させたいページも見れるようになってるので気を付けてください.
その方法に関してはまた別の機会にでも書こうかと思います!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした