Laravel - 4:如何向AUTH模块添加自定义字段

时间:2014-03-03 04:50:05

标签: php laravel

$cred = array(
    'username' => $post['username'],
    'password1' => md5($post['password1']),
    'password2' => md5($post['password2']) // custom third field
);

// Check all for authentication
Auth::attempt($cred);

如何向AUTH模块添加自定义字段?

3 个答案:

答案 0 :(得分:4)

如果您希望用户与另一个凭证/ where子句匹配,则只需将其传递到凭证数组即可。例如:

<?php
$credentials = [
    'username' => Input::get('username'),
    'password' => Input::get('password'),
    'active'   => 1
];

if(Auth::attempt($credentials)) {
    // code here
}

如果您想检查确认密码,例如上述建议,您需要先检查一下,然后再检查其他内容,而不是之后。

<?php
$validate = [
    'password' => Input::get('password'),
    'password_confirmation' => Input::get('password_confirmation')
];

$validator = Validator::make(
    $validate,
    ['password' => ['same:password_confirmation']]
);

// now you make a credentials array and attempt to auth

答案 1 :(得分:0)

您必须将usernamepassword的数组发送到Auth::attempt方法

你可以填写那些你需要的东西,但在你的情况下它会是这样的:

$post = Input::all(); // I assume this is how you are filling the $post variable?
Auth::attempt(array('username' => $post['username'], 'password' => $post['password1']);

请注意,您不需要对密码进行哈希处理,尝试方法将处理该密码。您也不需要随身携带第二个密码,它将完全忽略除“用户名”和“密码”之外的所有内容

答案 2 :(得分:0)

你没有,相反,你可以尝试这样的事情:

$cred = array(
    'username' => Input::get('username'),
    'password' => Input::get('password1')
);

// At first normally check the credentials using validate method
// but doesn't login, if check succeeded then check the second
// password manually, using your encrypted password2 field
if(Auth::validate($cred)) {
    // Now check the password2, assumed you're using md5
    // hashing for this field (according to your question)
    $password2 = md5(Input::get('password2'));
    $user = User::where('username', $cred['username'])->first();
    if( $user->password2 == $password2) {
        // Now manually login the user
        Auth::login($user);
        return Redirect::to('url'); // successful login url
    }
    else{
        // Password2 missmatched
        $validator = Validator::make(array(), array())->getMessagebag();
        $validator->add('errorLogin', 'Invalid Credentials!');
        return Redirect::back()->withInput()->withError($validator);
    }
}
else {
    // Didn't pass even the first validation (username, password1)
    $validator = Validator::make(array(), array())->getMessagebag();
    $validator->add('errorLogin', 'Invalid Credentials!');
    return Redirect::back()->withInput()->withError($validator);
}

view中,您可以使用此选项在登录失败时显示错误消息:

{{ $errors->first('errorLogin') }} // Invalid Credentials!

对于第一个validate方法,不要使用任何加密,让Laravel像这样做,而对于第二个密码,你可以使用自己的加密。