Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing Login with Sentry 2

I'm having trouble understanding Sentry 2 implementation for login. I mean in Sentry it was pretty strait forward. Provide username/email and password from Input to Sentry::login() method however they changed it now and it's really confusing.

First of all they removed Username column which makes no sense.
Second the login method now takes a User object that you need to retrieve using user's id which again makes no sense as you don't know the users id unless you make another query so they really complicated everything.

My code:

public function login()
{
    // Deny access to already logged-in user
    if(!Sentry::check())
    {
        $rules = array(
            'username' => 'required|unique:users',
            'password' => 'required' );

        $validator = Validator::make(Input::all(), $rules);

        if($validator->fails())
        {
            Session::flash('error', $validator->errors());
            return Redirect::to('/');
        }

        $fetch = User::where('username', '=', trim(Input::get('username')));
        $user = Sentry::getUserProvider()->findById($fetch->id);

        if(!Sentry::login($user, false))
        {
            Session::flash('error', 'Wrong Username or Password !');
        }

        return Redirect::to('/');

    }

    return Redirect::to('/');
}

I tried using this approach but it throws an exception: that id is unknown despite id being part of the table and User model being nothing but a class declaration with a $table = 'users'; attribute.

What am I doing wrong here or not understanding.

like image 392
Sterling Duchess Avatar asked Nov 30 '22 21:11

Sterling Duchess


1 Answers

Code below is my login method using Sentry 2. I'm basically letting Sentry do everything for me validation, find the user and, of course, login the user. Messages are in portuguese, but if you need me to translate just tell.

public function login()
{
    try
    {
        $credentials = array(
            'email'    => Input::has('email') ? Input::get('email') : null,
            'password' => Input::has('password') ? Input::get('password') : null,
        );

        // Log the user in
        $user = Sentry::authenticate($credentials, Input::has('remember_me') and Input::get('remember_me') == 'checked');

        return View::make('site.common.message')
            ->with('title','Seja bem-vindo!')
            ->with('message','Você efetuou login com sucesso em nossa loja.');

    }
    catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
    {
        return View::make('site.common.message')
            ->with('title','Erro')
            ->with('message','O campo do e-mail é necessário.');
    }
    catch (Cartalyst\Sentry\Users\PasswordRequiredException $e)
    {
        return View::make('site.common.message')
            ->with('title','Erro')
            ->with('message','O campo do senha é necessário.');
    }
    catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
    {
        $user = Sentry::getUserProvider()->findByLogin(Input::get('email'));

        Email::queue($user, 'site.users.emailActivation', 'Ativação da sua conta na Vevey');

        return View::make('site.common.message')
            ->with('title','Usuário não ativado')
            ->with('message',"O seu usuário ainda não foi ativado na nossa loja. Um novo e-mail de ativação foi enviado para $user->email, por favor verifique a sua caixa postal e clique no link que enviamos na mensagem. Verifique também se os nossos e-mails não estão indo direto para a sua caixa de SPAM.");
    }
    catch (Cartalyst\Sentry\Users\WrongPasswordException $e)
    {
        return View::make('site.common.message')
            ->with('title','Erro')
            ->with('message','A senha fornecida para este e-mail é inválida.');
    }       
    catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
    {
        return View::make('site.common.message')
            ->with('title','Erro')
            ->with('message','Não existe usuário cadastrado com este e-mail em nossa loja.');
    }

    // Following is only needed if throttle is enabled
    catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
    {
        $time = $throttle->getSuspensionTime();

        return View::make('site.common.message')
            ->with('title','Erro')
            ->with('message',"Este usário está suspenso por [$time] minutes. Aguarde e tente novamente mais tarde.");
    }
    catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
    {
        return View::make('site.common.message')
            ->with('title','Erro')
            ->with('message',"Este usário está banido do nossa loja.");
    }

}
like image 121
Antonio Carlos Ribeiro Avatar answered Dec 03 '22 23:12

Antonio Carlos Ribeiro