xiaowang/kirby/src/Cms/Auth/Challenge.php

64 lines
1.9 KiB
PHP
Raw Normal View History

2021-10-29 18:05:46 +02:00
<?php
namespace Kirby\Cms\Auth;
use Kirby\Cms\User;
/**
* Template class for authentication challenges
* that create and verify one-time auth codes
*
* @package Kirby Cms
* @author Lukas Bestle <lukas@getkirby.com>
* @link https://getkirby.com
2022-03-22 15:39:39 +01:00
* @copyright Bastian Allgeier
2021-10-29 18:05:46 +02:00
* @license https://getkirby.com/license
*/
abstract class Challenge
{
2022-08-31 16:08:03 +02:00
/**
* Checks whether the challenge is available
* for the passed user and purpose
*
* @param \Kirby\Cms\User $user User the code will be generated for
* @param string $mode Purpose of the code ('login', 'reset' or '2fa')
* @return bool
*/
abstract public static function isAvailable(User $user, string $mode): bool;
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
/**
* Generates a random one-time auth code and returns that code
* for later verification
*
* @param \Kirby\Cms\User $user User to generate the code for
* @param array $options Details of the challenge request:
* - 'mode': Purpose of the code ('login', 'reset' or '2fa')
* - 'timeout': Number of seconds the code will be valid for
* @return string|null The generated and sent code or `null` in case
* there was no code to generate by this algorithm
*/
2022-12-19 16:26:24 +01:00
abstract public static function create(User $user, array $options): string|null;
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
/**
* Verifies the provided code against the created one;
* default implementation that checks the code that was
* returned from the `create()` method
*
* @param \Kirby\Cms\User $user User to check the code for
* @param string $code Code to verify
* @return bool
*/
public static function verify(User $user, string $code): bool
{
$hash = $user->kirby()->session()->get('kirby.challenge.code');
if (is_string($hash) !== true) {
return false;
}
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
// normalize the formatting in the user-provided code
$code = str_replace(' ', '', $code);
2021-10-29 18:05:46 +02:00
2022-08-31 16:08:03 +02:00
return password_verify($code, $hash);
}
2021-10-29 18:05:46 +02:00
}