March 01, 2015

Home » » How To Login With Facebook Use Omniauth On Rails

How To Login With Facebook Use Omniauth On Rails

Posted by Unknown
0

Create a new rails application

# rails new sample_app

Open Gemfile and add following line into

gem 'omniauth'
gem 'omniauth-facebook'
Then run command to install it.
# bundle install

Create a provider

https://developers.facebook.com/

Go to My Apps and create a new app, copy App's ID and secret.

Configure

Configure your app to alive status

In config/initializers create omniauth.rb file

Add following lines
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, 'YOUR_APP_ID', 'YOUR_APP_SECRET'
end

Create login page

# rails g controller sessions new create

Open config/routes.rb

get   '/login', :to => 'sessions#new' => :login
get '/auth/:provider/callback' => 'sessions#create'

Open your app/controllers/sessions_controller.rb file and write the create method, like this:

def create
  auth_hash = request.env['omniauth.auth']
 
  render :text => auth_hash.inspect
end
Then you open browser and point to http://localhost:3000/auth/facebook, you can see some info of your facebook account.

Create a user model

# rails g model User name:string email:string
# rails generate model Authorization provider:string uid:string user_id:integer

Add the following code to your app/models/user.rb file:

has_many :authorizations
validates :name, :email, :presence => true

Add the following code to your app/models/authorization.rb file:

belongs_to :user
validates :provider, :uid, :presence => true

Modified create function in sessions_controller.rb

def create
  auth_hash = request.env['omniauth.auth']
 
  @authorization = Authorization.find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"])
  if @authorization
    render :text => "Welcome back #{@authorization.user.name}! You have already signed up."
  else
    user = User.new :name => auth_hash["info"]["name"], :email => auth_hash["info"]["email"]
    user.authorizations.build :provider => auth_hash["provider"], :uid => auth_hash["uid"]
    user.save
 
    render :text => "Hi #{user.name}! You've signed up."
  end
end
Go back, refresh web app. You can see your name !

Create destroy function to logout

Open sessions_controller.rb and add function:
def destroy
  session[:user_id] = nil
  render :text => "You've logged out!"
end
Open routes.rb, add route:
get '/logout' => 'sessions#destroy'





0 comments:

Post a Comment

Popular Posts

Labels

Archive

 

Blogroll

Recepies

Flickr Images

Copyright © 2014. Tutorials Blog - All Rights Reserved