Created
August 12, 2008 19:30
-
-
Save mig/5132 to your computer and use it in GitHub Desktop.
simple authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
include Authentication | |
# The rest of your codes go here | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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