[英]Sentry Login using username or email (any of em) in Laravel 4
Currently I am using sentry login using email , I know how easily it can be converted into username if I simply change the 目前我正在使用电子邮件登录哨兵,我知道如果我只是改变它,它可以很容易地转换成用户名
sentry config file to this sentry配置文件到此
'login_attribute' => 'username',
But I find it odd because then the emailing of forget password info became unreachable. 但我发现它很奇怪,因为忘记密码信息的电子邮件变得无法访问。 What I want is, I want to give user the freedom to choose the artibute as username or email any of them, during the login ....
我想要的是,我想让用户在登录期间自由选择artibute作为用户名或电子邮件。
Any idea How to start ? 任何想法如何开始?
This is one way of doing it: 这是一种方法:
Locate the user using whatever login field your user choose: 使用您选择的任何登录字段找到用户:
$user = User::where(Input::get('login_field'), Input::get('login_name'))->first();
Create valid credentials using the e-mail of the user you just found: 使用您刚刚找到的用户的电子邮件创建有效凭据:
$credentials = array(
'email' => $user ? $user->email : null,
'password' => Input::get('password'),
);
And authenticate it: 并验证它:
$user = Sentry::authenticate($credentials, false);
Firstly, in the database user table, you should add username field into it. 首先,在数据库用户表中,您应该在其中添加用户名字段。
In your login function, you can do following to verify account by username or email: 在您的登录功能中,您可以执行以下操作以通过用户名或电子邮件验证帐户:
$username = Input::get('username');
$password = Input::get('password');
$field = filter_var($username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
try {
if (empty($username)) {
throw new Cartalyst\Sentry\Users\LoginRequiredException();
}
if (empty($password)) {
throw new Cartalyst\Sentry\Users\PasswordRequiredException();
}
$user = User::where($field, '=', $username)
->first();
if (empty($user)) {
throw new Cartalyst\Sentry\Users\UserNotFoundException();
}
if (!Hash::check($password, $user->password)) {
throw new Cartalyst\Sentry\Users\WrongPasswordException();
}
// Authenticate the user
Sentry::login($user, $remember);
}
catch (Cartalyst\Sentry\Users\LoginRequiredException $e) {
...
}
catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) {
...
}
catch (Cartalyst\Sentry\Users\WrongPasswordException $e) {
...
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
...
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) {
...
}
With this way, we only access to database one time for user information. 通过这种方式,我们只访问数据库一次用户信息。
Hope this help. 希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.