Search code examples
ruby-on-railsauthenticationsorcery

Sorcery notifications if activation status is pending


How to make sorcery gem show specific error when trying to log in account with 'pending' activation status?


Solution

  • It took me a while trying to figure it out until I hadnt found a way to do that in a github repository issues here written by him So I just wanted to copy (and change a bit) it here so it would be easier to find it if somebody else had this problem.

    1) in config/initializers/sorcery.rb change to

    user.prevent_non_active_users_to_login = false
    

    2) Change or rewrite somewhere 'login' method as shown here:

         def login(*credentials)
            @current_user = nil
            if credentials[0].is_a?(user_class)
              user = credentials.shift
              credentials.unshift(nil, nil)
            else
              user = user_class.authenticate(*credentials)
            end
            if user
              old_session = session.dup.to_hash
              reset_sorcery_session
              old_session.each_pair do |k,v|
                session[k.to_sym] = v
              end
              form_authenticity_token
    
              auto_login(user)
              after_login!(user, credentials)
              current_user
            else
              after_failed_login!(credentials)
              nil
            end
          end
    

    3) And in controller you can use something as the following:

      def create
        user = User.authenticate(params[:email], params[:password])
        if user
          if user.activation_state == 'active'
            login(user, params[:remember_me])
            redirect_back_or_to root_url, :notice => "Logged in"
          else
            render :pending
          end
        else
          flash.now.alert = "Email or password was invalid"
          render :new
        end
      end