Skip to content

Instantly share code, notes, and snippets.

@mig
Created August 12, 2008 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mig/5132 to your computer and use it in GitHub Desktop.
Save mig/5132 to your computer and use it in GitHub Desktop.
simple authentication
class ApplicationController < ActionController::Base
include Authentication
# The rest of your codes go here
end
module Authentication
def authorized?
logged_in?
end
def access_denied
store_location
redirect_to login_path
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
def login_required
authorized? || access_denied
end
def logged_in?
!!current_user_id
end
def current_user
@current_user ||= User.find(current_user_id)
end
def current_user=(user)
session[:user_id] = user ? user.id : nil
@current_user = user || false
end
def current_user_id
session[:user_id]
end
def self.included(base)
base.send :helper_method, :current_user, :logged_in?, :authorized? if base.respond_to? :helper_method
end
end
class User < ActiveRecord::Base
attr_accessor :password
before_create :hash_password
validates_presence_of :username, :password
validates_uniqueness_of :username
def self.authenticate(username, password)
find_by_username_and_password_hash(username, digest(password)) || false
end
def is_admin?
!!admin
end
private
def self.digest(string)
Digest::SHA1.hexdigest(string)
end
def hash_password
self.password_hash = self.class.digest(password)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment