Skip to content

Instantly share code, notes, and snippets.

@cmkoller
Last active August 29, 2015 14:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmkoller/f87a5aaf3819a1f0a20f to your computer and use it in GitHub Desktop.
Save cmkoller/f87a5aaf3819a1f0a20f to your computer and use it in GitHub Desktop.

1. Make sure you have ActiveRecord set up in your app

(Follow these steps if not)

2. Add gem 'omniauth-github' to your Gemfile

3. Bundle

4. Add the following code to server.rb:

require 'Dotenv'
require 'sinatra'
require 'sinatra/activerecord'
require 'sinatra/flash'
require 'omniauth-github'

require_relative 'config/application'

Dotenv.load

Dir['app/**/*.rb'].each { |file| require_relative file }

helpers do
  def current_user
    user_id = session[:user_id]
    @current_user ||= User.find(user_id) if user_id.present?
  end

  def signed_in?
    current_user.present?
  end

end

def set_current_user(user)
  session[:user_id] = user.id
end

def authenticate!
  unless signed_in?
    flash[:notice] = 'You need to sign in if you want to do that!'
    redirect '/'
  end
end

def is_member?(meetup_id, user_id)
  if signed_in?
    !Membership.where(["user_id = ? and meetup_id = ?", user_id, meetup_id]).empty?
  end
end


get '/' do
  erb :index
end

get '/auth/github/callback' do
  auth = env['omniauth.auth']

  user = User.find_or_create_from_omniauth(auth)
  set_current_user(user)
  flash[:notice] = "You're now signed in as #{user.username}!"
  redirect '/'
end

get '/sign_out' do
  session[:user_id] = nil
  flash[:notice] = "You have been signed out."

  redirect '/'
end

get '/example_protected_page' do
  authenticate!
end

5. Create config/application.rb and add the following code:

configure :development do
  require 'dotenv'
  Dotenv.load

  require 'sinatra/reloader'
  require 'pry'

  also_reload 'app/**/*.rb'
end

configure do
  enable :sessions
  set :session_secret, ENV['SESSION_SECRET']

  set :views, 'app/views'

  use OmniAuth::Builder do
    provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'],
      scope: 'user:email'
  end
end

6. Create a migration called CreateUsers (or something similar) with the following code inside:

  def change
    create_table :users do |table|
      table.string :provider, null: false
      table.string :uid, null: false
      table.string :username, null: false
      table.string :email, null: false
      table.string :avatar_url, null: false

      table.timestamps
    end

    add_index :users, [:uid, :provider], unique: true
  end

7. Run rake db:migrate

8. Add /app/models/user.rb and add the following code:

class User < ActiveRecord::Base
def self.find_or_create_from_omniauth(auth)
  provider = auth.provider
  uid = auth.uid

  find_by(provider: provider, uid: uid) || create_from_omniauth(auth)
end

def self.create_from_omniauth(auth)
  create(
    provider: auth.provider,
    uid: auth.uid,
    email: auth.info.email,
    username: auth.info.nickname,
    avatar_url: auth.info.image
  )
end
end

9. Set up your app on Github

  • Go to "Settings" (under dropdown on top right)
  • Click "Applications", then "Developer Applications", then "Register New Application"
  • Fill out the name w/ the name of your app
  • Fill out "homepage url" with http://localhost:4567/
  • Fill out "callback url" with http://localhost:4567/auth/github/callback
  • Click "create application"
  • Take note of the "Client ID" and "Client Secret" values that are listed in the top right of your app information - you'll need them in just a sec!

Set up your .ENV file

  • Create a .env file in the root directory of your app
  • Go find your "Client ID" value as provided on your Github Application page (created above). This is your "GITHUB_KEY"
  • Go find your "Client Secret" value in the same place as the Client ID value was. This is your "GITHUB_SECRET"
  • Open your .env file and add the following things:
SESSION_SECRET='this can be anything you want'

GITHUB_KEY='your-github-key-as-found-above'
GITHUB_SECRET='your-github-secret-as-found-above'

Of course, repace the values of GITHUB_KEY and GITHUB_SECRET. The SESSION_SECRET can be whatever you want.

10. Add links

Add links to sign in and out. The path to sign in is "/auth/github", the path to sign out is "/sign_out"

    <% if signed_in? %>
  • Signed in as <%= current_user.username %>
  • Sign out
  • <% else %>
  • Sign in
  • <% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment