Refactoring multiple if statements for user authentication with subdomains
- by go minimal
I'm building a typical web app where once a user signs up they access the app through their own subdomain (company.myapp.com). The "checking what kind of user if any is logged in" piece is starting to get very hairy and it obviously needs to be well-written because its run so often so I was wondering how you guys would re-factor this stuff.
Here are the different states:
A user must be logged in, the user must not have a company name, and the sub-domain must be blank
A user must be logged in, the user must have a company name, that company name must match the current sub-domain
A user must be logged in, the user must have a company name, that company name must match the current sub-domain, and the user's is_admin boolean is true
if !session[:user_id].nil?
@user = User.find(session[:user_id])
if @user.company.nil? && request.subdomains.first.nil?
return "state1"
elsif [email protected]?
if @user.company.downcase == request.subdomains.first.downcase && [email protected]_admin
return "state2"
elsif @user.company.downcase == request.subdomains.first.downcase && @user.is_admin
return "state3"
end
end
end