Skip to content

Instantly share code, notes, and snippets.

@rickbacci
Last active September 19, 2015 23:37
Show Gist options
  • Save rickbacci/1215cb8c88588ebfbe31 to your computer and use it in GitHub Desktop.
Save rickbacci/1215cb8c88588ebfbe31 to your computer and use it in GitHub Desktop.
  • create app for id and secret
  • omniauth gem
  • setup figaro

initializers/omniauth.rb

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

home/show.html.haml

.row
  .col-md-2
  .col-md-8
    %h1.home Welcome
    = link_to "Login with Github", login_path, class: "btn btn-lg btn-default btn-home"
  .col-md-2

sessions_controller.rb

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment