You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
end
Setup routes.rb
Rails.application.routes.draw do
get '/auth/:provider', to: '/login'
get '/auth/github/callback', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
root 'home#show'
end
class SessionsController < ApplicationController
def create
user = User.find_or_create_from_auth(oauth_data)
if user
session[:user_id] = user.id
redirect_to dashboard_path
else
root_path
end
end
def destroy
session[:user_id] = nil
redirect_to root_path
end
private
def oauth_data
request.env['omniauth.auth']
end
end
User model
class User < ActiveRecord::Base
def self.find_or_create_from_auth(data)
user = User.find_or_create_by(provider: data.provider, uid: data.uid)
user.email = data.info.email
user.nickname = data.info.nickname
user.image_url = data.info.image
user.token = data.credentials.token
user.save
user
end
end
application_controller.rb
helper_method :current_user
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def authorize!
redirect_to root_path unless current_user
end