質問

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.

役に立ちましたか?

解決

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.");
    }

}

他のヒント

I'd like to share my take on Sentry 2 Auth routes. This is what I use now in all my projects. The 'Alert' class is from this package which I recently found. I use to pass it to the MessageBag but I like how clean this is.

class AuthController extends BaseController {

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

            // Authenticate our user and log them in
            $user = Sentry::authenticate($credentials, Input::get('remember_me') ?: false);

            // Tell them what a great job they did logging in.
            Alert::success(trans('success/authorize.login.successful'))->flash();

            // Send them where they wanted to go
            return Redirect::intended('/');

        }
        catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
        {
            Alert::error(trans('errors/authorize.login.required'))->flash();
        }
        catch (Cartalyst\Sentry\Users\PasswordRequiredException $e)
        {
            Alert::error(trans('errors/authorize.login.password.required'))->flash();
        }
        catch (Cartalyst\Sentry\Users\WrongPasswordException $e)
        {
            Alert::error(trans('errors/authorize.login.password.wrong'))->flash();
        }
        catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
        {
            Alert::error(trans('errors/authorize.login.user.found'))->flash();
        }
        catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
        {
            Alert::error(trans('errors/authorize.login.user.activated'))->flash();
        }
        // The following is only required if throttle is enabled
        catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
        {
            Alert::error(trans('errors/authorize.login.user.suspended'))->flash();
        }
        catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
        {
            Alert::error(trans('errors/authorize.login.user.banned'))->flash();
        }

        return Redirect::back()->withInput(Input::except('password'));
    }

    public function logout()
    {
        Sentry::logout();

        Alert::success(trans('success/authorize.logout.successful'))->flash();

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

You need to call the parent class constructor to inherit its functionality. In this case, the MainController constructor is not called and thus the check fails.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top