Skip to content

Firefly III: a personal finances manager

Filter the preferences users can set

Sander Dorigo42ab1ccd8f31
diff --git a/app/Api/V1/Controllers/User/PreferencesController.php b/app/Api/V1/Controllers/User/PreferencesController.php
index 3e9942e0ad..dad237eb4e 100644
--- a/app/Api/V1/Controllers/User/PreferencesController.php
+++ b/app/Api/V1/Controllers/User/PreferencesController.php
@@ -135,7 +135,6 @@ final class PreferencesController extends Controller
/** @var PreferenceTransformer $transformer */
$transformer = app(PreferenceTransformer::class);
- $transformer->setParameters($this->parameters);
$resource = new Item($pref, $transformer, 'preferences');
diff --git a/app/Console/Commands/Correction/CreatesAccessTokens.php b/app/Console/Commands/Correction/CreatesAccessTokens.php
index ef478d8da2..47b6d96201 100644
--- a/app/Console/Commands/Correction/CreatesAccessTokens.php
+++ b/app/Console/Commands/Correction/CreatesAccessTokens.php
@@ -58,7 +58,7 @@ class CreatesAccessTokens extends Command
$pref = Preferences::getForUser($user, 'access_token');
if (null === $pref) {
$token = $user->generateAccessToken();
- Preferences::setForUser($user, 'access_token', $token);
+ Preferences::setForUser($user, 'access_token', $token, true);
$this->friendlyInfo(sprintf('Generated access token for user %s', $user->email));
++$count;
}
diff --git a/app/Http/Controllers/Auth/TwoFactorController.php b/app/Http/Controllers/Auth/TwoFactorController.php
index b39337c994..afafcfa87c 100644
--- a/app/Http/Controllers/Auth/TwoFactorController.php
+++ b/app/Http/Controllers/Auth/TwoFactorController.php
@@ -130,7 +130,7 @@ final class TwoFactorController extends Controller
$preference = (int) Preferences::get('mfa_failure_count', 0)->data;
++$preference;
Log::channel('audit')->info(sprintf('MFA failure count is set to %d.', $preference));
- Preferences::set('mfa_failure_count', $preference);
+ Preferences::set('mfa_failure_count', $preference, true);
}
private function addToMFAHistory(string $mfaCode): void
@@ -140,7 +140,7 @@ final class TwoFactorController extends Controller
$entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode];
$mfaHistory[] = $entry;
- Preferences::set('mfa_history', $mfaHistory);
+ Preferences::set('mfa_history', $mfaHistory, true);
$this->filterMFAHistory();
}
@@ -160,7 +160,7 @@ final class TwoFactorController extends Controller
$newHistory[] = ['time' => $time, 'code' => $code];
}
}
- Preferences::set('mfa_history', $newHistory);
+ Preferences::set('mfa_history', $newHistory, true);
}
private function getMFAFailureCounter(): int
@@ -226,12 +226,12 @@ final class TwoFactorController extends Controller
event(new UserHasNoMFABackupCodesLeft($user));
}
- Preferences::set('mfa_recovery', $newList);
+ Preferences::set('mfa_recovery', $newList, true);
}
private function resetMFAFailureCounter(): void
{
- Preferences::set('mfa_failure_count', 0);
+ Preferences::set('mfa_failure_count', 0, true);
Log::channel('audit')->info('MFA failure count is set to zero.');
}
}
diff --git a/app/Http/Controllers/Profile/MfaController.php b/app/Http/Controllers/Profile/MfaController.php
index bf909709d5..8f53d4e652 100644
--- a/app/Http/Controllers/Profile/MfaController.php
+++ b/app/Http/Controllers/Profile/MfaController.php
@@ -116,7 +116,7 @@ final class MfaController extends Controller
$recoveryCodes = $recovery->lowercase()->setCount(8)->setBlocks(2)->setChars(6)->toArray(); // Generate 8 codes // Every code must have 2 blocks // Each block must have 6 chars
$codes = implode("\r\n", $recoveryCodes);
- Preferences::set('mfa_recovery', $recoveryCodes);
+ Preferences::set('mfa_recovery', $recoveryCodes, true);
Preferences::mark();
// send user notification.
@@ -163,8 +163,8 @@ final class MfaController extends Controller
/** @var User $user */
$user = auth()->user();
- Preferences::delete('temp-mfa-secret');
- Preferences::delete('temp-mfa-codes');
+ Preferences::delete('temp-mfa-secret', true);
+ Preferences::delete('temp-mfa-codes', true);
$repository->setMFACode($user, null);
Preferences::mark();
@@ -209,7 +209,7 @@ final class MfaController extends Controller
$secret = Google2FA::generateSecretKey();
$image = Google2FA::getQRCodeInline($domain, auth()->user()->email, $secret);
- Preferences::set('temp-mfa-secret', $secret);
+ Preferences::set('temp-mfa-secret', $secret, true);
return view('profile.mfa.enable-mfa', ['image' => $image, 'secret' => $secret]);
}
@@ -249,7 +249,7 @@ final class MfaController extends Controller
$repository->setMFACode($user, $secret);
- Preferences::delete('temp-mfa-secret');
+ Preferences::delete('temp-mfa-secret', true);
session()->flash('success', (string) trans('firefly.saved_preferences'));
Preferences::mark();
@@ -301,7 +301,7 @@ final class MfaController extends Controller
$entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode];
$mfaHistory[] = $entry;
- Preferences::set('mfa_history', $mfaHistory);
+ Preferences::set('mfa_history', $mfaHistory, true);
$this->filterMFAHistory();
}
@@ -321,6 +321,6 @@ final class MfaController extends Controller
$newHistory[] = ['time' => $time, 'code' => $code];
}
}
- Preferences::set('mfa_history', $newHistory);
+ Preferences::set('mfa_history', $newHistory, true);
}
}
diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php
index 2c38d74ed2..d5caf77427 100644
--- a/app/Http/Controllers/ProfileController.php
+++ b/app/Http/Controllers/ProfileController.php
@@ -137,6 +137,7 @@ final class ProfileController extends Controller
// find preference with this token value.
/** @var Collection $set */
$set = Preferences::findByName('email_change_confirm_token');
+ /** @var User|null $user */
$user = null;
/** @var Preference $preference */
@@ -147,11 +148,14 @@ final class ProfileController extends Controller
}
// update user to clear blocked and blocked_code.
if (null === $user) {
- throw new FireflyException('Invalid token.');
+ throw new FireflyException('[a] Invalid token.');
+ }
+ if('email_changed' !== $user->blocked_code) {
+ throw new FireflyException('[b] Invalid token.');
}
$repository->unblockUser($user);
// also remove the "remote_guard_alt_email" preference.
- Preferences::deleteForUser($user, 'remote_guard_alt_email');
+ Preferences::deleteForUser($user, 'remote_guard_alt_email', true);
// return to log in.
session()->flash('success', (string) trans('firefly.login_with_new_email'));
@@ -209,7 +213,7 @@ final class ProfileController extends Controller
$accessToken = Preferences::get('access_token');
if (null === $accessToken) {
$token = $user->generateAccessToken();
- $accessToken = Preferences::set('access_token', $token);
+ $accessToken = Preferences::set('access_token', $token, true);
}
return view('profile.index', [
@@ -375,7 +379,7 @@ final class ProfileController extends Controller
/** @var User $user */
$user = auth()->user();
$token = $user->generateAccessToken();
- Preferences::set('access_token', $token);
+ Preferences::set('access_token', $token, true);
session()->flash('success', (string) trans('firefly.token_regenerated'));
return redirect(route('profile.index'));
diff --git a/app/Http/Middleware/CatchBlockedUsers.php b/app/Http/Middleware/CatchBlockedUsers.php
new file mode 100644
index 0000000000..879a8d398b
--- /dev/null
+++ b/app/Http/Middleware/CatchBlockedUsers.php
@@ -0,0 +1,32 @@
+<?php
+
+namespace FireflyIII\Http\Middleware;
+
+use Closure;
+use FireflyIII\Exceptions\FireflyException;
+use Illuminate\Auth\AuthenticationException;
+use Illuminate\Http\Request;
+
+class CatchBlockedUsers
+{
+ /**
+ * Handle an incoming request.
+ *
+ * @param Request $request
+ *
+ * @return mixed
+ * @throws AuthenticationException
+ */
+ public function handle($request, Closure $next)
+ {
+ if(auth()->check()) {
+ $user = auth()->user();
+ if(null !== $user) {
+ if(false !== $user->blocked || '' !== (string) $user->blocked_code) {
+ throw new AuthenticationException(sprintf('User is not allowed to use the API ("%s")', $user->blocked_code));
+ }
+ }
+ }
+ return $next($request);
+ }
+}
diff --git a/app/Listeners/Security/User/NotifiesUserAboutNewIpAddress.php b/app/Listeners/Security/User/NotifiesUserAboutNewIpAddress.php
index a788f20203..e19d4cff56 100644
--- a/app/Listeners/Security/User/NotifiesUserAboutNewIpAddress.php
+++ b/app/Listeners/Security/User/NotifiesUserAboutNewIpAddress.php
@@ -54,6 +54,6 @@ class NotifiesUserAboutNewIpAddress implements ShouldQueue
$list[$index]['notified'] = true;
}
- Preferences::setForUser($user, 'login_ip_history', $list);
+ Preferences::setForUser($user, 'login_ip_history', $list, true);
}
}
diff --git a/app/Listeners/Security/User/StoresNewIpAddress.php b/app/Listeners/Security/User/StoresNewIpAddress.php
index 7034e2ead3..c762f96fb7 100644
--- a/app/Listeners/Security/User/StoresNewIpAddress.php
+++ b/app/Listeners/Security/User/StoresNewIpAddress.php
@@ -72,7 +72,7 @@ class StoresNewIpAddress implements ShouldQueue
/** @var bool $send */
$send = Preferences::getForUser($user, 'notification_user_login', true)->data;
- Preferences::setForUser($user, 'login_ip_history', $preference);
+ Preferences::setForUser($user, 'login_ip_history', $preference, true);
if (false === $inArray && true === $send) {
event(new UserLoggedInFromNewIpAddress($user));
diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php
index c4db79624b..fd7d320190 100644
--- a/app/Repositories/User/UserRepository.php
+++ b/app/Repositories/User/UserRepository.php
@@ -83,12 +83,12 @@ class UserRepository implements UserRepositoryInterface
$oldEmail = $user->email;
// save old email as pref
- Preferences::setForUser($user, 'previous_email_latest', $oldEmail);
- Preferences::setForUser($user, 'previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail);
+ Preferences::setForUser($user, 'previous_email_latest', $oldEmail, true);
+ Preferences::setForUser($user, 'previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail, true);
// set undo and confirm token:
- Preferences::setForUser($user, 'email_change_undo_token', bin2hex(random_bytes(16)));
- Preferences::setForUser($user, 'email_change_confirm_token', bin2hex(random_bytes(16)));
+ Preferences::setForUser($user, 'email_change_undo_token', bin2hex(random_bytes(16)), true);
+ Preferences::setForUser($user, 'email_change_confirm_token', bin2hex(random_bytes(16)), true);
// update user
$user->email = $newEmail;
@@ -410,8 +410,8 @@ class UserRepository implements UserRepositoryInterface
$oldEmail = $user->email;
// save old email as pref
- Preferences::setForUser($user, 'admin_previous_email_latest', $oldEmail);
- Preferences::setForUser($user, 'admin_previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail);
+ Preferences::setForUser($user, 'admin_previous_email_latest', $oldEmail, true);
+ Preferences::setForUser($user, 'admin_previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail, true);
$user->email = $newEmail;
$user->save();
diff --git a/app/Support/Authentication/RemoteUserGuard.php b/app/Support/Authentication/RemoteUserGuard.php
index 8053f7d033..342d57a5c0 100644
--- a/app/Support/Authentication/RemoteUserGuard.php
+++ b/app/Support/Authentication/RemoteUserGuard.php
@@ -97,11 +97,11 @@ class RemoteUserGuard implements Guard
$preference = Preferences::getForUser($retrievedUser, 'remote_guard_alt_email');
if ('' !== $emailAddress && null === $preference && $emailAddress !== $userID) {
- Preferences::setForUser($retrievedUser, 'remote_guard_alt_email', $emailAddress);
+ Preferences::setForUser($retrievedUser, 'remote_guard_alt_email', $emailAddress, true);
}
// if the pref isn't null and the object returned isn't null, update the email address.
if ('' !== $emailAddress && null !== $preference && $emailAddress !== $preference->data) {
- Preferences::setForUser($retrievedUser, 'remote_guard_alt_email', $emailAddress);
+ Preferences::setForUser($retrievedUser, 'remote_guard_alt_email', $emailAddress, true);
}
}
diff --git a/app/Support/Preferences.php b/app/Support/Preferences.php
index f0f3cfa7c6..92bcef9eda 100644
--- a/app/Support/Preferences.php
+++ b/app/Support/Preferences.php
@@ -65,8 +65,12 @@ class Preferences
return Preference::query()->where('user_id', $user->id)->whereLike('name', $value)->get();
}
- public function delete(string $name): bool
+ public function delete(string $name, bool $overrule = false): bool
{
+ $systemPreferences = config('firefly.system_preference_keys');
+ if(false === $overrule && (in_array($name, $systemPreferences, true) || array_any($systemPreferences, fn(string $arrayValue) => str_starts_with($name, $arrayValue)))) {
+ throw new FireflyException(sprintf('Function delete() cannot be used to delete preference "%s"', $name));
+ }
$fullName = sprintf('preference%s%s', auth()->user()->id, $name);
if (Cache::has($fullName)) {
Cache::forget($fullName);
@@ -75,10 +79,13 @@ class Preferences
return true;
}
-
- public function deleteForUser(User $user, string $name): bool
+ public function deleteForUser(User $user, string $name, bool $overrule = false): bool
{
- $fullName = sprintf('preference%s%s', auth()->user()->id, $name);
+ $systemPreferences = config('firefly.system_preference_keys');
+ if(false === $overrule && (in_array($name, $systemPreferences, true) || array_any($systemPreferences, fn(string $arrayValue) => str_starts_with($name, $arrayValue)))) {
+ throw new FireflyException(sprintf('Function deleteForUser() cannot be used to delete preference "%s"', $name));
+ }
+ $fullName = sprintf('preference%s%s', $user->id, $name);
if (Cache::has($fullName)) {
Cache::forget($fullName);
}
@@ -239,7 +246,7 @@ class Preferences
return $preference;
}
- return $this->getForUser($user, $name, $default);
+ return $this->getForUser($user, $name, $default, false);
}
public function lastActivity(): string
@@ -273,8 +280,12 @@ class Preferences
Session::forget('first');
}
- public function set(string $name, array|bool|int|string|null $value): Preference
+ public function set(string $name, array|bool|int|string|null $value, bool $overrule = false): Preference
{
+ $systemPreferences = config('firefly.system_preference_keys');
+ if(false === $overrule && (in_array($name, $systemPreferences, true) || array_any($systemPreferences, fn(string $arrayValue) => str_starts_with($name, $arrayValue)))) {
+ throw new FireflyException(sprintf('Function set() cannot be used to set preference "%s"', $name));
+ }
/** @var null|User $user */
$user = auth()->user();
if (null === $user) {
@@ -286,11 +297,15 @@ class Preferences
return $pref;
}
- return $this->setForUser($user, $name, $value);
+ return $this->setForUser($user, $name, $value, $overrule);
}
- public function setEncrypted(string $name, mixed $value): Preference
+ public function setEncrypted(string $name, mixed $value, bool $overrule = false): Preference
{
+ $systemPreferences = config('firefly.system_preference_keys');
+ if(false === $overrule && (in_array($name, $systemPreferences, true) || array_any($systemPreferences, fn(string $arrayValue) => str_starts_with($name, $arrayValue)))) {
+ throw new FireflyException(sprintf('Function setEncrypted() cannot be used to set preference "%s"', $name));
+ }
try {
$encrypted = encrypt($value);
} catch (EncryptException $e) {
@@ -299,11 +314,20 @@ class Preferences
throw new FireflyException(sprintf('Could not encrypt preference "%s". Cowardly refuse to continue.', $name));
}
- return $this->set($name, $encrypted);
+ return $this->set($name, $encrypted, $overrule);
}
- public function setForUser(User $user, string $name, array|bool|int|string|null $value): Preference
+ public function setForUser(User $user, string $name, array|bool|int|string|null $value, bool $overrule = false): Preference
{
+ $systemPreferences = config('firefly.system_preference_keys');
+ if(false === $overrule && (in_array($name, $systemPreferences, true) || array_any($systemPreferences, fn(string $arrayValue) => str_starts_with($name, $arrayValue)))) {
+ var_dump(false === $overrule);
+ var_dump(in_array($name, $systemPreferences, true));
+ var_dump(array_any($systemPreferences, fn(string $arrayValue) => str_starts_with($name, $arrayValue)));
+ var_dump((in_array($name, $systemPreferences, true) || array_any($systemPreferences, fn(string $arrayValue) => str_starts_with($name, $arrayValue))));
+ die('x');
+ throw new FireflyException(sprintf('Function setForUser() cannot be used to set preference "%s"', $name));
+ }
$fullName = sprintf('preference%s%s', $user->id, $name);
$userGroupId = $this->getUserGroupId($user, $name);
$userGroupId = 0 === (int) $userGroupId ? null : (int) $userGroupId;
diff --git a/bootstrap/app.php b/bootstrap/app.php
index 3791e2f5d4..9187403fc9 100644
--- a/bootstrap/app.php
+++ b/bootstrap/app.php
@@ -25,6 +25,7 @@ use FireflyIII\Exceptions\Handler;
use FireflyIII\Http\Middleware\AcceptHeaders;
use FireflyIII\Http\Middleware\Authenticate;
use FireflyIII\Http\Middleware\Binder;
+use FireflyIII\Http\Middleware\CatchBlockedUsers;
use FireflyIII\Http\Middleware\EncryptCookies;
use FireflyIII\Http\Middleware\Installer;
use FireflyIII\Http\Middleware\InterestingMessage;
@@ -112,6 +113,7 @@ $app = Application::configure(basePath: dirname(__DIR__))
// EnsureFrontendRequestsAreStateful::class,
'auth:api',
Binder::class,
+ CatchBlockedUsers::class,
]
);
$middleware->appendToGroup('api_basic', [AcceptHeaders::class, Binder::class]);
diff --git a/config/firefly.php b/config/firefly.php
index 8bdb180897..24a5126e96 100644
--- a/config/firefly.php
+++ b/config/firefly.php
@@ -118,6 +118,22 @@ return [
'update_endpoint' => 'https://version.firefly-iii.org/index.json',
'update_minimum_age' => 7,
+ // system preference keys.
+ // cannot be set or overruled by the user, despite being in the preferences table
+ 'system_preference_keys' => [
+ 'email_change_undo_token',
+ 'email_change_confirm_token',
+ 'access_token',
+ 'lastActivity',
+ 'login_ip_history',
+ 'previous_email_latest',
+ 'previous_email_',
+ 'remote_guard_alt_email',
+ 'mfa_failure_count',
+ 'mfa_history',
+ 'mfa_recovery',
+ 'temp-mfa-secret'],
+
// enabled languages
'languages' => [