Created
September 12, 2011 13:41
-
-
Save iwada/1211275 to your computer and use it in GitHub Desktop.
custom Authentication
This file contains hidden or 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
I have this issue, i'm new to rails. This is a custom authentication code, but when i enter a email address contained in my database, i get "Invalid Email/password Combination", | |
If i enter a valid email address but leave the password field blank, the user is loged in,What am i doing wrong please? | |
User.rb | |
def has_password?(submitted_password) | |
encrypted_password == encrypt(submitted_password) | |
end | |
class << self | |
def authenticate(email, submitted_password) | |
user = find_by_email(email) | |
return nil if user.nil? | |
return user if user.has_password?(submitted_password) | |
end | |
def authenticate_with_salt(id, cookie_salt) | |
user = find_by_id(id) | |
(user && user.salt == cookie_salt) ? user : nil | |
end | |
end | |
private | |
def encrypt_password | |
self.salt = make_salt if new_record? | |
self.encrypted_password = encrypt(password) | |
end | |
def encrypt(string) | |
secure_hash("#{salt}--#{string}") | |
end | |
def make_salt | |
secure_hash("#{Time.now.utc}--#{password}") | |
end | |
def secure_hash(string) | |
Digest::SHA2.hexdigest(string) | |
end | |
end | |
SessionController.rb | |
def create | |
user = User.authenticate(params[:session][:email], | |
params[:session][:password]) | |
if user.nil? | |
flash.now[:error] = "Invalid email/password combination." | |
@title = "Sign in" | |
render 'new' | |
else | |
sign_in user | |
redirect_back_or user | |
end | |
end | |
sessions/new.html.erb | |
.. | |
<%= form_for(:session, :url => sessions_path,:class => "expandedform") do |f| %> | |
<fieldset class=" round clearfix"> | |
<legend align="center">Enter Logon Details</legend> | |
<div class="row" align="center"> | |
<%= f.label :email %><br /> | |
<%= f.text_field :email,:class=>"texttop"%> | |
</div> | |
<div class="row" align="center"> | |
<%= f.label :password %><br /> | |
<%= f.password_field :password,:class =>"texttop"%> | |
</div> | |
<div class="row" align="center"> | |
<%= f.submit "Sign in", :class=> "new_project round" %> | |
</div> | |
<div class="row" align="center">New user? <%= link_to "Sign up now!", signup_path %></div> | |
<div class="row" align="center"><%= link_to "Forgot Password!", new_password_reset_path%></div> | |
</fieldset> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment