Skip to content

Instantly share code, notes, and snippets.

@novohispano
Last active August 29, 2015 14:16
Show Gist options
  • Save novohispano/e5a7de854789e0e032a5 to your computer and use it in GitHub Desktop.
Save novohispano/e5a7de854789e0e032a5 to your computer and use it in GitHub Desktop.
Getting Started with OAuth
development:
github_key: 710899dd3710a6a9814e
github_secret: 102dc5253ae360eaae533e7dc5ceb46929dcbe4b
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
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
end
<div class="container-fluid container-home">
<div class="col-md-2"></div>
<div class="col-md-8">
<h1 class="home">You Are Authorized</h1>
<%= image_tag current_user.image_url, class: "img-circle img-thumbnail home-image" %>
<h2 class="home"> <%= current_user.nickname %> </h2>
<h2 class="home"> <%= current_user.email %> </h2>
<%= link_to "Logout", logout_path, method: :delete, class: "btn btn-lg btn-default btn-home" %>
</div>
<div class="col-md-2"></div>
</div>
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['github_key'], ENV['github_secret']
end
class SessionsController < ApplicationController
def create
@user = User.find_or_create_from_auth(request.env['omniauth.auth'])
if @user
session[:user_id] = @user.id
redirect_to dashboard_path
else
redirect_to root_path
end
end
def destroy
session.clear
redirect_to root_path
end
end
<div class="container-fluid container-home">
<div class="col-md-2"></div>
<div class="col-md-8">
<h1 class="home">You Are Authorized</h1>
<%= image_tag current_user.image_url, class: "img-circle img-thumbnail home-image" %>
<h2 class="home"> <%= current_user.nickname %> </h2>
<h2 class="home"> <%= current_user.email %> </h2>
<%= link_to "Logout", logout_path, method: :delete, class: "btn btn-lg btn-default btn-home" %>
</div>
<div class="col-md-2"></div>
</div>
class User < ActiveRecord::Base
def self.find_or_create_from_auth(auth)
user = User.find_or_create_by(provider: auth.provider, uid: auth.provider)
user.email = auth.info.email
user.nickname = auth.info.nickname
user.image_url = auth.info.image
user.token = auth.credentials.token
user.save
user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment