Skip to content

Instantly share code, notes, and snippets.

@benmoss
Created April 22, 2011 18:54
Show Gist options
  • Save benmoss/937368 to your computer and use it in GitHub Desktop.
Save benmoss/937368 to your computer and use it in GitHub Desktop.
Authlogic UserSessionsController
module AuthenticationHelpers
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
def require_user(format = nil)
unless current_user
respond_to do |format|
format.html do
store_location
# flash[:notice] = "You must be logged in to access this page"
redirect_to new_user_session_url
end
format.json do
render :json => {'errors' => "You must be logged in to access this endpoint"}, :status => 403
end
end
return false
end
end
def require_no_user(format = nil)
if current_user
respond_to do |format|
format.html do
store_location
# flash[:notice] = "You must be logged out to access this page"
redirect_to root_url
end
format.json do
render :json => '"You must be logged out to access this endpoint"', :status => 403
end
end
return false
end
end
def require_admin_privileges
unless current_user && current_user.admin?
store_location
redirect_to root_url
end
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
end
class UserSessionsController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_user, :only => [:destroy, :show]
def new
@user_session = UserSession.new
end
def create
respond_to do |format|
format.html {
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash.clear
redirect_back_or_default root_url
else
render :action => :new, :status => 401
end
}
format.json {
user_session = UserSession.new({
:login => params[:username],
:password => params[:password],
:remember_me => '1'
})
if user_session.save
render :json => {'user_session' => user_session.to_compact_user_session}
else
render :json => {'errors' => user_session.errors}, :status => 401
end
}
end
end
def show
respond_to do |format|
format.html {
redirect_to root_url
# Solves the occasional weird json login output we were getting
}
format.json {
render :json => {'user_session' => current_user_session.to_compact_user_session}
}
end
end
def destroy
current_user_session.destroy
respond_to do |format|
format.html {
flash[:notice] = "You have been logged out."
redirect_back_or_default root_url
}
format.json {
head 200
}
end
end
end
@meliho
Copy link

meliho commented Jan 14, 2013

Did you also add to_compact_user_session to your UserSession model?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment