HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Rails authentication checks

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
railsauthenticationchecks

Problem

I have this authenticate! method where I am trying to retrieve their account based on the subdomain, then find the user. if user is found & their password is matched, we return success, else fail in all other cases. here is the code:

def authenticate!
    account = Account.find_by(subdomain: subdomain)
    if account
      u = account.users.find_by email: params["user"]["email"]
      if u.nil?
        fail!
      else
        u.authenticate(params["user"]["password"]) ? success!(u) : fail!
      end
    else
      fail!
    end
end


Now, I could simply this further by moving subdomain into a helper method,

def subdomain
  ActionDispatch::Http::URL.extract_subdomains(request.host, 1)
end

def authenticate!
      account = Account.find_by(subdomain: subdomain)
      if account
        u = account.users.find_by email: params["user"]["email"]
        if u.nil?
          fail!
        else
          u.authenticate(params["user"]["password"]) ? success!(u) : fail!
        end
      else
        fail!
      end
end


But how to I simply these nested conditionals?

Solution

Another view on @tokland solution:

def authenticate!
  return fail! unless account = Account.find_by(subdomain: subdomain)
  return fail! unless user = account.users.find_by(email: params["user"]["email"])
  return fail! unless user.authenticate(params["user"]["password"])
  success! user
end


This intention is to be as close to "original task explained in common English" as possible. And return keyword allows me to do that.

Code Snippets

def authenticate!
  return fail! unless account = Account.find_by(subdomain: subdomain)
  return fail! unless user = account.users.find_by(email: params["user"]["email"])
  return fail! unless user.authenticate(params["user"]["password"])
  success! user
end

Context

StackExchange Code Review Q#31619, answer score: 8

Revisions (0)

No revisions yet.