feat: encrypted user passwords

This commit is contained in:
Björn Fromme
2025-04-24 12:26:42 +02:00
parent 5fe88fc0f2
commit fb6665668b
16 changed files with 292 additions and 79 deletions
+1
View File
@@ -20,6 +20,7 @@
"nesbot/carbon": "^3.8", "nesbot/carbon": "^3.8",
"phpdocumentor/reflection-docblock": "^5.6", "phpdocumentor/reflection-docblock": "^5.6",
"phpstan/phpdoc-parser": "^2.0", "phpstan/phpdoc-parser": "^2.0",
"spatie/crypto": "^2.1",
"symfony/apache-pack": "^1.0", "symfony/apache-pack": "^1.0",
"symfony/asset": "6.4.*", "symfony/asset": "6.4.*",
"symfony/console": "6.4.*", "symfony/console": "6.4.*",
Generated
+62 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "75a72111cb05768e7e978a7161b2e0e5", "content-hash": "6fcf6eb198ed84c9f95609ce613497e0",
"packages": [ "packages": [
{ {
"name": "carbonphp/carbon-doctrine-types", "name": "carbonphp/carbon-doctrine-types",
@@ -2962,6 +2962,67 @@
}, },
"time": "2024-09-11T13:17:53+00:00" "time": "2024-09-11T13:17:53+00:00"
}, },
{
"name": "spatie/crypto",
"version": "2.1.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/crypto.git",
"reference": "9bda7d690ffa6a8884a8af69da2dba942bbac4eb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/crypto/zipball/9bda7d690ffa6a8884a8af69da2dba942bbac4eb",
"reference": "9bda7d690ffa6a8884a8af69da2dba942bbac4eb",
"shasum": ""
},
"require": {
"ext-openssl": "*",
"php": "^7.4|^8.0"
},
"require-dev": {
"phpunit/phpunit": "^9.3",
"symfony/var-dumper": "^5.1"
},
"type": "library",
"autoload": {
"psr-4": {
"Spatie\\Crypto\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "[email protected]",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "Encrypting and signing data using private/public keys",
"homepage": "https://github.com/spatie/crypto",
"keywords": [
"crypto",
"spatie"
],
"support": {
"source": "https://github.com/spatie/crypto/tree/2.1.0"
},
"funding": [
{
"url": "https://github.com/sponsors/spatie",
"type": "github"
},
{
"url": "https://spatie.be/open-source/support-us",
"type": "other"
}
],
"time": "2024-06-20T08:24:56+00:00"
},
{ {
"name": "symfony/apache-pack", "name": "symfony/apache-pack",
"version": "v1.0.1", "version": "v1.0.1",
+2
View File
@@ -0,0 +1,2 @@
*.key
!.gitignore
+9
View File
@@ -5,6 +5,7 @@
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration # https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
parameters: parameters:
travel_info_base_url: '%env(APP_TRAVEL_INFO_BASE_URL)%' travel_info_base_url: '%env(APP_TRAVEL_INFO_BASE_URL)%'
path_to_keys: '%kernel.project_dir%/config/secret'
services: services:
# default configuration for services in *this* file # default configuration for services in *this* file
@@ -51,3 +52,11 @@ services:
- name: knp_menu.menu_builder - name: knp_menu.menu_builder
method: createMainMenu method: createMainMenu
alias: main alias: main
App\Command\GenerateKeysCommand:
arguments:
$path: '%path_to_keys%'
App\Security\Crypt:
arguments:
$path: '%path_to_keys%'
+5 -3
View File
@@ -4,9 +4,9 @@ namespace App\BusProNet\Security;
use App\BusProNet\ApiClient; use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Exception\ResponseParserException;
use App\BusProNet\Model\CrmAttributes; use App\BusProNet\Model\CrmAttributes;
use App\BusProNet\Model\PersonalData; use App\BusProNet\Model\PersonalData;
use App\Security\Crypt;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -27,6 +27,7 @@ class Authenticator extends AbstractLoginFormAuthenticator implements Authentica
public function __construct( public function __construct(
private readonly UrlGeneratorInterface $urlGenerator, private readonly UrlGeneratorInterface $urlGenerator,
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -46,7 +47,7 @@ class Authenticator extends AbstractLoginFormAuthenticator implements Authentica
try { try {
$response = $this->apiClient->getPersonalData($email, $password); $response = $this->apiClient->getPersonalData($email, $password);
} catch (ApiClientException|ResponseParserException $e) { } catch (ApiClientException $e) {
throw new CustomUserMessageAuthenticationException($e->getMessage()); throw new CustomUserMessageAuthenticationException($e->getMessage());
} }
@@ -60,7 +61,8 @@ class Authenticator extends AbstractLoginFormAuthenticator implements Authentica
new UserBadge($email, function () use ($email, $password, $response, $request) { new UserBadge($email, function () use ($email, $password, $response, $request) {
$crmAttributes = $this->apiClient->getCrmAttributes($email, $password); $crmAttributes = $this->apiClient->getCrmAttributes($email, $password);
$roles = $this->collectRoles($crmAttributes); $roles = $this->collectRoles($crmAttributes);
$user = new User($email, $response->personId, $response->addressId, $password, $roles); $encryptedPassword = $this->crypt->encrypt($password);
$user = new User($email, $response->personId, $response->addressId, $encryptedPassword, $roles);
$request->getSession()->set('bpn_user', $user); $request->getSession()->set('bpn_user', $user);
+2 -2
View File
@@ -40,7 +40,7 @@ class User implements UserInterface
return ['ROLE_USER', ...$this->roles]; return ['ROLE_USER', ...$this->roles];
} }
public function eraseCredentials() public function eraseCredentials(): void
{ {
} }
@@ -48,4 +48,4 @@ class User implements UserInterface
{ {
return $this->email; return $this->email;
} }
} }
+15 -6
View File
@@ -5,6 +5,8 @@ namespace App\BusProNet\Security;
use App\BusProNet\ApiClient; use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\PersonalData; use App\BusProNet\Model\PersonalData;
use App\Controller\Traits\CredentialsTrait;
use App\Security\Crypt;
use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Exception\UserNotFoundException; use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserInterface;
@@ -12,14 +14,19 @@ use Symfony\Component\Security\Core\User\UserProviderInterface;
class UserProvider implements UserProviderInterface class UserProvider implements UserProviderInterface
{ {
public function __construct(private readonly ApiClient $apiClient, private readonly RequestStack $requestStack) use CredentialsTrait;
{
public function __construct(
private readonly ApiClient $apiClient,
private readonly RequestStack $requestStack,
private readonly Crypt $crypt,
) {
} }
public function refreshUser(UserInterface $user): UserInterface public function refreshUser(UserInterface $user): UserInterface
{ {
if (null !== $activeUuser = $this->requestStack->getSession()->get('bpn_user')) { if (null !== $activeUser = $this->requestStack->getSession()->get('bpn_user')) {
return $activeUuser; return $activeUser;
} }
return $this->loadUserByIdentifier($user->getUserIdentifier()); return $this->loadUserByIdentifier($user->getUserIdentifier());
@@ -37,7 +44,9 @@ class UserProvider implements UserProviderInterface
} }
try { try {
$response = $this->apiClient->getPersonalData($activeUser->getEmail(), $activeUser->getPassword()); $email = $activeUser->getEmail();
$password = $this->crypt->decrypt($activeUser->getPassword());
$response = $this->apiClient->getPersonalData($email, $password);
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
throw new UserNotFoundException(); throw new UserNotFoundException();
} }
@@ -48,4 +57,4 @@ class UserProvider implements UserProviderInterface
return $activeUser; return $activeUser;
} }
} }
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Command;
use Spatie\Crypto\Rsa\KeyPair;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:crypto:generate-keys', description: 'Generate keypair for encryption')]
class GenerateKeysCommand extends Command
{
public function __construct(private readonly string $path)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
(new KeyPair())->generate($this->path.'/private.key', $this->path.'/public.key');
return Command::SUCCESS;
}
}
+28 -11
View File
@@ -5,22 +5,29 @@ namespace App\Controller\Booking;
use App\BusProNet\ApiClient; use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification; use App\BusProNet\Model\Notification;
use App\BusProNet\Security\User;
use App\Controller\Traits\BookingDataTrait;
use App\Controller\Traits\CredentialsTrait;
use App\Security\Crypt;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted; use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Contracts\Cache\CacheInterface;
use function Symfony\Component\String\u; use function Symfony\Component\String\u;
class DownloadController extends AbstractController class DownloadController extends AbstractController
{ {
use CredentialsTrait;
use BookingDataTrait;
public function __construct( public function __construct(
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly Security $security, private readonly CacheInterface $cache,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -38,13 +45,12 @@ class DownloadController extends AbstractController
defaults: ['fileType' => 'invoice'] defaults: ['fileType' => 'invoice']
)] )]
#[IsGranted("ROLE_USER")] #[IsGranted("ROLE_USER")]
public function documents(int $id, string $fileType, Request $request): Response public function documents(int $id, string $fileType): Response
{ {
$bpnUser = $request->getSession()->get('bpn_user'); /** @var User $user */
$user = $this->getUser();
if (null === $bpnUser) { $email = $user->getEmail();
return $this->security->logout(); $password = $this->crypt->decrypt($user->getPassword());
}
$type = match ($fileType) { $type = match ($fileType) {
'documents' => 'Dokumentdruck', 'documents' => 'Dokumentdruck',
@@ -52,15 +58,26 @@ class DownloadController extends AbstractController
}; };
$this->logger->info('Initiated document download', [ $this->logger->info('Initiated document download', [
'email' => $bpnUser->getEmail(), 'email' => $email,
'document_type' => $fileType, 'document_type' => $fileType,
'booking_id' => $id, 'booking_id' => $id,
]); ]);
// Fetch booking data via API and cache result for a short ttl to check permissions
$bookingData = $this->fetchBookingData($email, $password, $id);
if (null === $bookingData || $bookingData instanceof Notification) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return $this->redirectToRoute('app_bookings');
}
$this->denyAccessUnlessGranted('VIEW', $bookingData);
try { try {
$file = $this $file = $this
->apiClient ->apiClient
->getDocuments($bpnUser->getEmail(), $bpnUser->getPassword(), $id, $type); ->getDocuments($email, $password, $id, $type);
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$file = null; $file = null;
} }
+21 -22
View File
@@ -4,12 +4,15 @@ namespace App\Controller\Booking;
use App\BusProNet\ApiClient; use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Exception\ResponseParserException;
use App\BusProNet\Model\Notification; use App\BusProNet\Model\Notification;
use App\BusProNet\Security\User;
use App\BusProNet\XmlLoader\PickupLoader; use App\BusProNet\XmlLoader\PickupLoader;
use App\BusProNet\XmlLoader\TravelLoader; use App\BusProNet\XmlLoader\TravelLoader;
use App\Controller\Traits\BookingDataTrait;
use App\Controller\Traits\CredentialsTrait;
use App\Form\BookingType; use App\Form\BookingType;
use App\Form\Model\BookingData; use App\Form\Model\BookingData;
use App\Security\Crypt;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@@ -19,16 +22,19 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted; use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
class EditController extends AbstractController class EditController extends AbstractController
{ {
use CredentialsTrait;
use BookingDataTrait;
public function __construct( public function __construct(
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly TravelLoader $travelDataLoader, private readonly TravelLoader $travelDataLoader,
private readonly PickupLoader $pickupDataLoader, private readonly PickupLoader $pickupDataLoader,
private readonly CacheInterface $cache, private readonly CacheInterface $cache,
private readonly Security $security, private readonly Security $security,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -37,30 +43,22 @@ class EditController extends AbstractController
#[IsGranted("ROLE_USER")] #[IsGranted("ROLE_USER")]
public function edit(int $id, Request $request): Response public function edit(int $id, Request $request): Response
{ {
$bpnUser = $request->getSession()->get('bpn_user'); /** @var User $user */
$user = $this->getUser();
$email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
if (null === $bpnUser) { // Fetch original booking data via API and cache result for a short ttl
return $this->security->logout(); $bookingData = $this->fetchBookingData($email, $password, $id);
}
// Fetch original bookingData data via API and cache result for a short ttl if (null === $bookingData || $bookingData instanceof Notification) {
$cacheKey = sprintf('bpn_booking_%d', $id);
try {
$bookingData = $this->cache->get($cacheKey, function (ItemInterface $item) use ($bpnUser, $id) {
$item->expiresAfter(300);
return $this->apiClient->getBooking($bpnUser->getEmail(), $bpnUser->getPassword(), $id);
});
} catch (InvalidArgumentException $e) {
$bookingData = null;
}
if (null === $bookingData) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar'); $this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return $this->redirectToRoute('app_bookings'); return $this->redirectToRoute('app_bookings');
} }
$this->denyAccessUnlessGranted('EDIT', $bookingData);
// Load according travel data // Load according travel data
$travelData = $this->travelDataLoader->loadById($bookingData->travelId); $travelData = $this->travelDataLoader->loadById($bookingData->travelId);
@@ -104,7 +102,7 @@ class EditController extends AbstractController
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$this->logger->info('Initiated booking update', [ $this->logger->info('Initiated booking update', [
'email' => $bpnUser->getEmail(), 'email' => $email,
'booking_id' => $id, 'booking_id' => $id,
]); ]);
@@ -117,12 +115,13 @@ class EditController extends AbstractController
$this->addFlash('info', $response->message); $this->addFlash('info', $response->message);
} }
$this->logger->error('Booking update not successful', [ $this->logger->error('Booking update not successful', [
'email' => $bpnUser->getEmail(), 'email' => $email,
'booking_id' => $id, 'booking_id' => $id,
'message' => $response->message, 'message' => $response->message,
]); ]);
} else { } else {
try { try {
$cacheKey = sprintf('bpn_booking_%d', $id);
$this->cache->delete($cacheKey); $this->cache->delete($cacheKey);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
} }
@@ -130,7 +129,7 @@ class EditController extends AbstractController
$this->addFlash('success', 'Buchung erfolgreich aktualisiert'); $this->addFlash('success', 'Buchung erfolgreich aktualisiert');
$this->logger->info('Booking update successful', [ $this->logger->info('Booking update successful', [
'email' => $bpnUser->getEmail(), 'email' => $email,
'booking_id' => $id, 'booking_id' => $id,
]); ]);
+12 -8
View File
@@ -6,10 +6,12 @@ use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\BaseData; use App\BusProNet\Model\BaseData;
use App\BusProNet\Model\Notification; use App\BusProNet\Model\Notification;
use App\BusProNet\Security\User;
use App\BusProNet\XmlLoader\TravelLoader; use App\BusProNet\XmlLoader\TravelLoader;
use App\Controller\Traits\CredentialsTrait;
use App\Security\Crypt;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
@@ -17,10 +19,12 @@ use Symfony\Component\Security\Http\Attribute\IsGranted;
class IndexController extends AbstractController class IndexController extends AbstractController
{ {
use CredentialsTrait;
public function __construct( public function __construct(
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly TravelLoader $travelDataLoader, private readonly TravelLoader $travelDataLoader,
private readonly Security $security, private readonly Crypt $crypt,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -29,14 +33,13 @@ class IndexController extends AbstractController
#[IsGranted("ROLE_USER")] #[IsGranted("ROLE_USER")]
public function index(Request $request): Response public function index(Request $request): Response
{ {
$bpnUser = $request->getSession()->get('bpn_user'); /** @var User $user */
$user = $this->getUser();
if (null === $bpnUser) { $email = $user->getEmail();
return $this->security->logout(); $password = $this->crypt->decrypt($user->getPassword());
}
try { try {
$bookings = $this->apiClient->getBookings($bpnUser->getEmail(), $bpnUser->getPassword()); $bookings = $this->apiClient->getBookings($email, $password);
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$this->addFlash('error', 'Buchungen nicht abrufbar'); $this->addFlash('error', 'Buchungen nicht abrufbar');
$bookings = new BaseData([]); $bookings = new BaseData([]);
@@ -44,6 +47,7 @@ class IndexController extends AbstractController
if ($bookings instanceof Notification) { if ($bookings instanceof Notification) {
$this->logger->error('Unable to fetch bookings data', [ $this->logger->error('Unable to fetch bookings data', [
'email' => $email,
'code' => $bookings->code, 'code' => $bookings->code,
'error' => $bookings->message, 'error' => $bookings->message,
]); ]);
+21 -19
View File
@@ -6,10 +6,12 @@ use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification; use App\BusProNet\Model\Notification;
use App\BusProNet\Model\PersonalData; use App\BusProNet\Model\PersonalData;
use App\BusProNet\Security\User;
use App\Controller\Traits\CredentialsTrait;
use App\Form\PersonalDataType; use App\Form\PersonalDataType;
use App\Security\Crypt;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
@@ -17,9 +19,11 @@ use Symfony\Component\Security\Http\Attribute\IsGranted;
class PersonalDataController extends AbstractController class PersonalDataController extends AbstractController
{ {
use CredentialsTrait;
public function __construct( public function __construct(
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly Security $security, private readonly Crypt $crypt,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -28,16 +32,15 @@ class PersonalDataController extends AbstractController
#[IsGranted('ROLE_USER')] #[IsGranted('ROLE_USER')]
public function index(Request $request): Response public function index(Request $request): Response
{ {
$bpnUser = $request->getSession()->get('bpn_user'); /** @var User $user */
$user = $this->getUser();
if (null === $bpnUser) { $email = $user->getEmail();
return $this->security->logout(); $password = $this->crypt->decrypt($user->getPassword());
}
try { try {
$personalData = $this $personalData = $this
->apiClient ->apiClient
->getPersonalData($bpnUser->getEmail(), $bpnUser->getPassword()); ->getPersonalData($email, $password);
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$this->addFlash('error', 'Deine persönlichen Daten konnten nicht abgerufen werden'); $this->addFlash('error', 'Deine persönlichen Daten konnten nicht abgerufen werden');
$personalData = new PersonalData(); $personalData = new PersonalData();
@@ -61,10 +64,10 @@ class PersonalDataController extends AbstractController
if ($personalDataForm->isSubmitted() && $personalDataForm->isValid()) { if ($personalDataForm->isSubmitted() && $personalDataForm->isValid()) {
try { try {
$this->apiClient->updatePersonalData($bpnUser->getEmail(), $bpnUser->getPassword(), $personalData); $this->apiClient->updatePersonalData($email, $password, $personalData);
$this->addFlash('success', 'Deine persönlichen Daten wurden aktualisiert'); $this->addFlash('success', 'Deine persönlichen Daten wurden aktualisiert');
$this->logger->info('Updated personal data', [ $this->logger->info('Updated personal data', [
'email' => $bpnUser->getEmail(), 'email' => $user->getEmail(),
]); ]);
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$this->addFlash('error', $e->getMessage()); $this->addFlash('error', $e->getMessage());
@@ -81,18 +84,17 @@ class PersonalDataController extends AbstractController
#[Route('/personal-data/newsletter', name: 'app_personal_data_newsletter', methods: ['POST'])] #[Route('/personal-data/newsletter', name: 'app_personal_data_newsletter', methods: ['POST'])]
#[IsGranted('ROLE_USER')] #[IsGranted('ROLE_USER')]
public function newsletter(Request $request): Response public function newsletter(): Response
{ {
$bpnUser = $request->getSession()->get('bpn_user'); /** @var User $user */
$user = $this->getUser();
if (null === $bpnUser) { $email = $user->getEmail();
return $this->security->logout(); $password = $this->crypt->decrypt($user->getPassword());
}
try { try {
$personalData = $this $personalData = $this
->apiClient ->apiClient
->getPersonalData($bpnUser->getEmail(), $bpnUser->getPassword()); ->getPersonalData($email, $password);
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$this->addFlash('error', 'Deine persönlichen Daten konnten nicht abgerufen werden'); $this->addFlash('error', 'Deine persönlichen Daten konnten nicht abgerufen werden');
$personalData = new PersonalData(); $personalData = new PersonalData();
@@ -101,10 +103,10 @@ class PersonalDataController extends AbstractController
$personalData->communication->newsletter = !$personalData->communication->newsletter; $personalData->communication->newsletter = !$personalData->communication->newsletter;
try { try {
$this->apiClient->updateNewsletterRegistration($bpnUser->getEmail(), $bpnUser->getPassword(), $personalData); $this->apiClient->updateNewsletterRegistration($email, $password, $personalData);
$this->addFlash('success', 'Deine Anmeldung zum Newsletter wurde aktualisiert'); $this->addFlash('success', 'Deine Anmeldung zum Newsletter wurde aktualisiert');
$this->logger->info('Updated newsletter registration', [ $this->logger->info('Updated newsletter registration', [
'email' => $bpnUser->getEmail(), 'email' => $user->getEmail(),
]); ]);
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$this->addFlash('error', $e->getMessage()); $this->addFlash('error', $e->getMessage());
@@ -0,0 +1,28 @@
<?php
namespace App\Controller\Traits;
use App\BusProNet\Model\Booking;
use App\BusProNet\Model\Notification;
use Psr\Cache\InvalidArgumentException;
use Symfony\Contracts\Cache\ItemInterface;
trait BookingDataTrait
{
public function fetchBookingData(string $email, string $password, int $id): Booking|Notification|null
{
// Fetch booking data via API and cache result for a short ttl to check permissions
$cacheKey = sprintf('bpn_booking_%d', $id);
try {
$bookingData = $this->cache->get($cacheKey, function (ItemInterface $item) use ($email, $password, $id) {
$item->expiresAfter(300);
return $this->apiClient->getBooking($email, $password, $id);
});
} catch (InvalidArgumentException $e) {
$bookingData = null;
}
return $bookingData;
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Controller\Traits;
use App\BusProNet\Security\User;
use App\Security\Crypt;
trait CredentialsTrait
{
public function getPasswordPlain(User $bpnUser, string $pathToKeys): string
{
$crypt = new Crypt($pathToKeys);
return $crypt->decrypt($bpnUser->getPassword());
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Security;
use Spatie\Crypto\Rsa\PrivateKey;
use Spatie\Crypto\Rsa\PublicKey;
class Crypt
{
public function __construct(private readonly string $path)
{
}
public function encrypt(string $message): string
{
$privateKey = PrivateKey::fromFile($this->path . '/private.key');
return $privateKey->encrypt($message);
}
public function decrypt(string $message): string
{
$publicKey = PublicKey::fromFile($this->path . '/public.key');
return $publicKey->decrypt($message);
}
public function sign(string $message): string
{
$privateKey = PrivateKey::fromFile($this->path . '/private.key');
return $privateKey->sign($message);
}
public function verify(string $message, string $signature): bool
{
$publicKey = PublicKey::fromFile($this->path . '/public.key');
return $publicKey->verify($message, $signature);
}
}
+4 -7
View File
@@ -3,7 +3,7 @@
namespace App\Security\Voter; namespace App\Security\Voter;
use App\BusProNet\Model\Booking; use App\BusProNet\Model\Booking;
use Symfony\Component\HttpFoundation\RequestStack; use App\BusProNet\Security\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter; use Symfony\Component\Security\Core\Authorization\Voter\Voter;
@@ -12,10 +12,6 @@ class BookingVoter extends Voter
public const VIEW = 'VIEW'; public const VIEW = 'VIEW';
public const EDIT = 'EDIT'; public const EDIT = 'EDIT';
public function __construct(private readonly RequestStack $requestStack)
{
}
protected function supports(string $attribute, mixed $subject): bool protected function supports(string $attribute, mixed $subject): bool
{ {
if (false === in_array($attribute, [self::VIEW, self::EDIT])) { if (false === in_array($attribute, [self::VIEW, self::EDIT])) {
@@ -27,7 +23,8 @@ class BookingVoter extends Voter
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{ {
$bpnUser = $this->requestStack->getSession()->get('bpn_user'); /** @var User $bpnUser */
$bpnUser = $token->getUser();
if (null === $bpnUser) { if (null === $bpnUser) {
return false; return false;
@@ -42,4 +39,4 @@ class BookingVoter extends Voter
return $booking->isEditable(); return $booking->isEditable();
} }
} }