Code cleanup.

This commit is contained in:
James Cole
2023-12-20 19:35:52 +01:00
parent c4f6366642
commit 64ec0cf62e
997 changed files with 12908 additions and 28136 deletions

View File

@@ -24,8 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers;
use Auth;
use DB;
use Exception;
use FireflyIII\Events\UserChangedEmail;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Exceptions\ValidationException;
@@ -38,8 +36,6 @@ use FireflyIII\Models\Preference;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Support\Http\Controllers\CreateStuff;
use FireflyIII\User;
use Google2FA;
use Hash;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Foundation\Application;
@@ -61,7 +57,6 @@ use Psr\Container\NotFoundExceptionInterface;
* Class ProfileController.
*
* @method Guard guard()
*
*/
class ProfileController extends Controller
{
@@ -71,8 +66,6 @@ class ProfileController extends Controller
/**
* ProfileController constructor.
*
*/
public function __construct()
{
@@ -96,16 +89,13 @@ class ProfileController extends Controller
/**
* View that generates a 2FA code for the user.
*
* @param Request $request
*
* @return Factory|View|RedirectResponse
* @throws IncompatibleWithGoogleAuthenticatorException
* @throws InvalidCharactersException
* @throws SecretKeyTooShortException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function code(Request $request): Factory | View | RedirectResponse
public function code(Request $request): Factory|RedirectResponse|View
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
@@ -119,7 +109,7 @@ class ProfileController extends Controller
// generate secret if not in session
if (null === $secretPreference) {
// generate secret + store + flash
$secret = Google2FA::generateSecretKey();
$secret = \Google2FA::generateSecretKey();
app('preferences')->set('temp-mfa-secret', $secret);
}
@@ -152,7 +142,7 @@ class ProfileController extends Controller
$codes = implode("\r\n", $recoveryCodes);
$image = Google2FA::getQRCodeInline($domain, auth()->user()->email, (string)$secret);
$image = \Google2FA::getQRCodeInline($domain, auth()->user()->email, (string)$secret);
return view('profile.code', compact('image', 'secret', 'codes'));
}
@@ -160,22 +150,19 @@ class ProfileController extends Controller
/**
* Screen to confirm email change.
*
* @param UserRepositoryInterface $repository
* @param string $token
*
* @return RedirectResponse|Redirector
*
* @throws FireflyException
*/
public function confirmEmailChange(UserRepositoryInterface $repository, string $token): RedirectResponse | Redirector
public function confirmEmailChange(UserRepositoryInterface $repository, string $token): Redirector|RedirectResponse
{
if (!$this->internalAuth) {
throw new FireflyException(trans('firefly.external_user_mgt_disabled'));
}
// find preference with this token value.
/** @var Collection $set */
$set = app('preferences')->findByName('email_change_confirm_token');
$user = null;
/** @var Preference $preference */
foreach ($set as $preference) {
if ($preference->data === $token) {
@@ -196,12 +183,8 @@ class ProfileController extends Controller
/**
* Delete your account view.
*
* @param Request $request
*
* @return View|RedirectResponse
*/
public function deleteAccount(Request $request): View | RedirectResponse
public function deleteAccount(Request $request): RedirectResponse|View
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
@@ -217,15 +200,15 @@ class ProfileController extends Controller
/**
* Delete 2FA routine.
*
*/
public function deleteCode(Request $request): RedirectResponse | Redirector
public function deleteCode(Request $request): Redirector|RedirectResponse
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
@@ -245,9 +228,8 @@ class ProfileController extends Controller
/**
* Enable 2FA screen.
*
*/
public function enable2FA(Request $request): RedirectResponse | Redirector
public function enable2FA(Request $request): Redirector|RedirectResponse
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
@@ -274,17 +256,16 @@ class ProfileController extends Controller
/**
* Index for profile.
*
* @return Factory|View
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function index(): Factory | View
public function index(): Factory|View
{
/** @var User $user */
$user = auth()->user();
$isInternalAuth = $this->internalAuth;
$count = DB::table('oauth_clients')->where('personal_access_client', true)->whereNull('user_id')->count();
$count = \DB::table('oauth_clients')->where('personal_access_client', true)->whereNull('user_id')->count();
$subTitle = $user->email;
$userId = $user->id;
$enabled2FA = null !== $user->mfa_secret;
@@ -298,7 +279,7 @@ class ProfileController extends Controller
if (0 === $count) {
/** @var ClientRepository $repository */
$repository = app(ClientRepository::class);
$repository->createPersonalAccessClient(null, config('app.name') . ' Personal Access Client', 'http://localhost');
$repository->createPersonalAccessClient(null, config('app.name').' Personal Access Client', 'http://localhost');
}
$accessToken = app('preferences')->get('access_token');
@@ -313,10 +294,7 @@ class ProfileController extends Controller
);
}
/**
* @return Factory|View|RedirectResponse
*/
public function logoutOtherSessions(): Factory | View | RedirectResponse
public function logoutOtherSessions(): Factory|RedirectResponse|View
{
if (!$this->internalAuth) {
session()->flash('info', (string)trans('firefly.external_auth_disabled'));
@@ -328,12 +306,9 @@ class ProfileController extends Controller
}
/**
* @param Request $request
*
* @return Factory|View|RedirectResponse
* @throws FireflyException
*/
public function newBackupCodes(Request $request): Factory | View | RedirectResponse
public function newBackupCodes(Request $request): Factory|RedirectResponse|View
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
@@ -344,10 +319,11 @@ class ProfileController extends Controller
// generate recovery codes:
$recovery = app(Recovery::class);
$recoveryCodes = $recovery->lowercase()
->setCount(8) // Generate 8 codes
->setBlocks(2) // Every code must have 7 blocks
->setChars(6) // Each block must have 16 chars
->toArray();
->setCount(8) // Generate 8 codes
->setBlocks(2) // Every code must have 7 blocks
->setChars(6) // Each block must have 16 chars
->toArray()
;
$codes = implode("\r\n", $recoveryCodes);
app('preferences')->set('mfa_recovery', $recoveryCodes);
@@ -358,13 +334,8 @@ class ProfileController extends Controller
/**
* Submit the change email form.
*
* @param EmailFormRequest $request
* @param UserRepositoryInterface $repository
*
* @return Factory|RedirectResponse|Redirector
*/
public function postChangeEmail(EmailFormRequest $request, UserRepositoryInterface $repository): Factory | RedirectResponse | Redirector
public function postChangeEmail(EmailFormRequest $request, UserRepositoryInterface $repository): Factory|Redirector|RedirectResponse
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
@@ -384,7 +355,7 @@ class ProfileController extends Controller
$existing = $repository->findByEmail($newEmail);
if (null !== $existing) {
// force user logout.
Auth::guard()->logout(); // @phpstan-ignore-line (does not recognize function)
\Auth::guard()->logout(); // @phpstan-ignore-line (does not recognize function)
$request->session()->invalidate();
session()->flash('success', (string)trans('firefly.email_changed'));
@@ -398,7 +369,7 @@ class ProfileController extends Controller
event(new UserChangedEmail($user, $newEmail, $oldEmail));
// force user logout.
Auth::guard()->logout(); // @phpstan-ignore-line (does not recognize function)
\Auth::guard()->logout(); // @phpstan-ignore-line (does not recognize function)
$request->session()->invalidate();
session()->flash('success', (string)trans('firefly.email_changed'));
@@ -407,12 +378,8 @@ class ProfileController extends Controller
/**
* Change your email address.
*
* @param Request $request
*
* @return Factory|RedirectResponse|View
*/
public function changeEmail(Request $request): Factory | RedirectResponse | View
public function changeEmail(Request $request): Factory|RedirectResponse|View
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
@@ -431,10 +398,7 @@ class ProfileController extends Controller
/**
* Submit change password form.
*
* @param ProfileFormRequest $request
* @param UserRepositoryInterface $repository
*
* @return RedirectResponse|Redirector
* @return Redirector|RedirectResponse
*/
public function postChangePassword(ProfileFormRequest $request, UserRepositoryInterface $repository)
{
@@ -447,8 +411,10 @@ class ProfileController extends Controller
// the request has already validated both new passwords must be equal.
$current = $request->get('current_password');
$new = $request->get('new_password');
/** @var User $user */
$user = auth()->user();
try {
$this->validatePassword($user, $current, $new);
} catch (ValidationException $e) {
@@ -466,9 +432,7 @@ class ProfileController extends Controller
/**
* Change your password.
*
* @param Request $request
*
* @return Factory|RedirectResponse|Redirector|View
* @return Factory|Redirector|RedirectResponse|View
*/
public function changePassword(Request $request)
{
@@ -488,9 +452,8 @@ class ProfileController extends Controller
/**
* Submit 2FA for the first time.
*
* @param TokenFormRequest $request
* @return Redirector|RedirectResponse
*
* @return RedirectResponse|Redirector
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
@@ -505,6 +468,7 @@ class ProfileController extends Controller
/** @var User $user */
$user = auth()->user();
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$secret = app('preferences')->get('temp-mfa-secret')?->data;
@@ -532,7 +496,7 @@ class ProfileController extends Controller
// make sure MFA is logged out.
if ('testing' !== config('app.env')) {
Google2FA::logout();
\Google2FA::logout();
}
// drop all info from session:
@@ -542,9 +506,142 @@ class ProfileController extends Controller
}
/**
* TODO duplicate code.
* Submit delete account.
*
* @param string $mfaCode
* @return Redirector|RedirectResponse
*/
public function postDeleteAccount(UserRepositoryInterface $repository, DeleteAccountFormRequest $request)
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
if (!\Hash::check($request->get('password'), auth()->user()->password)) {
session()->flash('error', (string)trans('firefly.invalid_password'));
return redirect(route('profile.delete-account'));
}
/** @var User $user */
$user = auth()->user();
app('log')->info(sprintf('User #%d has opted to delete their account', auth()->user()->id));
// make repository delete user:
auth()->logout();
session()->flush();
$repository->destroy($user);
return redirect(route('index'));
}
/**
* @return Application|Redirector|RedirectResponse
*
* @throws AuthenticationException
*/
public function postLogoutOtherSessions(Request $request)
{
if (!$this->internalAuth) {
session()->flash('info', (string)trans('firefly.external_auth_disabled'));
return redirect(route('profile.index'));
}
$creds = [
'email' => auth()->user()->email,
'password' => $request->get('password'),
];
if (\Auth::once($creds)) {
\Auth::logoutOtherDevices($request->get('password'));
session()->flash('info', (string)trans('firefly.other_sessions_logged_out'));
return redirect(route('profile.index'));
}
session()->flash('error', (string)trans('auth.failed'));
return redirect(route('profile.index'));
}
/**
* Regenerate access token.
*
* @return Redirector|RedirectResponse
*
* @throws \Exception
*/
public function regenerate(Request $request)
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
/** @var User $user */
$user = auth()->user();
$token = $user->generateAccessToken();
app('preferences')->set('access_token', $token);
session()->flash('success', (string)trans('firefly.token_regenerated'));
return redirect(route('profile.index'));
}
/**
* Undo change of user email address.
*
* @return Redirector|RedirectResponse
*
* @throws FireflyException
*/
public function undoEmailChange(UserRepositoryInterface $repository, string $token, string $hash)
{
if (!$this->internalAuth) {
throw new FireflyException(trans('firefly.external_user_mgt_disabled'));
}
// find preference with this token value.
$set = app('preferences')->findByName('email_change_undo_token');
$user = null;
/** @var Preference $preference */
foreach ($set as $preference) {
if ($preference->data === $token) {
$user = $preference->user;
}
}
if (null === $user) {
throw new FireflyException('Invalid token.');
}
// found user.which email address to return to?
$set = app('preferences')->beginsWith($user, 'previous_email_');
/** @var string $match */
$match = null;
foreach ($set as $entry) {
$hashed = hash('sha256', sprintf('%s%s', (string)config('app.key'), $entry->data));
if ($hashed === $hash) {
$match = $entry->data;
break;
}
}
if (null === $match) {
throw new FireflyException('Invalid token.');
}
// change user back
// now actually update user:
$repository->changeEmail($user, $match);
$repository->unblockUser($user);
// return to login.
session()->flash('success', (string)trans('firefly.login_with_old_email'));
return redirect(route('login'));
}
/**
* TODO duplicate code.
*
* @throws FireflyException
* @throws ContainerExceptionInterface
@@ -585,144 +682,4 @@ class ProfileController extends Controller
}
app('preferences')->set('mfa_history', $newHistory);
}
/**
* Submit delete account.
*
* @param UserRepositoryInterface $repository
* @param DeleteAccountFormRequest $request
*
* @return RedirectResponse|Redirector
*/
public function postDeleteAccount(UserRepositoryInterface $repository, DeleteAccountFormRequest $request)
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
if (!Hash::check($request->get('password'), auth()->user()->password)) {
session()->flash('error', (string)trans('firefly.invalid_password'));
return redirect(route('profile.delete-account'));
}
/** @var User $user */
$user = auth()->user();
app('log')->info(sprintf('User #%d has opted to delete their account', auth()->user()->id));
// make repository delete user:
auth()->logout();
session()->flush();
$repository->destroy($user);
return redirect(route('index'));
}
/**
* @param Request $request
*
* @return Application|RedirectResponse|Redirector
* @throws AuthenticationException
*/
public function postLogoutOtherSessions(Request $request)
{
if (!$this->internalAuth) {
session()->flash('info', (string)trans('firefly.external_auth_disabled'));
return redirect(route('profile.index'));
}
$creds = [
'email' => auth()->user()->email,
'password' => $request->get('password'),
];
if (Auth::once($creds)) {
Auth::logoutOtherDevices($request->get('password'));
session()->flash('info', (string)trans('firefly.other_sessions_logged_out'));
return redirect(route('profile.index'));
}
session()->flash('error', (string)trans('auth.failed'));
return redirect(route('profile.index'));
}
/**
* Regenerate access token.
*
* @param Request $request
*
* @return RedirectResponse|Redirector
* @throws Exception
*/
public function regenerate(Request $request)
{
if (!$this->internalAuth) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
/** @var User $user */
$user = auth()->user();
$token = $user->generateAccessToken();
app('preferences')->set('access_token', $token);
session()->flash('success', (string)trans('firefly.token_regenerated'));
return redirect(route('profile.index'));
}
/**
* Undo change of user email address.
*
* @param UserRepositoryInterface $repository
* @param string $token
* @param string $hash
*
* @return RedirectResponse|Redirector
*
* @throws FireflyException
*/
public function undoEmailChange(UserRepositoryInterface $repository, string $token, string $hash)
{
if (!$this->internalAuth) {
throw new FireflyException(trans('firefly.external_user_mgt_disabled'));
}
// find preference with this token value.
$set = app('preferences')->findByName('email_change_undo_token');
$user = null;
/** @var Preference $preference */
foreach ($set as $preference) {
if ($preference->data === $token) {
$user = $preference->user;
}
}
if (null === $user) {
throw new FireflyException('Invalid token.');
}
// found user.which email address to return to?
$set = app('preferences')->beginsWith($user, 'previous_email_');
/** @var string $match */
$match = null;
foreach ($set as $entry) {
$hashed = hash('sha256', sprintf('%s%s', (string)config('app.key'), $entry->data));
if ($hashed === $hash) {
$match = $entry->data;
break;
}
}
if (null === $match) {
throw new FireflyException('Invalid token.');
}
// change user back
// now actually update user:
$repository->changeEmail($user, $match);
$repository->unblockUser($user);
// return to login.
session()->flash('success', (string)trans('firefly.login_with_old_email'));
return redirect(route('login'));
}
}