Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for active user state with laravel

This is pretty standard login function and validation that works nicely. But I also want to check that the user is active. I have set up a column in my users table with 'active' set to either 0 or 1.

public function post_login() 
{
    $input = Input::all();

    $rules = array(
        'email' => 'required|email',
        'password' => 'required',
    );  

    $validation = Validator::make($input, $rules);

    if ($validation->fails())
    {
        return Redirect::to_route('login_user')
            ->with_errors($validation->errors)->with_input();
    }

    $credentials = array(
        'username' => $input['email'],
        'password' => $input['password'],
    );

    if (Auth::attempt($credentials)) 
    {
        // Set remember me cookie if the user checks the box
        $remember = Input::get('remember');
        if ( !empty($remember) )
        {
            Auth::login(Auth::user()->id, true);
        }

        return Redirect::home();

    } else {
        return Redirect::to_route('login_user')
            ->with('login_errors', true);
    }
}

I've tried something like this already:

$is_active = Auth::user()->active;

if (!$is_active == 1)
{
    echo "Account not activated";
}

But this can only be used within the 'auth attempt' if statement and at that point the users credentials(email and pass) are already validated. So even if the users account if not active at this point they are already logged in.

I need a way to return validation to let them know they still need to activate their account and check if their account is set at the same time their email and pass are being checked.

like image 628
Stephan-v Avatar asked Dec 02 '22 23:12

Stephan-v


2 Answers

Filters are the way to go. It's easy and clean to solve this problem, see my example below.

Route::filter('auth', function()
{
    if (Auth::guest())
{
    if (Request::ajax())
    {
        return Response::make('Unauthorized', 401);
    }
    else
    {
        return Redirect::guest('login');
    }
}
else
{
    // If the user is not active any more, immidiately log out.
    if(Auth::check() && !Auth::user()->active)
    {
        Auth::logout();

        return Redirect::to('/');
    }
}
});
like image 163
blinkiebill Avatar answered Dec 05 '22 14:12

blinkiebill


Can't you use something like this:

if (Auth::once($credentials))
{
    if(!Auth::user()->active) {
        Auth::logout();

        echo "Account not activated";
    }
}
like image 26
Antonio Carlos Ribeiro Avatar answered Dec 05 '22 12:12

Antonio Carlos Ribeiro