DEV Community

DavidNNussbaum
DavidNNussbaum

Posted on • Edited on

Rails Coding to Allow Log In Via Either Google or Facebook – A Step By Step Guide.

The setting up of coding to allow a user to log in via Google or Facebook is a little more complicated due to differences in their structure.

The first step is to set up an account with the two sites. The following blog gives guidance regarding signing up with Google:

https://medium.com/@amoschoo/google-oauth-for-ruby-on-rails-129ce7196f35

The blog giving guidance for signing up with Facebook is:

https://dev.to/nkemjiks/implementing-facebook-authentication-with-devise-for-your-rails-6-app-1p3b

These two blogs give full instructions regarding the setting up of Google and Facebook developer accounts respectively. These should be followed. The ID and secret are the two pieces of information that you will need to use in your code. The blogs also explain how to set up the rails code for the use of either one but there are some minor changes necessary in order for there to be the option of using either Google or Facebook. That code is what will be discussed here.

Be sure to have ‘uid’, ‘image’, and ‘provider’ columns in your users table. If not, use a migration to add them.

When a screenshot is shown, the code regarding Omniauth is the only code that needs to be utilized.

The next step is to add the omniauth related gems in the gemfile and use bundle install.

Gemfile - pharmacy-medications-tracker [WSL_ Ubuntu] - Visual Studio Code 4_18_2021 8_34_08 PM

Next Add the middleware to the project in config/initializers/omniauth.rb.

image

The next step is to add the following routes in config/routes.rb

image

Set up a controllers/omniauth_controller.rb file as follows:

image

The view allowing for usage of Google and Facebook would be set up as follows:

image

In config/routes.rb the following route would be used. In place of ‘social_media’, put in whichever view contains the link to Google and Facebook:

post '/sessions/social_media' => 'sessions#social_media'

Create a .env file. It is VERY IMPORTANT that you add this file to your .gitignore file so that the codes are not pushed to your github repository and viewed publicly, and set it up as follows, utilizing the ID and secret that you received from the Google and Facebook sites in place of the words ENTER YOUR CODE HERE.

image

Now you should be ready to allow users to log in with either Facebook or Google.

Top comments (0)