Hi everyone, I’d like some help to understand this method:
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
Don’t understand why it doesn’t return user instead of nil
since ‘user = find_by_email(email)’ was the last evaluated expression
like the comment, I just don’t get it, if anyone could explain it to me, please do it.
Because returning a user would mean that the answer was ambiguous, since it is both true-ish (yes, there's a user at that name) and false (no, that's not the right password for that user) at the same time. I can see why the decision was made to do things that way, since if authentication fails, you want to return false, not user, since user is apparently the signature of a successful login. In at least two authentication frameworks I have looked at, the authors are very clear about the sort of "no-answer" they give if you fail to log in. They don't say which was wrong -- username or password -- so that there's less evidence to go on in a dictionary attack.
# since 'user = find_by_email(email)' was the last evaluated expression
Wrong. In case user doesn't match password then last evaluated statement
which is a 'if modifier' for 'return user' statement; and it returned
nil. See from irb session:
ruby-1.9.2-p0 > true if false
ruby-1.9.2-p0 > true if true
In case 'if modifier' evaluates to false it will return nil - which is
exactly your case.
Thank you, I got it now =), I didn’t know that inside if evaluations counted.