Skip to content

Commit

Permalink
bugfix: handle IP lookup errors in user preferences
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewhilton committed Aug 22, 2023
1 parent cffe4ef commit f930d97
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
2 changes: 2 additions & 0 deletions lang/en/tool_mfa.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@
$string['guidance'] = 'MFA user guide';
$string['inputrequired'] = 'User input';
$string['ipatcreation'] = 'IP address when factor created';
$string['ip:geoinfo:unknown'] = '{$a} - Location unknown';
$string['ip:geoinfo'] = '{$a->ip} - {$a->city}, {$a->country}';
$string['lastverified'] = 'Last verified';
$string['lockedusersforallfactors'] = 'Locked users: All factors';
$string['lockedusersforfactor'] = 'Locked users: {$a}';
Expand Down
35 changes: 33 additions & 2 deletions renderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,8 @@ public function active_factors() {
$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'];
$ip = $this->append_location_to_ip($ip);

$row = new \html_table_row([
$factor->get_display_name(),
Expand All @@ -201,6 +200,38 @@ public function active_factors() {
return $html;
}

/**
* Finds the location for the given IP address, handling errors.
*
* Appends location info to the end of the IP address.
*
* @param string $ip
* @return string String with the IP with location details appended to it, or Unknown location if could not be determined.
*/
private function append_location_to_ip($ip): string {
try {
$geoinfo = iplookup_find_location($ip);
$city = $geoinfo['city'] ?: '';
$country = $geoinfo['country'] ?: '';

// It's possible for errors to be returned, or the geo lookup to simply be empty.
// In these cases, we want to return the 'unknown' string.
$iserror = !empty($geoinfo['error']);
$islookupempty = empty($city) || empty($country);

if ($iserror || $islookupempty) {
return get_string('ip:geoinfo:unknown', 'tool_mfa', $ip);
}

// Location info was found - return details.
return get_string('ip:geoinfo', 'tool_mfa', ['ip' => $ip, 'city' => $city, 'country' => $country]);

} catch (Throwable $e) {
// Some exception was thrown, so we cannot work out the location.
return get_string('ip:geoinfo:unknown', 'tool_mfa', $ip);
}
}

/**
* Generates notification text for display when user cannot login.
*
Expand Down

0 comments on commit f930d97

Please sign in to comment.