mirror of
https://github.com/friendica/friendica
synced 2025-04-27 16:30:10 +00:00
Merge pull request #7135 from MrPetovan/task/two-factor-authentication
Add native two-factor authentication support
This commit is contained in:
commit
5e85bdecd0
29 changed files with 1497 additions and 211 deletions
|
@ -47,6 +47,10 @@ class Router
|
|||
$collector->addRoute(['GET'], '/webfinger' , Module\Xrd::class);
|
||||
$collector->addRoute(['GET'], '/x-social-relay' , Module\WellKnown\XSocialRelay::class);
|
||||
});
|
||||
$this->routeCollector->addGroup('/2fa', function (RouteCollector $collector) {
|
||||
$collector->addRoute(['GET', 'POST'], '[/]' , Module\TwoFactor\Verify::class);
|
||||
$collector->addRoute(['GET', 'POST'], '/recovery' , Module\TwoFactor\Recovery::class);
|
||||
});
|
||||
$this->routeCollector->addGroup('/admin', function (RouteCollector $collector) {
|
||||
$collector->addRoute(['GET'] , '[/]' , Module\Admin\Summary::class);
|
||||
|
||||
|
@ -184,6 +188,14 @@ class Router
|
|||
$collector->addRoute(['GET'], '/{sub1}/{url}' , Module\Proxy::class);
|
||||
$collector->addRoute(['GET'], '/{sub1}/{sub2}/{url}' , Module\Proxy::class);
|
||||
});
|
||||
|
||||
$this->routeCollector->addGroup('/settings', function (RouteCollector $collector) {
|
||||
$collector->addGroup('/2fa', function (RouteCollector $collector) {
|
||||
$collector->addRoute(['GET', 'POST'], '[/]' , Module\Settings\TwoFactor\Index::class);
|
||||
$collector->addRoute(['GET', 'POST'], '/recovery' , Module\Settings\TwoFactor\Recovery::class);
|
||||
$collector->addRoute(['GET', 'POST'], '/verify' , Module\Settings\TwoFactor\Verify::class);
|
||||
});
|
||||
});
|
||||
$this->routeCollector->addRoute(['GET', 'POST'], '/register', Module\Register::class);
|
||||
$this->routeCollector->addRoute(['GET'], '/robots.txt', Module\RobotsTxt::class);
|
||||
$this->routeCollector->addRoute(['GET'], '/rsd.xml', Module\ReallySimpleDiscovery::class);
|
||||
|
|
|
@ -5,11 +5,9 @@
|
|||
|
||||
namespace Friendica\Core;
|
||||
|
||||
use Friendica\App;
|
||||
use Friendica\BaseObject;
|
||||
use Friendica\Database\DBA;
|
||||
use Friendica\Model\User;
|
||||
use Friendica\Util\BaseURL;
|
||||
use Friendica\Util\DateTimeFormat;
|
||||
|
||||
/**
|
||||
* Handle Authentification, Session and Cookies
|
||||
|
@ -55,112 +53,6 @@ class Authentication extends BaseObject
|
|||
setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == BaseUrl::SSL_POLICY_FULL), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the provided user's authenticated session
|
||||
*
|
||||
* @todo Should be moved to Friendica\Core\Session once it's created
|
||||
*
|
||||
* @param array $user_record
|
||||
* @param bool $login_initial
|
||||
* @param bool $interactive
|
||||
* @param bool $login_refresh
|
||||
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
|
||||
*/
|
||||
public static function setAuthenticatedSessionForUser($user_record, $login_initial = false, $interactive = false, $login_refresh = false)
|
||||
{
|
||||
$a = self::getApp();
|
||||
|
||||
$_SESSION['uid'] = $user_record['uid'];
|
||||
$_SESSION['theme'] = $user_record['theme'];
|
||||
$_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
|
||||
$_SESSION['authenticated'] = 1;
|
||||
$_SESSION['page_flags'] = $user_record['page-flags'];
|
||||
$_SESSION['my_url'] = $a->getbaseUrl() . '/profile/' . $user_record['nickname'];
|
||||
$_SESSION['my_address'] = $user_record['nickname'] . '@' . substr($a->getbaseUrl(), strpos($a->getbaseUrl(), '://') + 3);
|
||||
$_SESSION['addr'] = defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0');
|
||||
|
||||
$a->user = $user_record;
|
||||
|
||||
if ($interactive) {
|
||||
if ($a->user['login_date'] <= DBA::NULL_DATETIME) {
|
||||
$_SESSION['return_path'] = 'profile_photo/new';
|
||||
$a->module = 'profile_photo';
|
||||
info(L10n::t("Welcome ") . $a->user['username'] . EOL);
|
||||
info(L10n::t('Please upload a profile photo.') . EOL);
|
||||
} else {
|
||||
info(L10n::t("Welcome back ") . $a->user['username'] . EOL);
|
||||
}
|
||||
}
|
||||
|
||||
$member_since = strtotime($a->user['register_date']);
|
||||
if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
|
||||
$_SESSION['new_member'] = true;
|
||||
} else {
|
||||
$_SESSION['new_member'] = false;
|
||||
}
|
||||
if (strlen($a->user['timezone'])) {
|
||||
date_default_timezone_set($a->user['timezone']);
|
||||
$a->timezone = $a->user['timezone'];
|
||||
}
|
||||
|
||||
$masterUid = $user_record['uid'];
|
||||
|
||||
if (!empty($_SESSION['submanage'])) {
|
||||
$user = DBA::selectFirst('user', ['uid'], ['uid' => $_SESSION['submanage']]);
|
||||
if (DBA::isResult($user)) {
|
||||
$masterUid = $user['uid'];
|
||||
}
|
||||
}
|
||||
|
||||
$a->identities = User::identities($masterUid);
|
||||
|
||||
if ($login_initial) {
|
||||
Logger::log('auth_identities: ' . print_r($a->identities, true), Logger::DEBUG);
|
||||
}
|
||||
if ($login_refresh) {
|
||||
Logger::log('auth_identities refresh: ' . print_r($a->identities, true), Logger::DEBUG);
|
||||
}
|
||||
|
||||
$contact = DBA::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => true]);
|
||||
if (DBA::isResult($contact)) {
|
||||
$a->contact = $contact;
|
||||
$a->cid = $contact['id'];
|
||||
$_SESSION['cid'] = $a->cid;
|
||||
}
|
||||
|
||||
header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
|
||||
|
||||
if ($login_initial || $login_refresh) {
|
||||
DBA::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
|
||||
|
||||
// Set the login date for all identities of the user
|
||||
DBA::update('user', ['login_date' => DateTimeFormat::utcNow()],
|
||||
['parent-uid' => $masterUid, 'account_removed' => false]);
|
||||
}
|
||||
|
||||
if ($login_initial) {
|
||||
/*
|
||||
* If the user specified to remember the authentication, then set a cookie
|
||||
* that expires after one week (the default is when the browser is closed).
|
||||
* The cookie will be renewed automatically.
|
||||
* The week ensures that sessions will expire after some inactivity.
|
||||
*/
|
||||
if (!empty($_SESSION['remember'])) {
|
||||
Logger::log('Injecting cookie for remembered user ' . $a->user['nickname']);
|
||||
self::setCookie(604800, $user_record);
|
||||
unset($_SESSION['remember']);
|
||||
}
|
||||
}
|
||||
|
||||
if ($login_initial) {
|
||||
Hook::callAll('logged_in', $a->user);
|
||||
|
||||
if (($a->module !== 'home') && isset($_SESSION['return_path'])) {
|
||||
$a->internalRedirect($_SESSION['return_path']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Kills the "Friendica" cookie and all session data
|
||||
*/
|
||||
|
@ -170,5 +62,26 @@ class Authentication extends BaseObject
|
|||
session_unset();
|
||||
session_destroy();
|
||||
}
|
||||
|
||||
public static function twoFactorCheck($uid, App $a)
|
||||
{
|
||||
// Check user setting, if 2FA disabled return
|
||||
if (!PConfig::get($uid, '2fa', 'verified')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check current path, if 2fa authentication module return
|
||||
if ($a->argc > 0 && in_array($a->argv[0], ['ping', '2fa', 'view', 'help', 'logout'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 1: 2FA session present and valid: return
|
||||
if (Session::get('2fa')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 2: No valid 2FA session: redirect to code verification page
|
||||
$a->internalRedirect('2fa');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -5,9 +5,14 @@
|
|||
*/
|
||||
namespace Friendica\Core;
|
||||
|
||||
use Friendica\App;
|
||||
use Friendica\Core\Session\CacheSessionHandler;
|
||||
use Friendica\Core\Session\DatabaseSessionHandler;
|
||||
use Friendica\Database\DBA;
|
||||
use Friendica\Model\Contact;
|
||||
use Friendica\Model\User;
|
||||
use Friendica\Util\BaseURL;
|
||||
use Friendica\Util\DateTimeFormat;
|
||||
|
||||
/**
|
||||
* High-level Session service class
|
||||
|
@ -25,7 +30,7 @@ class Session
|
|||
ini_set('session.use_only_cookies', 1);
|
||||
ini_set('session.cookie_httponly', 1);
|
||||
|
||||
if (Config::get('system', 'ssl_policy') == BaseUrl::SSL_POLICY_FULL) {
|
||||
if (Config::get('system', 'ssl_policy') == BaseURL::SSL_POLICY_FULL) {
|
||||
ini_set('session.cookie_secure', 1);
|
||||
}
|
||||
|
||||
|
@ -66,8 +71,142 @@ class Session
|
|||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a single session variable.
|
||||
* Overrides value of existing key.
|
||||
*
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
*/
|
||||
public static function set($name, $value)
|
||||
{
|
||||
$_SESSION[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets multiple session variables.
|
||||
* Overrides values for existing keys.
|
||||
*
|
||||
* @param array $values
|
||||
*/
|
||||
public static function setMultiple(array $values)
|
||||
{
|
||||
$_SESSION = $values + $_SESSION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a session variable.
|
||||
* Ignores missing keys.
|
||||
*
|
||||
* @param $name
|
||||
*/
|
||||
public static function remove($name)
|
||||
{
|
||||
unset($_SESSION[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the provided user's authenticated session
|
||||
*
|
||||
* @param App $a
|
||||
* @param array $user_record
|
||||
* @param bool $login_initial
|
||||
* @param bool $interactive
|
||||
* @param bool $login_refresh
|
||||
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
|
||||
*/
|
||||
public static function setAuthenticatedForUser(App $a, array $user_record, $login_initial = false, $interactive = false, $login_refresh = false)
|
||||
{
|
||||
self::setMultiple([
|
||||
'uid' => $user_record['uid'],
|
||||
'theme' => $user_record['theme'],
|
||||
'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
|
||||
'authenticated' => 1,
|
||||
'page_flags' => $user_record['page-flags'],
|
||||
'my_url' => $a->getBaseURL() . '/profile/' . $user_record['nickname'],
|
||||
'my_address' => $user_record['nickname'] . '@' . substr($a->getBaseURL(), strpos($a->getBaseURL(), '://') + 3),
|
||||
'addr' => defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0'),
|
||||
]);
|
||||
|
||||
$member_since = strtotime($user_record['register_date']);
|
||||
self::set('new_member', time() < ($member_since + ( 60 * 60 * 24 * 14)));
|
||||
|
||||
if (strlen($user_record['timezone'])) {
|
||||
date_default_timezone_set($user_record['timezone']);
|
||||
$a->timezone = $user_record['timezone'];
|
||||
}
|
||||
|
||||
$masterUid = $user_record['uid'];
|
||||
|
||||
if (self::get('submanage')) {
|
||||
$user = DBA::selectFirst('user', ['uid'], ['uid' => self::get('submanage')]);
|
||||
if (DBA::isResult($user)) {
|
||||
$masterUid = $user['uid'];
|
||||
}
|
||||
}
|
||||
|
||||
$a->identities = User::identities($masterUid);
|
||||
|
||||
if ($login_initial) {
|
||||
$a->getLogger()->info('auth_identities: ' . print_r($a->identities, true));
|
||||
}
|
||||
|
||||
if ($login_refresh) {
|
||||
$a->getLogger()->info('auth_identities refresh: ' . print_r($a->identities, true));
|
||||
}
|
||||
|
||||
$contact = DBA::selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
|
||||
if (DBA::isResult($contact)) {
|
||||
$a->contact = $contact;
|
||||
$a->cid = $contact['id'];
|
||||
self::set('cid', $a->cid);
|
||||
}
|
||||
|
||||
header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
|
||||
|
||||
if ($login_initial || $login_refresh) {
|
||||
DBA::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
|
||||
|
||||
// Set the login date for all identities of the user
|
||||
DBA::update('user', ['login_date' => DateTimeFormat::utcNow()],
|
||||
['parent-uid' => $masterUid, 'account_removed' => false]);
|
||||
}
|
||||
|
||||
if ($login_initial) {
|
||||
/*
|
||||
* If the user specified to remember the authentication, then set a cookie
|
||||
* that expires after one week (the default is when the browser is closed).
|
||||
* The cookie will be renewed automatically.
|
||||
* The week ensures that sessions will expire after some inactivity.
|
||||
*/
|
||||
;
|
||||
if (self::get('remember')) {
|
||||
$a->getLogger()->info('Injecting cookie for remembered user ' . $user_record['nickname']);
|
||||
Authentication::setCookie(604800, $user_record);
|
||||
self::remove('remember');
|
||||
}
|
||||
}
|
||||
|
||||
Authentication::twoFactorCheck($user_record['uid'], $a);
|
||||
|
||||
if ($interactive) {
|
||||
if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
|
||||
info(L10n::t('Welcome %s', $user_record['username']));
|
||||
info(L10n::t('Please upload a profile photo.'));
|
||||
$a->internalRedirect('profile_photo/new');
|
||||
} else {
|
||||
info(L10n::t("Welcome back %s", $user_record['username']));
|
||||
}
|
||||
}
|
||||
|
||||
$a->user = $user_record;
|
||||
|
||||
if ($login_initial) {
|
||||
Hook::callAll('logged_in', $a->user);
|
||||
|
||||
if ($a->module !== 'home' && self::exists('return_path')) {
|
||||
$a->internalRedirect(self::get('return_path'));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1484,6 +1484,8 @@ class DBA
|
|||
$new_values = array_merge($new_values, array_values($value));
|
||||
$placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
|
||||
$condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
|
||||
} elseif (is_null($value)) {
|
||||
$condition_string .= "`" . $field . "` IS NULL";
|
||||
} else {
|
||||
$new_values[$field] = $value;
|
||||
$condition_string .= "`" . $field . "` = ?";
|
||||
|
|
125
src/Model/TwoFactorRecoveryCode.php
Normal file
125
src/Model/TwoFactorRecoveryCode.php
Normal file
|
@ -0,0 +1,125 @@
|
|||
<?php
|
||||
|
||||
namespace Friendica\Model;
|
||||
|
||||
use Friendica\BaseObject;
|
||||
use Friendica\Database\DBA;
|
||||
use Friendica\Util\DateTimeFormat;
|
||||
use PragmaRX\Random\Random;
|
||||
use PragmaRX\Recovery\Recovery;
|
||||
|
||||
/**
|
||||
* Manages users' two-factor recovery codes in the 2fa_recovery_codes table
|
||||
*
|
||||
* @package Friendica\Model
|
||||
*/
|
||||
class TwoFactorRecoveryCode extends BaseObject
|
||||
{
|
||||
/**
|
||||
* Returns the number of code the provided users can still use to replace a TOTP code
|
||||
*
|
||||
* @param int $uid User ID
|
||||
* @return int
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function countValidForUser($uid)
|
||||
{
|
||||
return DBA::count('2fa_recovery_codes', ['uid' => $uid, 'used' => null]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the provided code is available to use for login by the provided user
|
||||
*
|
||||
* @param int $uid User ID
|
||||
* @param string $code
|
||||
* @return bool
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function existsForUser($uid, $code)
|
||||
{
|
||||
return DBA::exists('2fa_recovery_codes', ['uid' => $uid, 'code' => $code, 'used' => null]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a complete list of all recovery codes for the provided user, including the used status
|
||||
*
|
||||
* @param int $uid User ID
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function getListForUser($uid)
|
||||
{
|
||||
$codesStmt = DBA::select('2fa_recovery_codes', ['code', 'used'], ['uid' => $uid]);
|
||||
|
||||
return DBA::toArray($codesStmt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the provided code as used for the provided user.
|
||||
* Returns false if the code doesn't exist for the user or it has been used already.
|
||||
*
|
||||
* @param int $uid User ID
|
||||
* @param string $code
|
||||
* @return bool
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function markUsedForUser($uid, $code)
|
||||
{
|
||||
DBA::update('2fa_recovery_codes', ['used' => DateTimeFormat::utcNow()], ['uid' => $uid, 'code' => $code, 'used' => null]);
|
||||
|
||||
return DBA::affectedRows() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a fresh set of recovery codes for the provided user.
|
||||
* Generates 12 codes constituted of 2 blocks of 6 characters separated by a dash.
|
||||
*
|
||||
* @param int $uid User ID
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function generateForUser($uid)
|
||||
{
|
||||
$Random = (new Random())->pattern('[a-z0-9]');
|
||||
|
||||
$RecoveryGenerator = new Recovery($Random);
|
||||
|
||||
$codes = $RecoveryGenerator
|
||||
->setCount(12)
|
||||
->setBlocks(2)
|
||||
->setChars(6)
|
||||
->lowercase(true)
|
||||
->toArray();
|
||||
|
||||
$generated = DateTimeFormat::utcNow();
|
||||
foreach ($codes as $code) {
|
||||
DBA::insert('2fa_recovery_codes', [
|
||||
'uid' => $uid,
|
||||
'code' => $code,
|
||||
'generated' => $generated
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all the recovery codes for the provided user.
|
||||
*
|
||||
* @param int $uid User ID
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function deleteForUser($uid)
|
||||
{
|
||||
DBA::delete('2fa_recovery_codes', ['uid' => $uid]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the existing recovery codes for the provided user by a freshly generated set.
|
||||
*
|
||||
* @param int $uid User ID
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function regenerateForUser($uid)
|
||||
{
|
||||
self::deleteForUser($uid);
|
||||
self::generateForUser($uid);
|
||||
}
|
||||
}
|
110
src/Module/BaseSettingsModule.php
Normal file
110
src/Module/BaseSettingsModule.php
Normal file
|
@ -0,0 +1,110 @@
|
|||
<?php
|
||||
|
||||
namespace Friendica\Module;
|
||||
|
||||
use Friendica\BaseModule;
|
||||
use Friendica\Content\Feature;
|
||||
use Friendica\Core\L10n;
|
||||
use Friendica\Core\Renderer;
|
||||
|
||||
class BaseSettingsModule extends BaseModule
|
||||
{
|
||||
public static function content()
|
||||
{
|
||||
$a = self::getApp();
|
||||
|
||||
$tpl = Renderer::getMarkupTemplate('settings/head.tpl');
|
||||
$a->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
|
||||
'$ispublic' => L10n::t('everybody')
|
||||
]);
|
||||
|
||||
$tabs = [];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Account'),
|
||||
'url' => 'settings',
|
||||
'selected' => (($a->argc == 1) && ($a->argv[0] === 'settings') ? 'active' : ''),
|
||||
'accesskey' => 'o',
|
||||
];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Two-factor authentication'),
|
||||
'url' => 'settings/2fa',
|
||||
'selected' => (($a->argc > 1) && ($a->argv[1] === '2fa') ? 'active' : ''),
|
||||
'accesskey' => 'o',
|
||||
];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Profiles'),
|
||||
'url' => 'profiles',
|
||||
'selected' => (($a->argc == 1) && ($a->argv[0] === 'profiles') ? 'active' : ''),
|
||||
'accesskey' => 'p',
|
||||
];
|
||||
|
||||
if (Feature::get()) {
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Additional features'),
|
||||
'url' => 'settings/features',
|
||||
'selected' => (($a->argc > 1) && ($a->argv[1] === 'features') ? 'active' : ''),
|
||||
'accesskey' => 't',
|
||||
];
|
||||
}
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Display'),
|
||||
'url' => 'settings/display',
|
||||
'selected' => (($a->argc > 1) && ($a->argv[1] === 'display') ? 'active' : ''),
|
||||
'accesskey' => 'i',
|
||||
];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Social Networks'),
|
||||
'url' => 'settings/connectors',
|
||||
'selected' => (($a->argc > 1) && ($a->argv[1] === 'connectors') ? 'active' : ''),
|
||||
'accesskey' => 'w',
|
||||
];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Addons'),
|
||||
'url' => 'settings/addon',
|
||||
'selected' => (($a->argc > 1) && ($a->argv[1] === 'addon') ? 'active' : ''),
|
||||
'accesskey' => 'l',
|
||||
];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Delegations'),
|
||||
'url' => 'delegate',
|
||||
'selected' => (($a->argc == 1) && ($a->argv[0] === 'delegate') ? 'active' : ''),
|
||||
'accesskey' => 'd',
|
||||
];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Connected apps'),
|
||||
'url' => 'settings/oauth',
|
||||
'selected' => (($a->argc > 1) && ($a->argv[1] === 'oauth') ? 'active' : ''),
|
||||
'accesskey' => 'b',
|
||||
];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Export personal data'),
|
||||
'url' => 'uexport',
|
||||
'selected' => (($a->argc == 1) && ($a->argv[0] === 'uexport') ? 'active' : ''),
|
||||
'accesskey' => 'e',
|
||||
];
|
||||
|
||||
$tabs[] = [
|
||||
'label' => L10n::t('Remove account'),
|
||||
'url' => 'removeme',
|
||||
'selected' => (($a->argc == 1) && ($a->argv[0] === 'removeme') ? 'active' : ''),
|
||||
'accesskey' => 'r',
|
||||
];
|
||||
|
||||
|
||||
$tabtpl = Renderer::getMarkupTemplate("generic_links_widget.tpl");
|
||||
$a->page['aside'] = Renderer::replaceMacros($tabtpl, [
|
||||
'$title' => L10n::t('Settings'),
|
||||
'$class' => 'settings-widget',
|
||||
'$items' => $tabs,
|
||||
]);
|
||||
}
|
||||
}
|
|
@ -21,35 +21,35 @@ class Help extends BaseModule
|
|||
$text = '';
|
||||
$filename = '';
|
||||
|
||||
$app = self::getApp();
|
||||
$config = $app->getConfig();
|
||||
$a = self::getApp();
|
||||
$config = $a->getConfig();
|
||||
$lang = $config->get('system', 'language');
|
||||
|
||||
// @TODO: Replace with parameter from router
|
||||
if ($app->argc > 1) {
|
||||
if ($a->argc > 1) {
|
||||
$path = '';
|
||||
// looping through the argv keys bigger than 0 to build
|
||||
// a path relative to /help
|
||||
for ($x = 1; $x < $app->argc; $x ++) {
|
||||
for ($x = 1; $x < $a->argc; $x ++) {
|
||||
if (strlen($path)) {
|
||||
$path .= '/';
|
||||
}
|
||||
|
||||
$path .= $app->getArgumentValue($x);
|
||||
$path .= $a->getArgumentValue($x);
|
||||
}
|
||||
$title = basename($path);
|
||||
$filename = $path;
|
||||
$text = self::loadDocFile('doc/' . $path . '.md', $lang);
|
||||
$app->page['title'] = L10n::t('Help:') . ' ' . str_replace('-', ' ', Strings::escapeTags($title));
|
||||
$a->page['title'] = L10n::t('Help:') . ' ' . str_replace('-', ' ', Strings::escapeTags($title));
|
||||
}
|
||||
|
||||
$home = self::loadDocFile('doc/Home.md', $lang);
|
||||
if (!$text) {
|
||||
$text = $home;
|
||||
$filename = "Home";
|
||||
$app->page['title'] = L10n::t('Help');
|
||||
$a->page['title'] = L10n::t('Help');
|
||||
} else {
|
||||
$app->page['aside'] = Markdown::convert($home, false);
|
||||
$a->page['aside'] = Markdown::convert($home, false);
|
||||
}
|
||||
|
||||
if (!strlen($text)) {
|
||||
|
@ -85,7 +85,7 @@ class Help extends BaseModule
|
|||
|
||||
$idNum[$level] ++;
|
||||
$id = implode("_", array_slice($idNum, 1, $level));
|
||||
$href = $app->getBaseURL() . "/help/{$filename}#{$id}";
|
||||
$href = $a->getBaseURL() . "/help/{$filename}#{$id}";
|
||||
$toc .= "<li><a href='{$href}'>" . strip_tags($line) . "</a></li>";
|
||||
$line = "<a name='{$id}'></a>" . $line;
|
||||
$lastLevel = $level;
|
||||
|
|
|
@ -12,6 +12,7 @@ use Friendica\Core\Hook;
|
|||
use Friendica\Core\L10n;
|
||||
use Friendica\Core\Logger;
|
||||
use Friendica\Core\Renderer;
|
||||
use Friendica\Core\Session;
|
||||
use Friendica\Core\System;
|
||||
use Friendica\Database\DBA;
|
||||
use Friendica\Model\User;
|
||||
|
@ -160,7 +161,8 @@ class Login extends BaseModule
|
|||
// if we haven't failed up this point, log them in.
|
||||
$_SESSION['remember'] = $remember;
|
||||
$_SESSION['last_login_date'] = DateTimeFormat::utcNow();
|
||||
Authentication::setAuthenticatedSessionForUser($record, true, true);
|
||||
|
||||
Session::setAuthenticatedForUser($a, $record, true, true);
|
||||
|
||||
if (!empty($_SESSION['return_path'])) {
|
||||
$return_path = $_SESSION['return_path'];
|
||||
|
@ -210,7 +212,7 @@ class Login extends BaseModule
|
|||
|
||||
// Do the authentification if not done by now
|
||||
if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
|
||||
Authentication::setAuthenticatedSessionForUser($user);
|
||||
Session::setAuthenticatedForUser($a, $user);
|
||||
|
||||
if (Config::get('system', 'paranoia')) {
|
||||
$_SESSION['addr'] = $data->ip;
|
||||
|
@ -263,7 +265,8 @@ class Login extends BaseModule
|
|||
$_SESSION['last_login_date'] = DateTimeFormat::utcNow();
|
||||
$login_refresh = true;
|
||||
}
|
||||
Authentication::setAuthenticatedSessionForUser($user, false, false, $login_refresh);
|
||||
|
||||
Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
108
src/Module/Settings/TwoFactor/Index.php
Normal file
108
src/Module/Settings/TwoFactor/Index.php
Normal file
|
@ -0,0 +1,108 @@
|
|||
<?php
|
||||
|
||||
|
||||
namespace Friendica\Module\Settings\TwoFactor;
|
||||
|
||||
|
||||
use Friendica\Core\L10n;
|
||||
use Friendica\Core\PConfig;
|
||||
use Friendica\Core\Renderer;
|
||||
use Friendica\Core\Session;
|
||||
use Friendica\Model\TwoFactorRecoveryCode;
|
||||
use Friendica\Model\User;
|
||||
use Friendica\Module\BaseSettingsModule;
|
||||
use Friendica\Module\Login;
|
||||
use PragmaRX\Google2FA\Google2FA;
|
||||
|
||||
class Index extends BaseSettingsModule
|
||||
{
|
||||
public static function post()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::checkFormSecurityTokenRedirectOnError('settings/2fa', 'settings_2fa');
|
||||
|
||||
try {
|
||||
User::getIdFromPasswordAuthentication(local_user(), defaults($_POST, 'password', ''));
|
||||
|
||||
$has_secret = (bool) PConfig::get(local_user(), '2fa', 'secret');
|
||||
$verified = PConfig::get(local_user(), '2fa', 'verified');
|
||||
|
||||
switch (defaults($_POST, 'action', '')) {
|
||||
case 'enable':
|
||||
if (!$has_secret && !$verified) {
|
||||
$Google2FA = new Google2FA();
|
||||
|
||||
PConfig::set(local_user(), '2fa', 'secret', $Google2FA->generateSecretKey(32));
|
||||
|
||||
self::getApp()->internalRedirect('settings/2fa/recovery?t=' . self::getFormSecurityToken('settings_2fa_password'));
|
||||
}
|
||||
break;
|
||||
case 'disable':
|
||||
if ($has_secret) {
|
||||
TwoFactorRecoveryCode::deleteForUser(local_user());
|
||||
PConfig::delete(local_user(), '2fa', 'secret');
|
||||
PConfig::delete(local_user(), '2fa', 'verified');
|
||||
Session::remove('2fa');
|
||||
|
||||
notice(L10n::t('Two-factor authentication successfully disabled.'));
|
||||
self::getApp()->internalRedirect('settings/2fa');
|
||||
}
|
||||
break;
|
||||
case 'recovery':
|
||||
if ($has_secret) {
|
||||
self::getApp()->internalRedirect('settings/2fa/recovery?t=' . self::getFormSecurityToken('settings_2fa_password'));
|
||||
}
|
||||
break;
|
||||
case 'configure':
|
||||
if (!$verified) {
|
||||
self::getApp()->internalRedirect('settings/2fa/verify?t=' . self::getFormSecurityToken('settings_2fa_password'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
notice(L10n::t('Wrong Password'));
|
||||
}
|
||||
}
|
||||
|
||||
public static function content()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return Login::form('settings/2fa');
|
||||
}
|
||||
|
||||
parent::content();
|
||||
|
||||
$has_secret = (bool) PConfig::get(local_user(), '2fa', 'secret');
|
||||
$verified = PConfig::get(local_user(), '2fa', 'verified');
|
||||
|
||||
return Renderer::replaceMacros(Renderer::getMarkupTemplate('settings/twofactor/index.tpl'), [
|
||||
'$form_security_token' => self::getFormSecurityToken('settings_2fa'),
|
||||
'$title' => L10n::t('Two-factor authentication'),
|
||||
'$help_label' => L10n::t('Help'),
|
||||
'$status_title' => L10n::t('Status'),
|
||||
'$message' => L10n::t('<p>Use an application on a mobile device to get two-factor authentication codes when prompted on login.</p>'),
|
||||
'$has_secret' => $has_secret,
|
||||
'$verified' => $verified,
|
||||
|
||||
'$auth_app_label' => L10n::t('Authenticator app'),
|
||||
'$app_status' => $has_secret ? $verified ? L10n::t('Configured') : L10n::t('Not Configured') : L10n::t('Disabled'),
|
||||
'$not_configured_message' => L10n::t('<p>You haven\'t finished configuring your authenticator app.</p>'),
|
||||
'$configured_message' => L10n::t('<p>Your authenticator app is correctly configured.</p>'),
|
||||
|
||||
'$recovery_codes_title' => L10n::t('Recovery codes'),
|
||||
'$recovery_codes_remaining' => L10n::t('Remaining valid codes'),
|
||||
'$recovery_codes_count' => TwoFactorRecoveryCode::countValidForUser(local_user()),
|
||||
'$recovery_codes_message' => L10n::t('<p>These one-use codes can replace an authenticator app code in case you have lost access to it.</p>'),
|
||||
|
||||
'$action_title' => L10n::t('Actions'),
|
||||
'$password' => ['password', L10n::t('Current password:'), '', L10n::t('You need to provide your current password to change two-factor authentication settings.'), 'required', 'autofocus'],
|
||||
'$enable_label' => L10n::t('Enable two-factor authentication'),
|
||||
'$disable_label' => L10n::t('Disable two-factor authentication'),
|
||||
'$recovery_codes_label' => L10n::t('Show recovery codes'),
|
||||
'$configure_label' => L10n::t('Finish app configuration'),
|
||||
]);
|
||||
}
|
||||
}
|
86
src/Module/Settings/TwoFactor/Recovery.php
Normal file
86
src/Module/Settings/TwoFactor/Recovery.php
Normal file
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
|
||||
|
||||
namespace Friendica\Module\Settings\TwoFactor;
|
||||
|
||||
|
||||
use Friendica\Core\L10n;
|
||||
use Friendica\Core\PConfig;
|
||||
use Friendica\Core\Renderer;
|
||||
use Friendica\Model\TwoFactorRecoveryCode;
|
||||
use Friendica\Module\BaseSettingsModule;
|
||||
use Friendica\Module\Login;
|
||||
|
||||
/**
|
||||
* // Page 3: 2FA enabled but not verified, show recovery codes
|
||||
*
|
||||
* @package Friendica\Module\TwoFactor
|
||||
*/
|
||||
class Recovery extends BaseSettingsModule
|
||||
{
|
||||
public static function init()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$secret = PConfig::get(local_user(), '2fa', 'secret');
|
||||
|
||||
if (!$secret) {
|
||||
self::getApp()->internalRedirect('settings/2fa');
|
||||
}
|
||||
|
||||
if (!self::checkFormSecurityToken('settings_2fa_password', 't')) {
|
||||
notice(L10n::t('Please enter your password to access this page.'));
|
||||
self::getApp()->internalRedirect('settings/2fa');
|
||||
}
|
||||
}
|
||||
|
||||
public static function post()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!empty($_POST['action'])) {
|
||||
self::checkFormSecurityTokenRedirectOnError('settings/2fa/recovery', 'settings_2fa_recovery');
|
||||
|
||||
if ($_POST['action'] == 'regenerate') {
|
||||
TwoFactorRecoveryCode::regenerateForUser(local_user());
|
||||
notice(L10n::t('New recovery codes successfully generated.'));
|
||||
self::getApp()->internalRedirect('settings/2fa/recovery?t=' . self::getFormSecurityToken('settings_2fa_password'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function content()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return Login::form('settings/2fa/recovery');
|
||||
}
|
||||
|
||||
parent::content();
|
||||
|
||||
if (!TwoFactorRecoveryCode::countValidForUser(local_user())) {
|
||||
TwoFactorRecoveryCode::generateForUser(local_user());
|
||||
}
|
||||
|
||||
$recoveryCodes = TwoFactorRecoveryCode::getListForUser(local_user());
|
||||
|
||||
$verified = PConfig::get(local_user(), '2fa', 'verified');
|
||||
|
||||
return Renderer::replaceMacros(Renderer::getMarkupTemplate('settings/twofactor/recovery.tpl'), [
|
||||
'$form_security_token' => self::getFormSecurityToken('settings_2fa_recovery'),
|
||||
'$password_security_token' => self::getFormSecurityToken('settings_2fa_password'),
|
||||
|
||||
'$title' => L10n::t('Two-factor recovery codes'),
|
||||
'$help_label' => L10n::t('Help'),
|
||||
'$message' => L10n::t('<p>Recovery codes can be used to access your account in the event you lose access to your device and cannot receive two-factor authentication codes.</p><p><strong>Put these in a safe spot!</strong> If you lose your device and don’t have the recovery codes you will lose access to your account.</p>'),
|
||||
'$recovery_codes' => $recoveryCodes,
|
||||
'$regenerate_message' => L10n::t('When you generate new recovery codes, you must copy the new codes. Your old codes won’t work anymore.'),
|
||||
'$regenerate_label' => L10n::t('Generate new recovery codes'),
|
||||
'$verified' => $verified,
|
||||
'$verify_label' => L10n::t('Next: Verification'),
|
||||
]);
|
||||
}
|
||||
}
|
130
src/Module/Settings/TwoFactor/Verify.php
Normal file
130
src/Module/Settings/TwoFactor/Verify.php
Normal file
|
@ -0,0 +1,130 @@
|
|||
<?php
|
||||
|
||||
|
||||
namespace Friendica\Module\Settings\TwoFactor;
|
||||
|
||||
|
||||
use BaconQrCode\Renderer\Image\SvgImageBackEnd;
|
||||
use BaconQrCode\Renderer\ImageRenderer;
|
||||
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
|
||||
use BaconQrCode\Writer;
|
||||
use Friendica\BaseModule;
|
||||
use Friendica\Core\L10n;
|
||||
use Friendica\Core\PConfig;
|
||||
use Friendica\Core\Renderer;
|
||||
use Friendica\Core\Session;
|
||||
use Friendica\Module\BaseSettingsModule;
|
||||
use Friendica\Module\Login;
|
||||
use PragmaRX\Google2FA\Google2FA;
|
||||
|
||||
/**
|
||||
* // Page 4: 2FA enabled but not verified, QR code and verification
|
||||
*
|
||||
* @package Friendica\Module\TwoFactor\Settings
|
||||
*/
|
||||
class Verify extends BaseSettingsModule
|
||||
{
|
||||
public static function init()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$secret = PConfig::get(local_user(), '2fa', 'secret');
|
||||
$verified = PConfig::get(local_user(), '2fa', 'verified');
|
||||
|
||||
if ($secret && $verified) {
|
||||
self::getApp()->internalRedirect('settings/2fa');
|
||||
}
|
||||
|
||||
if (!self::checkFormSecurityToken('settings_2fa_password', 't')) {
|
||||
notice(L10n::t('Please enter your password to access this page.'));
|
||||
self::getApp()->internalRedirect('settings/2fa');
|
||||
}
|
||||
}
|
||||
|
||||
public static function post()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (defaults($_POST, 'action', null) == 'verify') {
|
||||
self::checkFormSecurityTokenRedirectOnError('settings/2fa/verify', 'settings_2fa_verify');
|
||||
|
||||
$google2fa = new Google2FA();
|
||||
|
||||
$valid = $google2fa->verifyKey(PConfig::get(local_user(), '2fa', 'secret'), defaults($_POST, 'verify_code', ''));
|
||||
|
||||
if ($valid) {
|
||||
PConfig::set(local_user(), '2fa', 'verified', true);
|
||||
Session::set('2fa', true);
|
||||
|
||||
notice(L10n::t('Two-factor authentication successfully activated.'));
|
||||
|
||||
self::getApp()->internalRedirect('settings/2fa');
|
||||
} else {
|
||||
notice(L10n::t('Invalid code, please retry.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function content()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return Login::form('settings/2fa/verify');
|
||||
}
|
||||
|
||||
parent::content();
|
||||
|
||||
$company = 'Friendica';
|
||||
$holder = Session::get('my_address');
|
||||
$secret = PConfig::get(local_user(), '2fa', 'secret');
|
||||
|
||||
$otpauthUrl = (new Google2FA())->getQRCodeUrl($company, $holder, $secret);
|
||||
|
||||
$renderer = (new \BaconQrCode\Renderer\Image\Svg())
|
||||
->setHeight(256)
|
||||
->setWidth(256);
|
||||
|
||||
$writer = new Writer($renderer);
|
||||
|
||||
$qrcode_image = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $writer->writeString($otpauthUrl));
|
||||
|
||||
$shortOtpauthUrl = explode('?', $otpauthUrl)[0];
|
||||
|
||||
$manual_message = L10n::t('<p>Or you can submit the authentication settings manually:</p>
|
||||
<dl>
|
||||
<dt>Issuer</dt>
|
||||
<dd>%s</dd>
|
||||
<dt>Account Name</dt>
|
||||
<dd>%s</dd>
|
||||
<dt>Secret Key</dt>
|
||||
<dd>%s</dd>
|
||||
<dt>Type</dt>
|
||||
<dd>Time-based</dd>
|
||||
<dt>Number of digits</dt>
|
||||
<dd>6</dd>
|
||||
<dt>Hashing algorithm</dt>
|
||||
<dd>SHA-1</dd>
|
||||
</dl>', $company, $holder, $secret);
|
||||
|
||||
return Renderer::replaceMacros(Renderer::getMarkupTemplate('settings/twofactor/verify.tpl'), [
|
||||
'$form_security_token' => self::getFormSecurityToken('settings_2fa_verify'),
|
||||
'$password_security_token' => self::getFormSecurityToken('settings_2fa_password'),
|
||||
|
||||
'$title' => L10n::t('Two-factor code verification'),
|
||||
'$help_label' => L10n::t('Help'),
|
||||
'$message' => L10n::t('<p>Please scan this QR Code with your authenticator app and submit the provided code.</p>'),
|
||||
'$qrcode_image' => $qrcode_image,
|
||||
'$qrcode_url_message' => L10n::t('<p>Or you can open the following URL in your mobile devicde:</p><p><a href="%s">%s</a></p>', $otpauthUrl, $shortOtpauthUrl),
|
||||
'$manual_message' => $manual_message,
|
||||
'$company' => $company,
|
||||
'$holder' => $holder,
|
||||
'$secret' => $secret,
|
||||
|
||||
'$verify_code' => ['verify_code', L10n::t('Please enter a code from your authentication app'), '', '', 'required', 'autofocus placeholder="000000"'],
|
||||
'$verify_label' => L10n::t('Verify code and enable two-factor authentication'),
|
||||
]);
|
||||
}
|
||||
}
|
72
src/Module/TwoFactor/Recovery.php
Normal file
72
src/Module/TwoFactor/Recovery.php
Normal file
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
namespace Friendica\Module\TwoFactor;
|
||||
|
||||
use Friendica\BaseModule;
|
||||
use Friendica\Core\L10n;
|
||||
use Friendica\Core\Renderer;
|
||||
use Friendica\Core\Session;
|
||||
use Friendica\Model\TwoFactorRecoveryCode;
|
||||
|
||||
/**
|
||||
* // Page 1a: Recovery code verification
|
||||
*
|
||||
* @package Friendica\Module\TwoFactor
|
||||
*/
|
||||
class Recovery extends BaseModule
|
||||
{
|
||||
public static function init()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public static function post()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (defaults($_POST, 'action', null) == 'recover') {
|
||||
self::checkFormSecurityTokenRedirectOnError('2fa', 'twofactor_recovery');
|
||||
|
||||
$a = self::getApp();
|
||||
|
||||
$recovery_code = defaults($_POST, 'recovery_code', '');
|
||||
|
||||
if (TwoFactorRecoveryCode::existsForUser(local_user(), $recovery_code)) {
|
||||
TwoFactorRecoveryCode::markUsedForUser(local_user(), $recovery_code);
|
||||
Session::set('2fa', true);
|
||||
notice(L10n::t('Remaining recovery codes: %d', TwoFactorRecoveryCode::countValidForUser(local_user())));
|
||||
|
||||
// Resume normal login workflow
|
||||
Session::setAuthenticatedForUser($a, $a->user, true, true);
|
||||
} else {
|
||||
notice(L10n::t('Invalid code, please retry.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function content()
|
||||
{
|
||||
if (!local_user()) {
|
||||
self::getApp()->internalRedirect();
|
||||
}
|
||||
|
||||
// Already authenticated with 2FA token
|
||||
if (Session::get('2fa')) {
|
||||
self::getApp()->internalRedirect();
|
||||
}
|
||||
|
||||
return Renderer::replaceMacros(Renderer::getMarkupTemplate('twofactor/recovery.tpl'), [
|
||||
'$form_security_token' => self::getFormSecurityToken('twofactor_recovery'),
|
||||
|
||||
'$title' => L10n::t('Two-factor recovery'),
|
||||
'$message' => L10n::t('<p>You can enter one of your one-time recovery codes in case you lost access to your mobile device.</p>'),
|
||||
'$recovery_message' => L10n::t('Don’t have your phone? <a href="%s">Enter a two-factor recovery code</a>', '2fa/recovery'),
|
||||
'$recovery_code' => ['recovery_code', L10n::t('Please enter a recovery code'), '', '', '', 'placeholder="000000-000000"'],
|
||||
'$recovery_label' => L10n::t('Submit recovery code and complete login'),
|
||||
]);
|
||||
}
|
||||
}
|
67
src/Module/TwoFactor/Verify.php
Normal file
67
src/Module/TwoFactor/Verify.php
Normal file
|
@ -0,0 +1,67 @@
|
|||
<?php
|
||||
|
||||
namespace Friendica\Module\TwoFactor;
|
||||
|
||||
use Friendica\BaseModule;
|
||||
use Friendica\Core\L10n;
|
||||
use Friendica\Core\PConfig;
|
||||
use Friendica\Core\Renderer;
|
||||
use Friendica\Core\Session;
|
||||
use PragmaRX\Google2FA\Google2FA;
|
||||
|
||||
/**
|
||||
* Page 1: Authenticator code verification
|
||||
*
|
||||
* @package Friendica\Module\TwoFactor
|
||||
*/
|
||||
class Verify extends BaseModule
|
||||
{
|
||||
public static function post()
|
||||
{
|
||||
if (!local_user()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (defaults($_POST, 'action', null) == 'verify') {
|
||||
self::checkFormSecurityTokenRedirectOnError('2fa', 'twofactor_verify');
|
||||
|
||||
$a = self::getApp();
|
||||
|
||||
$code = defaults($_POST, 'verify_code', '');
|
||||
|
||||
$valid = (new Google2FA())->verifyKey(PConfig::get(local_user(), '2fa', 'secret'), $code);
|
||||
|
||||
// The same code can't be used twice even if it's valid
|
||||
if ($valid && Session::get('2fa') !== $code) {
|
||||
Session::set('2fa', $code);
|
||||
|
||||
// Resume normal login workflow
|
||||
Session::setAuthenticatedForUser($a, $a->user, true, true);
|
||||
} else {
|
||||
notice(L10n::t('Invalid code, please retry.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function content()
|
||||
{
|
||||
if (!local_user()) {
|
||||
self::getApp()->internalRedirect();
|
||||
}
|
||||
|
||||
// Already authenticated with 2FA token
|
||||
if (Session::get('2fa')) {
|
||||
self::getApp()->internalRedirect();
|
||||
}
|
||||
|
||||
return Renderer::replaceMacros(Renderer::getMarkupTemplate('twofactor/verify.tpl'), [
|
||||
'$form_security_token' => self::getFormSecurityToken('twofactor_verify'),
|
||||
|
||||
'$title' => L10n::t('Two-factor authentication'),
|
||||
'$message' => L10n::t('<p>Open the two-factor authentication app on your device to get an authentication code and verify your identity.</p>'),
|
||||
'$recovery_message' => L10n::t('Don’t have your phone? <a href="%s">Enter a two-factor recovery code</a>', '2fa/recovery'),
|
||||
'$verify_code' => ['verify_code', L10n::t('Please enter a code from your authentication app'), '', '', 'required', 'autofocus placeholder="000000"'],
|
||||
'$verify_label' => L10n::t('Verify code and complete login'),
|
||||
]);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue