4

我无法理解用于登录的 Sentry 2 实现。我的意思是,在 Sentry 中,它非常狭窄。提供从输入到Sentry::login()方法的用户名/电子邮件和密码,但是他们现在更改了它,这真的很混乱。

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

我的代码:

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

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

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

4

3 回答 3

17

下面的代码是我使用 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.");
    }

}
于 2013-05-31T06:55:16.237 回答
2

我想分享我对 Sentry 2 Auth 路线的看法。这是我现在在所有项目中使用的。'Alert' 类来自我最近发现的这个包。我曾经将它传递给 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('/');
    }
}
于 2013-10-20T23:59:27.123 回答
0

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

于 2014-04-17T20:40:23.847 回答