Question

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

'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 ....

Any idea How to start ?

Was it helpful?

Solution

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);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top