Job Search update — Rails and OAuth

gobias101
2 min readDec 23, 2021

This week, like the last, I contacted technical recruiters through LinkedIn hoping to get a foot in the door. My messages to them asks what quality skills they look for in boot camp grads to get hired/foot in the door. So far only one has wrote me back recently, but gave me good advice for when/if I ever land an interview.

For the technical portion of this blog we will talk about how to authenticate users in your Rails app using another website such as Facebook or Google. I am sure all of you have been to a website that lets you create an account or login using your account from another popular website. This is done through OAuth, or ‘Open Authorization.’ It allows the website to gather information about you such as name/age/sex/etc. from the other website without revealing your password.

TO setup OAuth in your rails program, first go intoo your gemfile and add the following gems:

gem 'jwt'
gem 'oath2'

The jwt gem is a simple we token that allows for encryption on your website, keeping passwords hidden from hackers. For this example we will use Facebook OAuth to allow users to log into your Rails app using Facebook. You can view the Facebook OAuth documentation and tutorials on how to setup a Facebook developers account and allow OAuth on your Rails app from this link:

Once you have that all setup, in your Ruby app, first go to your Routes file in your config folder and create a new route for the OAuth logins like so:

match '/auth/:provider/callback', to: 'sessions#facebook', via: [:get, :post]

Then, in your views page where the user logs in/creates a new account, you can add a link with this code so the button to login with Facebook will take the user to the Facebook OAuth login:

<%= link_to('Log in with Facebook!', '/auth/facebook') %>

Finally, in your sessions page you can write the code to gather whatever information you want from the users facebook page to create a new profile for them on your site:

class SessionsController < ApplicationController
...

def facebook
# finds existing user or creates new user based on omniAuth
# login
@user = User.find_or_create_by(uid: auth['uid']) do |u|
u.name = auth['info']['name']
u.email = auth['info']['email']
u.password = SecureRandom.hex
end

if @user.save
# if user is new, creates a new user entry in Users table,
# logs them in/starts new session
start_session
else
# if user already exists from previous omniauth login,
# logs them in/starts new session
start_session
end
end

...

private

...
def auth
request.env['omniauth.auth']
end

And thats it! now users can use your website by signing in through another, there are many websites that allow you to use OAuth to share information with your site, to find out more see the official OAuth page here:

https://oauth.net/2/

--

--