Skip to content

Instantly share code, notes, and snippets.

@robzolkos
Created December 30, 2011 00:05
Show Gist options
  • Save robzolkos/1536810 to your computer and use it in GitHub Desktop.
Save robzolkos/1536810 to your computer and use it in GitHub Desktop.
custom user class to store user attributes retrieved from omniauth
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :login_required
helper_method :current_user
def current_ability
@current_ability ||= Ability.new(current_user)
end
protected
def login_required
if !current_user
respond_to do |format|
format.html {
redirect_to '/auth/identity'
}
format.json {
render :json => { 'error' => 'Access Denied' }.to_json
}
end
end
end
def current_user
session[:user]
end
rescue_from CanCan::AccessDenied do |exception|
flash[:alert] = "Access Denied!"
redirect_to "#{CUSTOM_PROVIDER_URL}"
end
end
class User
ATTRIBUTES = [:uid, :membername, :email,
:role, :id, :contact_number, :menubuilder, :venue, :venue_id]
attr_accessor *ATTRIBUTES
def initialize(attributes = {})
self.attributes = attributes
end
def self.from_omniauth(omniauth)
User.new(omniauth['info']).tap do | user |
user.uid = omniauth['uid']
end
end
def attributes
ATTRIBUTES.inject(ActiveSupport::HashWithIndifferentAccess.new) do |result, key|
result[key] = read_attribute_for_validation(key)
result
end
end
def attributes=(attrs)
attrs.each_pair {|k, v| send("#{k}=", v) if respond_to?("#{k}=") }
end
def read_attribute_for_validation(key)
send(key)
end
end
class UserSessionsController < ApplicationController
before_filter :login_required, :only => :destroy
respond_to :html
# Omniauth callback method
def create
session[:user] = User.from_omniauth(request.env['omniauth.auth'])
flash[:notice] = "Successfully logged in"
redirect_to root_path
end
# Omniauth failure callback
def failure
flash[:notice] = params[:message]
redirect_to root_path
end
# logout - Clear our rack session BUT essentially redirect to the provider
# to clean up the Devise session from there too !
def destroy
session[:user] = nil
flash[:notice] = 'You have successfully signed out!'
redirect_to "#{CUSTOM_PROVIDER_URL}/logout"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment