确定是否在Laravel Fortify中使用了恢复代码



是否可以确定Laravel Fortify中是否已经使用了恢复代码?

据我所知,没有什么是开箱即用的,但是,您可以自己实现一些东西。

基本工作流程可能如下所示:

try {
// grab the codes for the currently authenticated user
$codes = json_decode(decrypt(auth()->user()->two_factor_recovery_codes), true);
// if the provided code exists in the array of codes stored in the DB for the authenticated user
if (in_array($code, $codes)) {
// remove the associated code and reindex the array
$codes = array_values(array_diff($codes, [$code]));
// optionally add a new recovery code
array_push($codes, LaravelFortifyRecoveryCode::generate());
// save the recovery codes back to the database
auth()->user()->two_factor_recovery_codes = 
encrypt(json_encode(array_values($codes)));
auth()->user()->save();
}
} catch (DecryptException $e) {
echo $e->getMessage();
} catch (EncryptException $e) {
echo $e->getMessage();
}

默认情况下,无论何时使用恢复代码,都会删除单个恢复代码并用新代码替换:

强化/TwoFactorAuthenticatedSessionController控制器:

public function store(TwoFactorLoginRequest $request)
{
$user = $request->challengedUser();
if ($code = $request->validRecoveryCode()) {
$user->replaceRecoveryCode($code);
event(new RecoveryCodeReplaced($user, $code));
}
//...
}

强化/src/TwoFactorAuthenticatable特征:

/**
* Replace the given recovery code with a new one in the user's stored codes.
*
* @param  string  $code
* @return void
*/
public function replaceRecoveryCode($code)
{
$this->forceFill([
'two_factor_recovery_codes' => encrypt(str_replace(
$code,
RecoveryCode::generate(),
decrypt($this->two_factor_recovery_codes)
)),
])->save();
}

回顾过去,这是自第一版以来的行为

因此,没有任何方法可以满足您的需要,但可以放心地假设用户以前没有使用过所有可用的恢复代码。如果您确实想记录恢复代码的使用情况,那么有一个事件您可以从Fortify收听RecoveryCodeReplaced>1.8

最新更新