Authlogic validation order
guys. I have a problem when doing the authlogic login validation. I have the magical "active" field in the user model, say if active is false, when login with correct password, it will pop up the message like "You are suspended, please contact your administration" (I defined this message in I18n file); when login with wrong password, it will pop up the the not_active message plus password_invalid message like "password invalid". I think that is because authlogic did the validation both for "active" field and password and it seems password validation comes first.
My question is, how can bypass the password validation if 'active' is false. Or, can I only show not_active message? my code like:
if @user_session.save
redirect_to home_path
else开发者_如何学编程
render :json => {:success => false, :error => @user_session.errors.full_messages.join("\n")}
end
OK, so I don't like this as a user-experience, but if you really want to, do something like:
before_filter :restrict_inactive_users, :on=>:create
def restrict_inactive_users
@user = User.find_by_login(params[:user_session][:login]) rescue nil
return unless @user
unless @user.active?
flash[:error] = "You are suspended, please contact your administration"
render :action=>:new
return false
end
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
redirect_to home_path
else
render :json => {:success => false, :error => @user_session.errors.full_messages.join("\n")}
end
end
Today I thought out a solution which doesn't bypass the password validation but just delete the password error message from user_session. Code like:
if @user_session.save
redirect_to home_path
else
@user_session.errors.delete(:password) unless @user_session.attempted_record.active
render :json => {:success => false, :error => @user_session.errors.full_messages.join("\n")}
end
Start with fetching the user by the identifier of your choice, like the email or user name. If the user is not active you can remove the other errors before redirecting back to the login page.
@user_session.errors.clear
Then the errors will not show when the page is rerendered. But you must provide a custom error message, for example via the flash.now[:error]
or your json response.
精彩评论