Guest User

Untitled

a guest
Jul 27th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. Use CanCan Authorization along with Custom Authentication in Rails 3
  2. class AccessController < ApplicationController
  3. before_filter :confirm_logged_in, :except => [:login, :attempt_login, :logout]
  4.  
  5. def attempt_login
  6. authorized_user = User.authenticate(params[:username], params[:password])
  7. if authorized_user
  8. session[:user_id] = authorized_user.id
  9. flash[:notice] = "You are logged in"
  10. redirect_to(:controller => 'orders', :action => 'list')
  11. else
  12. flash[:notice] = "Invalid Username/password combination"
  13. redirect_to(:action => 'login')
  14. end
  15. end
  16.  
  17. def logout
  18. session[:user_id] = nil
  19. flash[:notice] = "You have been logged out"
  20. redirect_to(:action => 'login')
  21. end
  22. end
  23.  
  24. require 'digest/sha1'
  25.  
  26. class User < ActiveRecord::Base
  27. has_one :profile
  28. has_many :user_roles
  29. has_many :roles, :through => :user_roles
  30.  
  31. attr_accessor :password
  32. attr_protected :hashed_password, :salt
  33.  
  34. def self.authenticate(username="", password="")
  35. user = User.find_by_username(username)
  36. if user && user.password_match(password)
  37. return user
  38. else
  39. return false
  40. end
  41. end
  42.  
  43. def password_match(password="")
  44. hashed_password == User.hash_with_salt(password, salt)
  45. end
  46.  
  47. validates_length_of :password, :within => 4..25, :on => :create
  48. before_save :create_hashed_password
  49. after_save :clear_password
  50.  
  51. def self.make_salt(username="")
  52. Digest::SHA1.hexdigest("Use #{username} with #{Time.now} to make salt")
  53. end
  54.  
  55. def self.hash_with_salt(password="", salt="")
  56. Digest::SHA1.hexdigest("Put #{salt} on the #{password}" )
  57. end
  58.  
  59. private
  60. def create_hashed_password
  61. unless password.blank?
  62. self.salt = User.make_salt(username) if salt.blank?
  63. self.hashed_password = User.hash_with_salt(password, salt)
  64. end
  65. end
  66.  
  67. def clear_password
  68. self.password = nil
  69. end
  70. end
  71.  
  72. class ApplicationController < ActionController::Base
  73. protect_from_forgery
  74.  
  75. private
  76.  
  77. def confirm_logged_in
  78. unless session[:user_id]
  79. flash[:notice] = "Please Log In"
  80. redirect_to(:controller => 'access', :action => 'login')
  81. return false
  82. else
  83. return true
  84. end
  85. end
  86. end
  87.  
  88. class UsersController < ApplicationController
  89. # your other actions here
  90.  
  91. def current_user
  92. User.find(session[:user_id])
  93. end
  94. end
Add Comment
Please, Sign In to add comment