Frage

I would like to customize my login in laravel 4 where username is either his username or email so what I did is:

public static function custom_login($uname,$pwd)
{
    $res = DB::select("select * from users where (username = ? or email = ?) and password = ? and active = 1",array($uname,$uname,$pwd));
            return $res;
}

Now, we all know that password are hashed so you cant use password = ?. how can I check the password if it's correct?

War es hilfreich?

Lösung 3

You can use

$password = Hash::make($password);

function to get the hash of password, and then check it

Andere Tipps

I agree with guys here with the principle, but I would use Eloqunet, just in case the table name will change in the future.

$user = User::whereRaw('email = ? OR username = ?', array('value', 'value'))->first();

if ( ! $user) {
    return false;
}

if (Hash::check('password', $user->password)) {
    // The passwords match, log in the user
    Auth::loginUsingId( $user->id );
}

I wrote code on the fly, so sorry if any syntax error is present.

You first need to get the password from the database. Then do Hash::check($pwd, $theDatabasepassword) to see if it matches.

Befor DB query, you may hash password variable. Something like this:

......
$pwd = do_hash($pwd);//do_hash is the hash function name 
$res = DB::select("select * from users where (username = ? or email = ?) and password = ? and active = 1",array($uname,$uname,$pwd));
        return $res;
......

i'l give you a guideline.

1. get the hashed pass from DB with respect to the username or email

2. Hash::check() to see if it matches. This function returns a boolean value. 

3. if it passes, login the user.

While registration, hash the password by using Hash::make().

Here's my take on a username or email login:

$input = Input::all();
$remember = (isset($input['remember'])) ? true : null;
$rules = array('email_or_username' => 'required', 'password' => 'required');
$validator = Validator::make($input, $rules);

if ($validator->fails())
{
    return Redirect::back()->withErrors($validator)->withInput();
}

// get model based on username_or_email, returns null if not present
$user = User::where('email', $input['email_or_username'])->orWhere('username', $input['email_or_username'])->first();

if(!$user) {
    $attempt = false;
} else {
    $attempt = Auth::attempt(array('email' => $user->email, 'password' => $input['password']),$remember);
}       

if($attempt) {
    return Redirect::intended('/')->with(array('flash_message' => 'Successfully logged into ' . Lang::get('site.general.title') . '!', 'flash_type' => 'success') ); 
}

return Redirect::back()->with(array('flash_message' => 'Invalid credentials, please try again', 'flash_type' =>'danger'))->withInput();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top