laravel 使用 Sentry 2 处理登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16851069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:50:31  来源:igfitidea点击:

Processing Login with Sentry 2

phplaravellaravel-4cartalyst-sentry

提问by Sterling Duchess

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.

我无法理解 Sentry 2 的登录实现。我的意思是,在哨兵中,前进的方向非常狭窄。提供从 Input 到Sentry::login()method 的用户名/电子邮件和密码,但是他们现在更改了它,这真的很令人困惑。

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.

首先,他们删除了没有意义的用户名列。
其次,登录方法现在需要一个 User 对象,您需要使用用户的 id 检索该对象,这再次没有意义,因为除非您进行另一个查询,否则您不知道用户 id,因此它们确实使一切变得复杂。

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.

我尝试使用这种方法,但它抛出了一个异常:尽管 id 是表的一部分,而 User 模型只是一个带有 $table = 'users'; 的类声明,但该 id 是未知的;属性。

What am I doing wrong here or not understanding.

我在这里做错了什么或不理解。

回答by Antonio Carlos Ribeiro

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.

下面的代码是我使用 Sentry 2 的登录方法。我基本上让 Sentry 为我做所有的验证,找到用户,当然,登录用户。消息是葡萄牙语,但如果您需要我翻译,请告诉我。

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

}

回答by gerobk

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 packagewhich I recently found. I use to pass it to the MessageBag but I like how clean this is.

我想分享我对 Sentry 2 Auth 路线的看法。这就是我现在在所有项目中使用的。“警报”类来自我最近发现的这个包。我过去常常将它传递给 MessageBag,但我喜欢它的干净程度。

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('/');
    }
}

回答by mimi

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.

您需要调用父类构造函数来继承其功能。在这种情况下,不会调用 MainController 构造函数,因此检查失败。