Facebook authentication with devise in ruby on rails
Step 1: Preparing your Application
rails
new
omniauth-tutorial
And integrate devise
Step 2: Creating a Provider
In order to add a provider to Omniauth, you will need to sign up as a developer on the provider’s site. Once you’ve signed up, you’ll be given two strings (sort of like a username and a password), that needs to be passed on to Omniauth. If you’re using an OpenID provider, then all you need is the OpenID URL.If you want to use Facebook authentication, head over to developers.facebook.com/apps and click on “Create New App”.
Configuring Twitter is a bit more complicated on a development machine, since they don’t allow you to use “localhost” as a domain for callbacks. Configuring your development environment for this kind of thing is outside of the scope of this tutorial, however, I recommend you use Pow if you’re on a Mac.
Add to your
Gemfile
:gem 'omniauth-facebook'
Then
bundle install
.Step 3: Add your Providers to the App
Create a new file under config/initializers
called omniauth.rb
. We’re going to configure our authentication providers through this file.
Paste the following code into the file we created earlier:In config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder
do
provider
:facebook
,
YOUR_APP_ID
,
YOUR_APP_SECRET
end
Step 4: Creating the Login Page
rails generate controller sessions new create failure
Step 5: Creating the
Authentication
Modelrails generate model Authentication provider:string uid:string user_id:integer token:string
rake db:migrate
Add the following code to your
app/models/user.rb
file:has_many :authentications validates :name , :email , :presence => true
This specifies that a
user may have multiple authorizations, and that the name and email fields in the database are required. Next, to your app/models/ file, add:
|
Step 6: Adding a Bit of Logic to our Sessions Controller app/controllers/sessions_controller.rb
def
create
user = Authentication.from_omniauth(request.env["omniauth.auth"])
if user
flash[:notice] = "Authentication successful."
sign_in(user)
sign_in_and_redirect(user)
else
flash[:notice] = "Authentication Failed."
end
end
end
Next, to your app/models/authentication.rb
file:-
def self.from_omniauth(auth)
authenticate = where(provider: auth['provider'], :uid=>auth['uid']).first_or_initialize
if authenticate.user
authenticate.provider = auth.provider
authenticate.uid = auth.uid
authenticate.token = auth.credentials.token
else
user = User.new
authenticate.provider = auth.provider
authenticate.uid = auth.uid
authenticate.token = auth.credentials.token
user.email = auth.info.email
user.password = Devise.friendly_token.first(8)
user.save!
authenticate.user_id = user.id
end
authenticate.save
authenticate.user
end
In config/routes.rb:-
get 'auth/:provider/callback', to: 'sessions#create'
In Views :-
<a href="/auth/facebook" class="auth_provider">
Facebook
</a>
Comments
Post a Comment