Skip to content

Commit

Permalink
improved loading of associations
Browse files Browse the repository at this point in the history
  • Loading branch information
fiste788 committed Sep 13, 2024
1 parent 2b14f03 commit 783bb70
Show file tree
Hide file tree
Showing 8 changed files with 624 additions and 512 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"symfony/property-access": "^7.0",
"symfony/serializer": "^7.0",
"symfony/uid": "^7.0",
"web-auth/webauthn-lib": "^4.7",
"web-auth/webauthn-lib": "^5.0",
"web-token/jwt-library": "^4.0",
"whichbrowser/parser": "^2.1"
},
Expand Down
958 changes: 520 additions & 438 deletions composer.lock

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions src/Controller/Leagues/ChampionshipsController.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

declare(strict_types=1);

namespace App\Controller\Leagues;
Expand All @@ -13,6 +14,16 @@
*/
class ChampionshipsController extends AppController
{
/**
* Pagination
*
* @var array<string, mixed>
*/
protected array $paginate = [
'limit' => 1000,
'maxLimit' => 1000,
];

/**
* {@inheritDoc}
*
Expand Down Expand Up @@ -42,6 +53,7 @@ public function index(): ResponseInterface
$action = $this->Crud->action();
$action->findMethod(['byLeagueId' => [
'league_id' => (int)$this->request->getParam('league_id'),
'season' => $this->currentSeason
]]);

return $this->Crud->execute();
Expand Down
7 changes: 6 additions & 1 deletion src/Model/Table/ChampionshipsTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public function findByLeagueId(SelectQuery $query, mixed ...$args): SelectQuery
{
$teams = $this->RollOfHonors->Teams;

return $query->select(['id'])
$query = $query->select(['id', 'league_id'])
->select(['Seasons.id', 'Seasons.name'])
->contain(['Seasons', 'RollOfHonors' => function (SelectQuery $q) use ($teams): SelectQuery {
return $q->select(['championship_id', 'rank', 'points'])
Expand All @@ -154,5 +154,10 @@ public function findByLeagueId(SelectQuery $query, mixed ...$args): SelectQuery
->where([
'Championships.league_id' => $args['league_id'],
])->orderBy(['Seasons.year' => 'DESC']);

/** @var \App\Model\Entity\Season */
$season = $args['season'];

return !$season->ended ? $query->where(['Seasons.year <' => $season->year]) : $query;
}
}
80 changes: 40 additions & 40 deletions src/Model/Table/TeamsTable.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

declare(strict_types=1);

namespace App\Model\Table;
Expand Down Expand Up @@ -117,42 +118,42 @@ public function initialize(array $config): void
// defaults to `type`
],
'nameCallback' =>
function (
RepositoryInterface $_table,
EntityInterface $_entity,
UploadedFileInterface $file,
string $_field,
array $_settings
) {
return strtolower($file->getClientFilename() ?? (string)$_entity->get('id'));
},
function (
RepositoryInterface $_table,
EntityInterface $_entity,
UploadedFileInterface $file,
string $_field,
array $_settings
) {
return strtolower($file->getClientFilename() ?? (string)$_entity->get('id'));
},
'transformer' =>
function (
RepositoryInterface $_table,
EntityInterface $entity,
UploadedFileInterface $file,
string $_field,
array $_settings
) {
$tmpFileName = new SplFileInfo(
strtolower($file->getClientFilename() ?? (string)$entity->get('id') . '.jpg')
);
$tmpFile = tempnam(TMP, $tmpFileName->getFilename());
if ($tmpFile != false) {
$file->moveTo($tmpFile);
$image = Image::useImageDriver(ImageDriver::Gd)->load($tmpFile);
$array = [$tmpFile => $tmpFileName->getFilename()];
foreach (Team::$size as $value) {
if ($value < $image->getWidth()) {
$tmp = tempnam(TMP, (string)$value) . '.' . $tmpFileName->getExtension();
$image->width($value)->optimize()->save($tmp);
$array[$tmp] = $value . 'w' . DS . strtolower($tmpFileName->getFilename());
}
function (
RepositoryInterface $_table,
EntityInterface $entity,
UploadedFileInterface $file,
string $_field,
array $_settings
) {
$tmpFileName = new SplFileInfo(
strtolower($file->getClientFilename() ?? (string)$entity->get('id') . '.jpg')
);
$tmpFile = tempnam(TMP, $tmpFileName->getFilename());
if ($tmpFile != false) {
$file->moveTo($tmpFile);
$image = Image::useImageDriver(ImageDriver::Gd)->load($tmpFile);
$array = [$tmpFile => $tmpFileName->getFilename()];
foreach (Team::$size as $value) {
if ($value < $image->getWidth()) {
$tmp = tempnam(TMP, (string)$value) . '.' . $tmpFileName->getExtension();
$image->width($value)->optimize()->save($tmp);
$array[$tmp] = $value . 'w' . DS . strtolower($tmpFileName->getFilename());
}

return $array;
}
},

return $array;
}
},
'deleteCallback' => function (string $path, EntityInterface $entity, string $field, array $_settings) {
$array = [$path . (string)$entity->{$field}];
foreach (Team::$size as $value) {
Expand Down Expand Up @@ -273,12 +274,11 @@ public function saveWithoutUser(Team $team): void
*/
public function findTeamsOrdered(SelectQuery $query, mixed ...$args): SelectQuery
{
return $query->contain(['PushNotificationSubscriptions',
'EmailNotificationSubscriptions',
'Championships' => [
'Leagues',
'Seasons',
],
])->innerJoinWith('Championships.Seasons')->orderBy(['Seasons.year' => 'DESC']);
return $query->contain([
'Championships' => [
'Leagues',
'Seasons',
],
])->innerJoinWith('Championships.Seasons')->orderBy(['Seasons.year' => 'DESC']);
}
}
27 changes: 16 additions & 11 deletions src/Model/Table/UsersTable.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

declare(strict_types=1);

namespace App\Model\Table;
Expand Down Expand Up @@ -150,17 +151,21 @@ public function buildRules(RulesChecker $rules): RulesChecker
*/
public function findAuth(SelectQuery $query, mixed ...$args): SelectQuery
{
$query
->contain(['Teams' => [
'PushNotificationSubscriptions',
'EmailNotificationSubscriptions',
'Championships' => [
'Leagues',
'Seasons',
],
]])
return $query
->contain(['Teams' => function (SelectQuery $q): SelectQuery {
return $q->select(['id', 'name', 'user_id', 'championship_id'])
->contain([
'Championships' => function (SelectQuery $q): SelectQuery {
return $q->select(['id', 'league_id', 'season_id', 'started'])
->select($this->Teams->Championships->Leagues)
->select($this->Teams->Championships->Seasons)
->contain([
'Leagues',
'Seasons',
]);
}
]);
}])
->where(['Users.active' => 1]);

return $query;
}
}
3 changes: 2 additions & 1 deletion src/Policy/ChampionshipPolicy.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

declare(strict_types=1);

namespace App\Policy;
Expand Down Expand Up @@ -53,6 +54,6 @@ public function canDelete(IdentityInterface $user, Championship $championship):
*/
public function canIndex(IdentityInterface $user, Championship $championship): bool
{
return $user->admin;
return $user->isInLeague($championship->league_id);
}
}
47 changes: 27 additions & 20 deletions src/Service/WebauthnService.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
use Cose\Algorithms;
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Uid\Uuid;
use Webauthn\AttestationStatement\AndroidKeyAttestationStatementSupport;
Expand All @@ -35,6 +37,7 @@
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\AuthenticatorAttestationResponseValidator;
use Webauthn\AuthenticatorSelectionCriteria;
use Webauthn\CeremonyStep\CeremonyStepManagerFactory;
use Webauthn\Denormalizer\WebauthnSerializerFactory;
use Webauthn\PublicKeyCredential;
use Webauthn\PublicKeyCredentialCreationOptions;
Expand All @@ -48,7 +51,6 @@
/**
* Credentials Repo
*
* @property \App\Service\PublicKeyCredentialSourceRepositoryService $PublicKeyCredentialSourceRepository
*/
#[AllowDynamicProperties]
class WebauthnService
Expand All @@ -60,7 +62,7 @@ class WebauthnService

protected AuthenticatorAssertionResponseValidator $authenticatorAssertionResponseValidator;

protected PublicKeyCredentialSourceRepositoryService $PublicKeyCredentialSourceRepository;
// protected PublicKeyCredentialSourceRepositoryService $PublicKeyCredentialSourceRepository;

public SerializerInterface $serializer;

Expand All @@ -73,25 +75,24 @@ class WebauthnService
*/
public function __construct()
{
$this->loadService('PublicKeyCredentialSourceRepository');
// $this->loadService('PublicKeyCredentialSourceRepository');
$attestationStatementSupportManager = $this->createStatementSupportManager();

$factory = new WebauthnSerializerFactory($attestationStatementSupportManager);
$this->serializer = $factory->create();

$csmFactory = new CeremonyStepManagerFactory();

$creationCSM = $csmFactory->creationCeremony();
$requestCSM = $csmFactory->requestCeremony();

$this->authenticatorAttestationResponseValidator = new AuthenticatorAttestationResponseValidator(
$attestationStatementSupportManager,
$this->PublicKeyCredentialSourceRepository,
null,
new ExtensionOutputCheckerHandler()
$creationCSM
);

// Authenticator Assertion Response Validator
$this->authenticatorAssertionResponseValidator = new AuthenticatorAssertionResponseValidator(
$this->PublicKeyCredentialSourceRepository,
null,
new ExtensionOutputCheckerHandler(),
$this->createAlgorithManager()
$requestCSM,
);
}

Expand Down Expand Up @@ -218,6 +219,7 @@ public function signinRequest(ServerRequestInterface $request): ?PublicKeyCreden
$user = $this->fetchTable('Users')->find()->where(['email' => $params['email']])->first();
if ($user != null) {
$credentialUser = $user->toCredentialUserEntity();

$credentials = $this->PublicKeyCredentialSourceRepository->findAllForUserEntity($credentialUser);
$allowedCredentials = $this->credentialsToDescriptors($credentials);
$request->getSession()->write('User.Handle', $credentialUser->id);
Expand Down Expand Up @@ -340,6 +342,9 @@ public function registerRequest(ServerRequestInterface $request): PublicKeyCrede
$user = $request->getAttribute('identity');
$userEntity = $user->toCredentialUserEntity();

/** @var \App\Model\Table\PublicKeyCredentialSourcesTable $publicKeyCredentialSourcesTable */
$publicKeyCredentialSourcesTable = $this->fetchTable('PublicKeyCredentialSources');
$credential = $publicKeyCredentialSourcesTable->newEmptyEntity();
$credential = $this->PublicKeyCredentialSourceRepository->findAllForUserEntity($userEntity);
$excludeCredentials = $this->credentialsToDescriptors($credential);

Expand All @@ -353,8 +358,7 @@ public function registerRequest(ServerRequestInterface $request): PublicKeyCrede
$authenticatorSelectionCriteria = AuthenticatorSelectionCriteria::create(
AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_PLATFORM,
AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED,
AuthenticatorSelectionCriteria::RESIDENT_KEY_REQUIREMENT_PREFERRED,
true
AuthenticatorSelectionCriteria::RESIDENT_KEY_REQUIREMENT_PREFERRED
);
//$authenticatorSelectionCriteria = new AuthenticatorSelectionCriteria();

Expand All @@ -369,15 +373,18 @@ public function registerRequest(ServerRequestInterface $request): PublicKeyCrede
60_000
);

$jsonObject = $this->serializer->serialize(
$publicKeyCredentialCreationOptions,
'json',
[ // Optional
AbstractObjectNormalizer::SKIP_NULL_VALUES => true,
JsonEncode::OPTIONS => JSON_THROW_ON_ERROR,
]
);

$session = $request->getSession();
$session->start();
$session->write(
'User.PublicKey',
json_encode(
$publicKeyCredentialCreationOptions,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
)
);
$session->write('User.PublicKey', $jsonObject);

return $publicKeyCredentialCreationOptions;
}
Expand Down

0 comments on commit 783bb70

Please sign in to comment.