MDL-78534 Authentication: MFA refactoring and clean up

General refactoring and cleanup of MFA code, to allow for easier
addition of UX improvements.
This commit is contained in:
Matt Porritt
2023-09-14 11:49:34 +10:00
parent f140a0dff9
commit 27ca1dee46
5 changed files with 124 additions and 88 deletions
+51 -21
View File
@@ -127,32 +127,18 @@ class factor extends \core\plugininfo\base {
}
/**
* Finds active factors for current user.
* Finds active factors for a user.
* If user is not specified, current user is used.
*
* @param mixed $user user object or null.
* @return array of factor objects.
*/
public static function get_active_user_factor_types(): array {
public static function get_active_user_factor_types(mixed $user = null): array {
global $USER;
$return = [];
$factors = self::get_enabled_factors();
foreach ($factors as $factor) {
$userfactors = $factor->get_active_user_factors($USER);
if (count($userfactors) > 0) {
$return[] = $factor;
}
if (is_null($user)) {
$user = $USER;
}
return $return;
}
/**
* Finds active factors for given user.
*
* @param stdClass $user the user to get types for.
* @return array of factor objects.
*/
public static function get_active_other_user_factor_types(stdClass $user): array {
$return = [];
$factors = self::get_enabled_factors();
@@ -168,10 +154,11 @@ class factor extends \core\plugininfo\base {
/**
* Returns next factor to authenticate user.
* Only returns factors that require user input.
*
* @return mixed factor object the next factor to be authenticated or false.
*/
public static function get_next_user_factor(): object {
public static function get_next_user_login_factor(): mixed {
$factors = self::get_active_user_factor_types();
foreach ($factors as $factor) {
@@ -187,6 +174,23 @@ class factor extends \core\plugininfo\base {
return new \tool_mfa\local\factor\fallback();
}
/**
* Returns all factors that require user input.
*
* @return array of factor objects.
*/
public static function get_all_user_login_factors(): array {
$factors = self::get_active_user_factor_types();
$loginfactors = [];
foreach ($factors as $factor) {
if ($factor->has_input()) {
$loginfactors[] = $factor;
}
}
return $loginfactors;
}
/**
* Returns the list of available actions with factor.
*
@@ -336,4 +340,30 @@ class factor extends \core\plugininfo\base {
parent::uninstall_cleanup();
}
/**
* Sorts factors by state.
*
* @param array $factors The factors to sort.
* @param string $state The state to sort by.
* @return array $factors The sorted factors.
*/
public static function sort_factors_by_state(array $factors, string $state): array {
usort($factors, function ($a, $b) use ($state) {
$statea = $a->get_state();
$stateb = $b->get_state();
if ($statea === $state && $stateb !== $state) {
return -1; // A comes before B.
}
if ($stateb === $state && $statea !== $state) {
return 1; // B comes before A.
}
return 0; // They are the same, keep current order.
});
return $factors;
}
}