Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Use CanCan Authorization along with Custom Authentication in Rails 3
- class AccessController < ApplicationController
- before_filter :confirm_logged_in, :except => [:login, :attempt_login, :logout]
- def attempt_login
- authorized_user = User.authenticate(params[:username], params[:password])
- if authorized_user
- session[:user_id] = authorized_user.id
- flash[:notice] = "You are logged in"
- redirect_to(:controller => 'orders', :action => 'list')
- else
- flash[:notice] = "Invalid Username/password combination"
- redirect_to(:action => 'login')
- end
- end
- def logout
- session[:user_id] = nil
- flash[:notice] = "You have been logged out"
- redirect_to(:action => 'login')
- end
- end
- require 'digest/sha1'
- class User < ActiveRecord::Base
- has_one :profile
- has_many :user_roles
- has_many :roles, :through => :user_roles
- attr_accessor :password
- attr_protected :hashed_password, :salt
- def self.authenticate(username="", password="")
- user = User.find_by_username(username)
- if user && user.password_match(password)
- return user
- else
- return false
- end
- end
- def password_match(password="")
- hashed_password == User.hash_with_salt(password, salt)
- end
- validates_length_of :password, :within => 4..25, :on => :create
- before_save :create_hashed_password
- after_save :clear_password
- def self.make_salt(username="")
- Digest::SHA1.hexdigest("Use #{username} with #{Time.now} to make salt")
- end
- def self.hash_with_salt(password="", salt="")
- Digest::SHA1.hexdigest("Put #{salt} on the #{password}" )
- end
- private
- def create_hashed_password
- unless password.blank?
- self.salt = User.make_salt(username) if salt.blank?
- self.hashed_password = User.hash_with_salt(password, salt)
- end
- end
- def clear_password
- self.password = nil
- end
- end
- class ApplicationController < ActionController::Base
- protect_from_forgery
- private
- def confirm_logged_in
- unless session[:user_id]
- flash[:notice] = "Please Log In"
- redirect_to(:controller => 'access', :action => 'login')
- return false
- else
- return true
- end
- end
- end
- class UsersController < ApplicationController
- # your other actions here
- def current_user
- User.find(session[:user_id])
- end
- end
Add Comment
Please, Sign In to add comment