Rails 4: is it possible to extract complex authentication logic out of the controller? -
conventional rails best practices seek reduce logic code in controllers engineered route , not perform complex tasks.
however, if have semi-complex authentication logic, how can reasonably extract logic out of controller?
the following seems me "standard" logic basic application. while logic relates directly "routing", seems i'm putting logic controller , isn't small...am going overkill here?
is possible extract logic separate class since redirect_to ...
method accessible in controllers?
class sessionscontroller < applicationcontroller # login page posts here perform authentication logic def create user = user.find_by(email: params[:email]) if user , user.authenticate(params[:password]) # default has_secure_password if user.confirmed? if user.account.active? flash[:notice] = "successfully logged in" redirect_to root_path else flash[:error] = "this account no longer active" redirect_to inactive_account_path(user.account) end else flash[:alert] = "you not confirmed yet" redirect_to confirmation_path(user.confirmation_token) end else flash[:error] = "invalid email or password" redirect_to login_path end end end
you can throw stuff callbacks or similar if method little simpler, routing should more-or-less belong in controller.
class sessionscontroller < applicationcontroller before_filter :set_user, :check_confirmed def create if user.account.active? flash[:notice] = 'successfully logged in' redirect_to root_path else flash[:error] = 'this account no longer active' redirect_to inactive_account_path(user.account) end end private def set_user user = user.find_by(email: params[:email]) return if user.authenticate(params[:password]) flash[:error] = 'invalid email or password' redirect_to login_path end def check_confirmed return if user.confirmed? flash[:alert] = 'you not confirmed yet' redirect_to confirmation_path(user.confirmation_token) end end
note can put callbacks in applicationcontroller
if want sessionscontroller
little leaner.
but remember though sessions controller, , user state should managed somewhere else. ideally, logical position, create method should this:
def create user = user.find_by(email: params[:email]) if user flash[:notice] = 'successfully logged in' redirect_to root_path else flash[:error] = 'invalid email or password' redirect_to login_path end end
and put user status callbacks or similar somewhere else (applicationcontroller
or whatevs).
Comments
Post a Comment