Refactor code related to authentication:
* User model * SessionsController
This commit is contained in:
@@ -2,15 +2,12 @@ class SessionsController < ApplicationController
|
||||
skip_before_filter :authenticate!, :only => [:new, :create]
|
||||
|
||||
def create
|
||||
user = User.authenticate(
|
||||
params[:session][:email],
|
||||
params[:session][:password]
|
||||
)
|
||||
if ! user
|
||||
render 'new'
|
||||
else
|
||||
user = User.find_by_email(params[:session][:email])
|
||||
if user.try(:authenticate?, params[:session][:password])
|
||||
self.current_user = user
|
||||
redirect_to :root
|
||||
else
|
||||
render 'new'
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@@ -3,31 +3,18 @@ require 'bcrypt'
|
||||
class User < ActiveRecord::Base
|
||||
include BCrypt
|
||||
|
||||
attr_accessor :password
|
||||
attr_reader :password
|
||||
attr_accessible :email, :password, :password_confirmation
|
||||
|
||||
validates_presence_of :email
|
||||
validates_presence_of :email, :password_hash
|
||||
validates_confirmation_of :password
|
||||
|
||||
validates :password,
|
||||
:presence => true,
|
||||
:confirmation => true
|
||||
|
||||
before_save :hash_password
|
||||
|
||||
def self.authenticate(email, password)
|
||||
user = find_by_email(email)
|
||||
return false if user.nil?
|
||||
return user if Password.new(user.password_hash) == password
|
||||
def password=(plain_password)
|
||||
@password = plain_password
|
||||
self.password_hash = Password.create(plain_password)
|
||||
end
|
||||
|
||||
|
||||
private
|
||||
|
||||
def hash_password
|
||||
self.password_hash = bcrypt(password)
|
||||
end
|
||||
|
||||
def bcrypt(string)
|
||||
Password.create(string)
|
||||
def authenticate?(password)
|
||||
Password.new(password_hash) == password
|
||||
end
|
||||
end
|
||||
|
Reference in New Issue
Block a user