Phase 3 introduced Rails and all it’s magic, making sinatra the horse draw carriage compared to the ferrari that is rails. For this project, I once again kept the main theme that has driven the previous 2 projects from cli to sinatra. Tasked with building a web app, I set out to create, as most have already, a blog to create and review drinks, titled Booze-Hound.

One of the requirements was to set up a way to login using some form of authentication beyond just the regular password, that’s where omniauth comes in. Omniauth is a gem in rails that lets you use multiple authentication providers alongside the usual username/password getup. Essentially allowing you to sign in using your preferred credentials from either Google, Facebook, Twitter, etc. You probably already have an with one or more of those, it just makes life easier to use an already established id. My go to choice was google, and while setting it up can prove a little tricky the payoff is well worth it.

To begin lets get setup in google, head to the Google cloud platform https://console.developers.google.com/ , on the sidebar of APIs & Services click credentials, here you will and create a new project and following the onscreen instructions you can get setup really quickly at the end of this you should be presented with you Google client ID and Secret, save those we are going to need them.

Next to your app, first lets set up our gems, add omniauth, omniauth-google-oauth2, dotenv-rails to you gemfile (don’t forget to bundle). In your config/initializers/ create new file omniauth.rb and enter the code below

Rails.application.config.middleware.use OmniAuth::Builder do

provider :google_oauth2, ENV[‘GOOGLE_CLIENT_ID’], ENV[‘GOOGLE_CLIENT_SECRET’]

end

Next lets config/routes, we are adding the following: get ‘auth/:provider/callback’, to: ‘sessions#omniauth’

Over to our sessions controller and we will first create a private method auth: def auth

request.env[‘omniauth.auth’]

end

second will will create a method called omniauth to relate to our route we added. It is here that i suggest debugging with your preferred debugger, calling auth the the console will allow us to see what attributes are available and we can decided what to use to authenticate the user, (remember if you choose attributes your user model doesn’t already have you will have to setup migrations to add them). Once decided we can go ahead and write our login login in the omniauth method, also most similar to the create method of the same controller.

Go ahead and build your “login with Google” link where you have your login link and you are good to go. The step mostly play out the same with other providers but pay attention to the little details, like each provider has their own specific gem. Good luck and happy developing with rails.