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,7 +51,8 @@ class verification_field extends \MoodleQuickForm_text {
$attributes['autocomplete'] = 'one-time-code';
$attributes['inputmode'] = 'numeric';
$attributes['pattern'] = '[0-9]*';
$attributes['class'] = 'tool-mfa-verification-code';
$attributes['class'] = 'tool-mfa-verification-code font-weight-bold';
$attributes['maxlength'] = 6;
// If we aren't on the auth page, this might be part of a larger form such as for setup.
// We shouldn't autofocus here, as it probably isn't the only element, or main target.
@@ -62,11 +63,7 @@ class verification_field extends \MoodleQuickForm_text {
// If we are on the auth page, load JS for element.
$this->appendjs = false;
if ($auth) {
if ($PAGE->pagelayout === 'secure') {
$this->appendjs = true;
} else {
$PAGE->requires->js_call_amd('tool_mfa/autosubmit_verification_code', 'init', []);
}
$PAGE->requires->js_call_amd('tool_mfa/autosubmit_verification_code', 'init', []);
}
// Force element name to match JS.
+39 -37
View File
@@ -17,6 +17,7 @@
namespace tool_mfa;
use dml_exception;
use tool_mfa\plugininfo\factor;
/**
* MFA management class.
@@ -69,8 +70,8 @@ class manager {
'text-right',
'text-center',
];
$factors = \tool_mfa\plugininfo\factor::get_enabled_factors();
$userfactors = \tool_mfa\plugininfo\factor::get_active_user_factor_types();
$factors = factor::get_enabled_factors();
$userfactors = factor::get_active_user_factor_types();
$runningtotal = 0;
$weighttoggle = false;
@@ -79,13 +80,13 @@ class manager {
$name = get_string('pluginname', $namespace);
// If factor is unknown, pending from here.
if ($factor->get_state() == \tool_mfa\plugininfo\factor::STATE_UNKNOWN) {
if ($factor->get_state() == factor::STATE_UNKNOWN) {
$weighttoggle = true;
}
// Stop adding weight if 100 achieved.
if (!$weighttoggle) {
$achieved = $factor->get_state() == \tool_mfa\plugininfo\factor::STATE_PASS ? $factor->get_weight() : 0;
$achieved = $factor->get_state() == factor::STATE_PASS ? $factor->get_weight() : 0;
$achieved = '+'.$achieved;
$runningtotal += $achieved;
} else {
@@ -148,10 +149,10 @@ class manager {
*/
public static function get_total_weight(): int {
$totalweight = 0;
$factors = \tool_mfa\plugininfo\factor::get_active_user_factor_types();
$factors = factor::get_active_user_factor_types();
foreach ($factors as $factor) {
if ($factor->get_state() == \tool_mfa\plugininfo\factor::STATE_PASS) {
if ($factor->get_state() == factor::STATE_PASS) {
$totalweight += $factor->get_weight();
}
}
@@ -227,12 +228,12 @@ class manager {
global $SESSION;
// Check for any instant fail states.
$factors = \tool_mfa\plugininfo\factor::get_active_user_factor_types();
$factors = factor::get_active_user_factor_types();
foreach ($factors as $factor) {
$factor->load_locked_state();
if ($factor->get_state() == \tool_mfa\plugininfo\factor::STATE_FAIL) {
return \tool_mfa\plugininfo\factor::STATE_FAIL;
if ($factor->get_state() == factor::STATE_FAIL) {
return factor::STATE_FAIL;
}
}
@@ -240,25 +241,24 @@ class manager {
self::passed_enough_factors());
// Check next factor for instant fail (fallback).
if (\tool_mfa\plugininfo\factor::get_next_user_factor()->get_state() ==
\tool_mfa\plugininfo\factor::STATE_FAIL) {
if (factor::get_next_user_login_factor()->get_state() == factor::STATE_FAIL) {
// We need to handle a special case here, where someone reached the fallback,
// If they were able to modify their state on the error page, such as passing iprange,
// We must return pass.
if ($passcondition) {
return \tool_mfa\plugininfo\factor::STATE_PASS;
return factor::STATE_PASS;
}
return \tool_mfa\plugininfo\factor::STATE_FAIL;
return factor::STATE_FAIL;
}
// Now check for general passing state. If found, ensure that session var is set.
if ($passcondition) {
return \tool_mfa\plugininfo\factor::STATE_PASS;
return factor::STATE_PASS;
}
// Else return neutral state.
return \tool_mfa\plugininfo\factor::STATE_NEUTRAL;
return factor::STATE_NEUTRAL;
}
/**
@@ -272,7 +272,7 @@ class manager {
global $SESSION;
$state = self::get_status();
if ($state == \tool_mfa\plugininfo\factor::STATE_PASS) {
if ($state == factor::STATE_PASS) {
self::set_pass_state();
// Check if user even had to reach auth page.
if (isset($SESSION->tool_mfa_has_been_redirected)) {
@@ -287,7 +287,7 @@ class manager {
// Don't touch anything, let user be on their way.
return;
}
} else if ($state == \tool_mfa\plugininfo\factor::STATE_FAIL) {
} else if ($state == factor::STATE_FAIL) {
self::cannot_login();
} else if ($shouldreload) {
// Set a session variable to track whether user is where they want to be.
@@ -305,9 +305,9 @@ class manager {
public static function passed_enough_factors(): bool {
// Check for any instant fail states.
$factors = \tool_mfa\plugininfo\factor::get_active_user_factor_types();
$factors = factor::get_active_user_factor_types();
foreach ($factors as $factor) {
if ($factor->get_state() == \tool_mfa\plugininfo\factor::STATE_FAIL) {
if ($factor->get_state() == factor::STATE_FAIL) {
self::mfa_logout();
}
}
@@ -353,17 +353,17 @@ class manager {
// @codingStandardsIgnoreEnd
// Fire post pass state factor actions.
$factors = \tool_mfa\plugininfo\factor::get_active_user_factor_types();
$factors = factor::get_active_user_factor_types();
foreach ($factors as $factor) {
$factor->post_pass_state();
// Also set the states for this session to neutral if they were locked.
if ($factor->get_state() == \tool_mfa\plugininfo\factor::STATE_LOCKED) {
$factor->set_state(\tool_mfa\plugininfo\factor::STATE_NEUTRAL);
if ($factor->get_state() == factor::STATE_LOCKED) {
$factor->set_state(factor::STATE_NEUTRAL);
}
}
// Output notifications if any factors were reset for this user.
$enabledfactors = \tool_mfa\plugininfo\factor::get_enabled_factors();
$enabledfactors = factor::get_enabled_factors();
foreach ($enabledfactors as $factor) {
$pref = 'tool_mfa_reset_' . $factor->name;
$factorpref = get_user_preferences($pref, false);
@@ -377,7 +377,7 @@ class manager {
}
// Also check for a global reset.
// TODO: Delete this in a ferw months, the reset all preference is no longer set.
// TODO: Delete this in a few months, the reset all preference is no longer set.
$allfactor = get_user_preferences('tool_mfa_reset_all', false);
if ($allfactor) {
$url = new \moodle_url('/admin/tool/mfa/user_preferences.php');
@@ -563,7 +563,7 @@ class manager {
* @return array
*/
public static function get_no_redirect_urls(): array {
$factors = \tool_mfa\plugininfo\factor::get_factors();
$factors = factor::get_factors();
$urls = [
new \moodle_url('/login/logout.php'),
new \moodle_url('/admin/tool/mfa/guide.php'),
@@ -723,7 +723,7 @@ class manager {
return false;
}
$enabledfactors = \tool_mfa\plugininfo\factor::get_enabled_factors();
$enabledfactors = factor::get_enabled_factors();
if (count($enabledfactors) == 0) {
return false;
}
@@ -791,13 +791,13 @@ class manager {
global $USER;
// Get all active factors.
$factors = \tool_mfa\plugininfo\factor::get_enabled_factors();
$factors = factor::get_enabled_factors();
// Check if there are enough factors that a user can ONLY pass, if so, don't display the menu.
$weight = 0;
foreach ($factors as $factor) {
$states = $factor->possible_states($USER);
if (count($states) == 1 && reset($states) == \tool_mfa\plugininfo\factor::STATE_PASS) {
if (count($states) == 1 && reset($states) == factor::STATE_PASS) {
$weight += $factor->get_weight();
if ($weight >= 100) {
return false;
@@ -808,7 +808,7 @@ class manager {
// Now if there is a factor that can be setup, that may return a pass state for the user, display menu.
foreach ($factors as $factor) {
if ($factor->has_setup()) {
if (in_array(\tool_mfa\plugininfo\factor::STATE_PASS, $factor->possible_states($USER))) {
if (in_array(factor::STATE_PASS, $factor->possible_states($USER))) {
return true;
}
}
@@ -820,19 +820,21 @@ class manager {
/**
* Gets current user weight, up until first unknown factor.
*
* @return int
* @return int $totalweight Total weight of all factors.
*/
public static function get_cumulative_weight(): int {
$factors = \tool_mfa\plugininfo\factor::get_active_user_factor_types();
$factors = factor::get_active_user_factor_types();
// Factor order is important here, so sort the factors by state.
$sortedfactors = factor::sort_factors_by_state($factors, factor::STATE_PASS);
$totalweight = 0;
foreach ($factors as $factor) {
if ($factor->get_state() == \tool_mfa\plugininfo\factor::STATE_PASS) {
foreach ($sortedfactors as $factor) {
if ($factor->get_state() == factor::STATE_PASS) {
$totalweight += $factor->get_weight();
// If over 100, break. Dont care about >100.
// If over 100, break. Don't care about >100.
if ($totalweight >= 100) {
break;
}
} else if ($factor->get_state() == \tool_mfa\plugininfo\factor::STATE_UNKNOWN) {
} else if ($factor->get_state() == factor::STATE_UNKNOWN) {
break;
}
}
@@ -846,7 +848,7 @@ class manager {
* @return bool true if factor is pending.
*/
public static function check_factor_pending(string $factorname): bool {
$factors = \tool_mfa\plugininfo\factor::get_active_user_factor_types();
$factors = factor::get_active_user_factor_types();
// Setup vars.
$pending = [];
$totalweight = 0;
@@ -859,7 +861,7 @@ class manager {
continue;
}
if ($factor->get_state() == \tool_mfa\plugininfo\factor::STATE_PASS) {
if ($factor->get_state() == factor::STATE_PASS) {
$totalweight += $factor->get_weight();
if ($totalweight >= 100) {
$weighttoggle = true;
+559
View File
@@ -0,0 +1,559 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace tool_mfa\output;
use tool_mfa\local\factor\object_factor;
use tool_mfa\local\form\login_form;
use \html_writer;
use tool_mfa\plugininfo\factor;
/**
* MFA renderer.
*
* @package tool_mfa
* @author Mikhail Golenkov <[email protected]>
* @copyright Catalyst IT
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends \plugin_renderer_base {
/**
* Returns the state of the factor as a badge.
*
* @param string $state
* @return string
*/
public function get_state_badge(string $state): string {
switch ($state) {
case factor::STATE_PASS:
return html_writer::tag('span', get_string('state:pass', 'tool_mfa'), ['class' => 'badge badge-success']);
case factor::STATE_FAIL:
return html_writer::tag('span', get_string('state:fail', 'tool_mfa'), ['class' => 'badge badge-danger']);
case factor::STATE_NEUTRAL:
return html_writer::tag('span', get_string('state:neutral', 'tool_mfa'), ['class' => 'badge badge-warning']);
case factor::STATE_UNKNOWN:
return html_writer::tag('span', get_string('state:unknown', 'tool_mfa'),
['class' => 'badge badge-secondary']);
case factor::STATE_LOCKED:
return html_writer::tag('span', get_string('state:locked', 'tool_mfa'), ['class' => 'badge badge-error']);
default:
return html_writer::tag('span', get_string('pending', 'tool_mfa'), ['class' => 'badge badge-secondary']);
}
}
/**
* Returns a list of factors which a user can add.
*
* @return string
*/
public function available_factors(): string {
$html = $this->output->heading(get_string('preferences:availablefactors', 'tool_mfa'), 2);
$factors = factor::get_enabled_factors();
foreach ($factors as $factor) {
// TODO is_configured / is_ready.
if (!$factor->has_setup() || !$factor->show_setup_buttons()) {
continue;
}
$html .= $this->setup_factor($factor);
}
return $html;
}
/**
* Returns the html section for factor setup
*
* @param object $factor object of the factor class
* @return string
*/
public function setup_factor(object $factor): string {
$html = '';
$html .= html_writer::start_tag('div', ['class' => 'card']);
$html .= html_writer::tag('h4', $factor->get_display_name(), ['class' => 'card-header']);
$html .= html_writer::start_tag('div', ['class' => 'card-body']);
$html .= $factor->get_info();
$setupparams = ['action' => 'setup', 'factor' => $factor->name, 'sesskey' => sesskey()];
$setupurl = new \moodle_url('action.php', $setupparams);
$html .= $this->output->single_button($setupurl, $factor->get_setup_string());
$html .= html_writer::end_tag('div');
$html .= html_writer::end_tag('div');
$html .= '<br>';
return $html;
}
/**
* Defines section with active user's factors.
*
* @return string $html
* @throws \coding_exception
*/
public function active_factors(): string {
global $USER, $CFG;
require_once($CFG->dirroot . '/iplookup/lib.php');
$html = $this->output->heading(get_string('preferences:activefactors', 'tool_mfa'), 2);
$headers = get_strings([
'factor',
'devicename',
'created',
'createdfromip',
'lastverified',
'revoke',
], 'tool_mfa');
$table = new \html_table();
$table->id = 'active_factors';
$table->attributes['class'] = 'generaltable table table-bordered';
$table->head = [
$headers->factor,
$headers->devicename,
$headers->created,
$headers->createdfromip,
$headers->lastverified,
$headers->revoke,
];
$table->colclasses = [
'leftalign',
'leftalign',
'centeralign',
'centeralign',
'centeralign',
'centeralign',
'centeralign',
'centeralign',
];
$table->data = [];
$factors = factor::get_enabled_factors();
foreach ($factors as $factor) {
$userfactors = $factor->get_active_user_factors($USER);
if (!$factor->has_setup()) {
continue;
}
foreach ($userfactors as $userfactor) {
if ($factor->has_revoke()) {
$revokeparams = [
'action' => 'revoke', 'factor' => $factor->name,
'factorid' => $userfactor->id, 'sesskey' => sesskey(),
];
$revokeurl = new \moodle_url('action.php', $revokeparams);
$revokelink = \html_writer::link($revokeurl, $headers->revoke);
} else {
$revokelink = '';
}
$timecreated = $userfactor->timecreated == '-' ? '-'
: userdate($userfactor->timecreated, get_string('strftimedatetime'));
$lastverified = $userfactor->lastverified;
if ($lastverified == 0) {
$lastverified = '-';
} else if ($lastverified != '-') {
$lastverified = userdate($userfactor->lastverified, get_string('strftimedatetime'));
$lastverified .= '<br>';
$lastverified .= get_string('ago', 'core_message', format_time(time() - $userfactor->lastverified));
}
$info = iplookup_find_location($userfactor->createdfromip);
$ip = $userfactor->createdfromip;
$ip .= '<br>' . $info['country'] . ' - ' . $info['city'];
$row = new \html_table_row([
$factor->get_display_name(),
$userfactor->label,
$timecreated,
$ip,
$lastverified,
$revokelink,
]);
$table->data[] = $row;
}
}
// If table has no data, don't output.
if (count($table->data) == 0) {
return '';
}
$html .= \html_writer::table($table);
$html .= '<br>';
return $html;
}
/**
* Generates notification text for display when user cannot login.
*
* @return string $notification
*/
public function not_enough_factors(): string {
global $CFG, $SITE;
$notification = \html_writer::tag('h4', get_string('error:notenoughfactors', 'tool_mfa'));
$notification .= \html_writer::tag('p', get_string('error:reauth', 'tool_mfa'));
// Support link.
$supportemail = $CFG->supportemail;
if (!empty($supportemail)) {
$subject = get_string('email:subject', 'tool_mfa', $SITE->fullname);
$maillink = \html_writer::link("mailto:$supportemail?Subject=$subject", $supportemail);
$notification .= get_string('error:support', 'tool_mfa');
$notification .= \html_writer::tag('p', $maillink);
}
// Support page link.
$supportpage = $CFG->supportpage;
if (!empty($supportpage)) {
$linktext = \html_writer::link($supportpage, $supportpage);
$notification .= $linktext;
}
$return = $this->output->notification($notification, 'notifyerror');
// Logout button.
$url = new \moodle_url('/admin/tool/mfa/auth.php', ['logout' => 1]);
$btn = new \single_button($url, get_string('logout'), 'post', true);
$return .= $this->render($btn);
$return .= $this->guide_link();
return $return;
}
/**
* Displays a table of all factors in use currently.
*
* @param int $lookback the period to view.
* @return string the HTML for the table
*/
public function factors_in_use_table(int $lookback): string {
global $DB;
$factors = factor::get_factors();
// Setup 2 arrays, one with internal names, one pretty.
$columns = [''];
$displaynames = $columns;
$colclasses = ['center', 'center', 'center', 'center', 'center'];
// Force the first 4 columns to custom data.
$displaynames[] = get_string('totalusers', 'tool_mfa');
$displaynames[] = get_string('usersauthedinperiod', 'tool_mfa');
$displaynames[] = get_string('nonauthusers', 'tool_mfa');
$displaynames[] = get_string('nologinusers', 'tool_mfa');
foreach ($factors as $factor) {
$columns[] = $factor->name;
$displaynames[] = get_string('pluginname', 'factor_'.$factor->name);
$colclasses[] = 'right';
}
// Add total column to the end.
$displaynames[] = get_string('total');
$colclasses[] = 'center';
$table = new \html_table();
$table->head = $displaynames;
$table->align = $colclasses;
$table->attributes['class'] = 'generaltable table table-bordered w-auto';
$table->attributes['style'] = 'width: auto; min-width: 50%; margin-bottom: 0;';
// Manually handle Total users and MFA users.
$alluserssql = "SELECT auth,
COUNT(id)
FROM {user}
WHERE deleted = 0
AND suspended = 0
GROUP BY auth";
$allusersinfo = $DB->get_records_sql($alluserssql, []);
$noncompletesql = "SELECT u.auth, COUNT(u.id)
FROM {user} u
LEFT JOIN {tool_mfa_auth} mfaa ON u.id = mfaa.userid
WHERE u.lastlogin >= ?
AND (mfaa.lastverified < ?
OR mfaa.lastverified IS NULL)
GROUP BY u.auth";
$noncompleteinfo = $DB->get_records_sql($noncompletesql, [$lookback, $lookback]);
$nologinsql = "SELECT auth, COUNT(id)
FROM {user}
WHERE deleted = 0
AND suspended = 0
AND lastlogin < ?
GROUP BY auth";
$nologininfo = $DB->get_records_sql($nologinsql, [$lookback]);
$mfauserssql = "SELECT auth,
COUNT(DISTINCT tm.userid)
FROM {tool_mfa} tm
JOIN {user} u ON u.id = tm.userid
WHERE tm.lastverified >= ?
AND u.deleted = 0
AND u.suspended = 0
GROUP BY u.auth";
$mfausersinfo = $DB->get_records_sql($mfauserssql, [$lookback]);
$factorsusedsql = "SELECT CONCAT(u.auth, '_', tm.factor) as id,
COUNT(*)
FROM {tool_mfa} tm
JOIN {user} u ON u.id = tm.userid
WHERE tm.lastverified >= ?
AND u.deleted = 0
AND u.suspended = 0
AND (tm.revoked = 0 OR (tm.revoked = 1 AND tm.timemodified > ?))
GROUP BY CONCAT(u.auth, '_', tm.factor)";
$factorsusedinfo = $DB->get_records_sql($factorsusedsql, [$lookback, $lookback]);
// Auth rows.
$authtypes = get_enabled_auth_plugins(true);
$row = [];
foreach ($authtypes as $authtype) {
$row[] = \html_writer::tag('b', $authtype);
// Setup the overall totals columns.
$row[] = $allusersinfo[$authtype]->count ?? '-';
$row[] = $mfausersinfo[$authtype]->count ?? '-';
$row[] = $noncompleteinfo[$authtype]->count ?? '-';
$row[] = $nologininfo[$authtype]->count ?? '-';
// Create a running counter for the total.
$authtotal = 0;
// Now for each factor add the count from the factor query, and increment the running total.
foreach ($columns as $column) {
if (!empty($column)) {
// Get the information from the data key.
$key = $authtype . '_' . $column;
$count = $factorsusedinfo[$key]->count ?? 0;
$authtotal += $count;
$row[] = $count ? format_float($count, 0) : '-';
}
}
// Append the total of all factors to final column.
$row[] = $authtotal ? format_float($authtotal, 0) : '-';
$table->data[] = $row;
}
// Total row.
$totals = [0 => html_writer::tag('b', get_string('total'))];
for ($colcounter = 1; $colcounter < count($row); $colcounter++) {
$column = array_column($table->data, $colcounter);
// Transform string to int forcibly, remove -.
$column = array_map(function ($element) {
return $element === '-' ? 0 : (int) $element;
}, $column);
$columnsum = array_sum($column);
$colvalue = $columnsum === 0 ? '-' : $columnsum;
$totals[$colcounter] = $colvalue;
}
$table->data[] = $totals;
// Wrap in a div to cleanly scroll.
return \html_writer::div(\html_writer::table($table), '', ['style' => 'overflow:auto;']);
}
/**
* Displays a table of all factors in use currently.
*
* @return string the HTML for the table
*/
public function factors_locked_table(): string {
global $DB;
$factors = factor::get_factors();
$table = new \html_table();
$table->attributes['class'] = 'generaltable table table-bordered w-auto';
$table->attributes['style'] = 'width: auto; min-width: 50%';
$table->head = [
'factor' => get_string('factor', 'tool_mfa'),
'active' => get_string('active'),
'locked' => get_string('state:locked', 'tool_mfa'),
'actions' => get_string('actions'),
];
$table->align = [
'left',
'left',
'right',
'right',
];
$table->data = [];
$locklevel = (int) get_config('tool_mfa', 'lockout');
foreach ($factors as $factor) {
$sql = "SELECT COUNT(DISTINCT(userid))
FROM {tool_mfa}
WHERE factor = ?
AND lockcounter >= ?
AND revoked = 0";
$lockedusers = $DB->count_records_sql($sql, [$factor->name, $locklevel]);
$enabled = $factor->is_enabled() ? \html_writer::tag('b', get_string('yes')) : get_string('no');
$actions = \html_writer::link( new moodle_url($this->page->url,
['reset' => $factor->name, 'sesskey' => sesskey()]), get_string('performbulk', 'tool_mfa'));
$lockedusers = \html_writer::link(new moodle_url($this->page->url, ['view' => $factor->name]), $lockedusers);
$table->data[] = [
$factor->get_display_name(),
$enabled,
$lockedusers,
$actions,
];
}
return \html_writer::table($table);
}
/**
* Displays a table of all users with a locked instance of the given factor.
*
* @param object $factor the factor class
* @return string the HTML for the table
*/
public function factor_locked_users_table(object $factor): string {
global $DB;
$table = new html_table();
$table->attributes['class'] = 'generaltable table table-bordered w-auto';
$table->attributes['style'] = 'width: auto; min-width: 50%';
$table->head = [
'userid' => get_string('userid', 'grades'),
'fullname' => get_string('fullname'),
'factorip' => get_string('ipatcreation', 'tool_mfa'),
'lastip' => get_string('lastip'),
'modified' => get_string('modified'),
'actions' => get_string('actions'),
];
$table->align = [
'left',
'left',
'left',
'left',
'left',
'right',
];
$table->data = [];
$locklevel = (int) get_config('tool_mfa', 'lockout');
$sql = "SELECT mfa.id as mfaid, u.*, mfa.createdfromip, mfa.timemodified
FROM {tool_mfa} mfa
JOIN {user} u ON mfa.userid = u.id
WHERE factor = ?
AND lockcounter >= ?
AND revoked = 0";
$records = $DB->get_records_sql($sql, [$factor->name, $locklevel]);
foreach ($records as $record) {
// Construct profile link.
$proflink = \html_writer::link(new moodle_url('/user/profile.php',
['id' => $record->id]), fullname($record));
// IP link.
$creatediplink = \html_writer::link(new moodle_url('/iplookup/index.php',
['ip' => $record->createdfromip]), $record->createdfromip);
$lastiplink = \html_writer::link(new moodle_url('/iplookup/index.php',
['ip' => $record->lastip]), $record->lastip);
// Deep link to logs.
$logicon = $this->pix_icon('i/report', get_string('userlogs', 'tool_mfa'));
$actions = \html_writer::link(new moodle_url('/report/log/index.php', [
'id' => 1, // Site.
'user' => $record->id,
]), $logicon);
$action = new confirm_action(get_string('resetfactorconfirm', 'tool_mfa', fullname($record)));
$actions .= $this->action_link(
new moodle_url($this->page->url, ['reset' => $factor->name, 'id' => $record->id, 'sesskey' => sesskey()]),
$this->pix_icon('t/delete', get_string('resetconfirm', 'tool_mfa')),
$action
);
$table->data[] = [
$record->id,
$proflink,
$creatediplink,
$lastiplink,
userdate($record->timemodified, get_string('strftimedatetime', 'langconfig')),
$actions,
];
}
return \html_writer::table($table);
}
/**
* Returns a html section render of the guide link template
*
* @return string
*/
public function guide_link(): string {
if (!get_config('tool_mfa', 'guidance')) {
return '';
}
$html = $this->heading(get_string('needhelp', 'tool_mfa'), 3);
$html .= $this->render_from_template('tool_mfa/guide_link', []);
return $this->notification($html, 'info');
}
/**
* Renders an mform element from a template
*
* In certain situations, includes a script element which adds autosubmission behaviour.
*
* @param \HTML_QuickForm_element $element element
* @param bool $required if input is required field
* @param bool $advanced if input is an advanced field
* @param string|null $error error message to display
* @param bool $ingroup True if this element is rendered as part of a group
* @return mixed string|bool
*/
public function mform_element(HTML_QuickForm_element $element, bool $required,
bool $advanced, string|null $error, bool $ingroup): string|bool {
$script = null;
if ($element instanceof tool_mfa\local\form\verification_field) {
if ($this->page->pagelayout === 'secure') {
$script = $element->secure_js();
}
}
$result = parent::mform_element($element, $required, $advanced, $error, $ingroup);
if (!empty($script) && $result !== false) {
$result .= $script;
}
return $result;
}
}
+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;
}
}