Skip to content

Instantly share code, notes, and snippets.

@mm53bar
Created December 23, 2010 20:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mm53bar/753507 to your computer and use it in GitHub Desktop.
Save mm53bar/753507 to your computer and use it in GitHub Desktop.
Code to roll your own authentication!
class ApplicationController < ActionController::Base
include AuthenticateUser
before_filter :authenticate_user!
end
# lib/authenticate_user.rb
#
# Be sure to add lib to your autoload in config/application.rb
#
# config.autoload_paths += %W(#{config.root}/lib)
#
module AuthenticateUser
def self.included(base)
base.helper_method :current_user
end
protected
def authenticate_user!
redirect unless session[:user_id] && User.first(:conditions => {:id => session[:user_id]})
end
def sign_in_and_redirect(user, options = {})
session[:user_id] = user.id
options.reverse_merge!({:notice => I18n.t(:signed_in, :scope => 'app.sessions')})
redirect_to after_sign_in_path, options
end
def sign_out_and_redirect(options = {})
reset_session
options.reverse_merge!({:notice => I18n.t(:signed_out, :scope => 'app.sessions')})
redirect_to after_sign_out_path, options
end
private
def current_user
@current_user ||= User.first(:conditions => {:id => session[:user_id]}) if session[:user_id]
end
def redirect
store_location!
store_params!
redirect_to new_session_path
end
def store_location!
session[:return_to] = request.fullpath if request.get?
end
def stored_location
session.delete("return_to")
end
def store_params!
session[:params] = params
end
def stored_params
session[:params] || {}
end
def after_sign_in_path
stored_location || root_path
end
def after_sign_out_path
root_path
end
end
en:
app:
sessions:
signed_in: 'Signed in successfully.'
signed_out: 'Signed out successfully.'
invalid_login: 'Invalid email or password.'
class SessionsController < ApplicationController
skip_before_filter :authenticate_user!, :except => [:destroy]
def new
@user = User.new
end
def create
@user = User.find_by_email(params[:user][:email])
if @user && @user.authenticate(params[:user][:password])
sign_in_and_redirect(@user)
else
flash.now[:error] = I18n.t(:invalid_login, :scope => 'app.sessions')
render "new"
end
end
def destroy
sign_out_and_redirect
end
end
class User < ActiveRecord::Base
has_secure_password
#...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment