Performance: OAuth integration basics
OAuth integration affects page load speed mainly during the initial authentication redirect and token exchange phases.
class SessionsController < ApplicationController def create # Use asynchronous background job for token exchange OAuthTokenJob.perform_later(params.to_unsafe_h) redirect_to loading_path end end
class SessionsController < ApplicationController def create # Blocking synchronous HTTP call to OAuth provider response = Net::HTTP.post_form(URI('https://oauth.provider.com/token'), params) user_info = JSON.parse(response.body) # Heavy processing before redirect process_user_data(user_info) redirect_to root_path end end
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous token exchange in controller | Minimal | 0 | Low but delayed by network | [X] Bad |
| Asynchronous token exchange with background job | Minimal | 0 | Low and immediate | [OK] Good |
config/initializers/omniauth.rb file?Rails.application.config.middleware.use OmniAuth::Builder with a block specifying providers.provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] inside the middleware use call.session[:user_id] be set to if the user is found?def github
auth = request.env['omniauth.auth']
user = User.find_by(uid: auth['uid'], provider: auth['provider'])
if user
session[:user_id] = user.id
redirect_to root_path
else
redirect_to login_path
end
endsession[:user_id] to user.id.user.id representsdef google
auth = request.env['omniauth.auth']
user = User.find_or_create_by(uid: auth['uid']) do |u|
u.email = auth['info']['email']
u.provider = auth['provider']
end
session[:user_id] = user.id
redirect_to root_path
enduid: auth['uid'] to find or create a user, missing provider in the lookup.def oauth_callback
auth = request.env['omniauth.auth']
user = User.find_by(email: auth['info']['email'])
if user
# What should happen here?
else
user = User.create(
email: auth['info']['email'],
uid: auth['uid'],
provider: auth['provider']
)
end
session[:user_id] = user.id
redirect_to root_path
enduid and provider fields if missing to link OAuth data to one account.Pass the test and this pattern moves unknown