apply changes for api calls

This commit is contained in:
Charles 2026-02-25 09:21:06 +01:00
parent 9f430a3656
commit cad6a4f370
5 changed files with 225 additions and 28 deletions

View File

@ -34,6 +34,10 @@ security:
auth_token: auth_token:
pattern: ^/token pattern: ^/token
stateless: true stateless: true
api_m2m:
pattern: ^/api/v1/
stateless: true
oauth2: true
api: api:
pattern: ^/oauth/api pattern: ^/oauth/api
security: true security: true

View File

@ -178,18 +178,54 @@ class SsoAuthenticator extends OAuth2Authenticator implements AuthenticationEntr
**/ **/
if (!$user) { if (!$user) {
$user = new User(); $user = new User();
$user->setEmail($sudalysSsoUser->getEmail()); $user->setEmail($ssoData->getEmail());
$user->setName($sudalysSsoUser->getName()); $user->setPrenom($ssoData->getName());
$user->setSurname($sudalysSsoUser->getSurname()); $user->setNom($ssoData->getSurname());
$user->setSsoId($sudalysSsoUser->getId()); $user->setSsoId($ssoData->getId());
$this->em->persist($user); $this->em->persist($user);
}else{ }else{
// On met a jour l'utilisateur // On met a jour l'utilisateur
$user->setEmail($sudalysSsoUser->getEmail()); $user->setEmail($ssoData->getEmail());
$user->setName($sudalysSsoUser->getName()); $user->setPrenom($ssoData->getName());
$user->setSurname($sudalysSsoUser->getSurname()); $user->setNom($ssoData->getSurname());
$this->em->persist($user); $this->em->persist($user);
} }
//handle UOs links
$ssoArray = $ssoData->toArray();
$uoData = $ssoArray['uos'] ?? [];
foreach ($uoData as $uo) {
$ssoOrgId = $uo['id'];
$entity = $this->em->getRepository(Entity::class)->findOneBy(['ssoId' => $ssoOrgId]);
if (!$entity) {
$entity = new Entity();
$entity->setSsoId($ssoOrgId);
$entity->setNom($uo['name']);
$this->em->persist($entity);
}
$role = $this->em->getRepository(Roles::class)->findOneBy(['name' => $uo['role']]);
// Check if the user-organization link already exists
$existingLink = $this->em->getRepository(UsersOrganizations::class)->findOneBy([
'users' => $user,
'organizations' => $entity
]);
if (!$existingLink) {
// Create a new link if it doesn't exist
$newLink = new UsersOrganizations();
$newLink->setUsers($user);
$newLink->setOrganizations($entity);
$newLink->setRole($role);
$this->em->persist($newLink);
} else {
// Update the role if the link already exists
$existingLink->setRole($role);
$existingLink->setModifiedAt(new \DateTimeImmutable());
$this->em->persist($existingLink);
}
}
$this->em->flush(); $this->em->flush();
return $user; return $user;
} }

View File

@ -32,3 +32,138 @@ Get Access to the following with the following authorisations:
Organizations roles are specific to individual Organizations. They include: Organizations roles are specific to individual Organizations. They include:
- **Organization Admin**: Has full access to all organization features and settings. Can manage users of the organizations. - **Organization Admin**: Has full access to all organization features and settings. Can manage users of the organizations.
- **Organization User**: Has limited access to organization features and settings. Can view projects and applications, can manage own information - **Organization User**: Has limited access to organization features and settings. Can view projects and applications, can manage own information
# Set up
Like for the sso, we need to create roles in the system. create the following command and the create the roles.
``` php
#[AsCommand(
name: 'app:create-role',
description: 'Creates a new role in the database'
)]
class CreateRoleCommand extends Command
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
parent::__construct();
$this->entityManager = $entityManager;
}
protected function configure(): void
{
$this
->addArgument('name', InputArgument::REQUIRED, 'The name of the role'); // role name required
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$roleName = trim($input->getArgument('name'));
$roleName = strtoupper($roleName); // Normalize to uppercase
// Ensure not empty
if ($roleName === '') {
$output->writeln('<error>The role name cannot be empty</error>');
return Command::FAILURE;
}
// Check if role already exists
$existing = $this->entityManager->getRepository(Roles::class)
->findOneBy(['name' => $roleName]);
if ($existing) {
$output->writeln("<comment>Role '{$roleName}' already exists.</comment>");
return Command::SUCCESS; // not failure, just redundant
}
// Create and persist new role
$role = new Roles();
$role->setName($roleName);
$this->entityManager->persist($role);
$this->entityManager->flush();
$output->writeln("<info>Role '{$roleName}' created successfully!</info>");
return Command::SUCCESS;
}
}
```
```php
#[AsCommand(
name: 'app:delete-role',
description: 'Deletes a role from the database'
)]
class DeleteRoleCommand extends Command
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
parent::__construct();
$this->entityManager = $entityManager;
}
protected function configure(): void
{
$this
->addArgument('name', InputArgument::REQUIRED, 'The name of the role to delete');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$roleName = trim($input->getArgument('name'));
$roleName = strtoupper($roleName); // Normalize to uppercase
if ($roleName === '') {
$output->writeln('<error>The role name cannot be empty</error>');
return Command::FAILURE;
}
// Find the role
$role = $this->entityManager->getRepository(Roles::class)
->findOneBy(['name' => $roleName]);
if (!$role) {
$output->writeln("<error>Role '{$roleName}' not found.</error>");
return Command::FAILURE;
}
// Check if role is being used (optional safety check)
$usageCount = $this->entityManager->getRepository(\App\Entity\UsersOrganizations::class)
->count(['role' => $role]);
if ($usageCount > 0) {
$output->writeln("<error>Cannot delete role '{$roleName}' - it is assigned to {$usageCount} user(s).</error>");
$output->writeln('<comment>Remove all assignments first, then try again.</comment>');
return Command::FAILURE;
}
// Confirmation prompt
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion(
"Are you sure you want to delete role '{$roleName}'? [y/N] ",
false
);
if (!$helper->ask($input, $output, $question)) {
$output->writeln('<comment>Operation cancelled.</comment>');
return Command::SUCCESS;
}
// Delete the role
$this->entityManager->remove($role);
$this->entityManager->flush();
$output->writeln("<info>Role '{$roleName}' deleted successfully!</info>");
return Command::SUCCESS;
}
}
```
``` bash
php bin/console app:create-role USER
php bin/console app:create-role ADMIN
```

View File

@ -1,20 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Controller\api\Check;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
#[Route(path: '/api/v1/check', name: 'api_check_')]
class EasyCheckController extends AbstractController
{
#[Route('/easy-check')]
public function index(): Response
{
return $this->render('easy_check/index.html.twig');
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace App\Controller\api\v1\user;
use App\Entity\Roles;
use App\Entity\UsersOrganizations;
use App\Repository\RolesRepository;
use App\Repository\UserRepository;
use App\Repository\UsersOrganizationsRepository;
use App\Service\LoggerService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
#[Route(path: '/api/v1/users', name: 'api_v1_user_')]
class UserController extends AbstractController{
public function __construct(private readonly UsersOrganizationsRepository $uoRepository, private readonly LoggerService $loggerService, private readonly EntityManagerInterface $entityManager,)
{
}
/*Function that get all the users that a user is admin of*/
#[Route(path: '/admin/{id}', name: 'get_user_users', methods: ['GET'])]
public function getUserUsers($id, UserRepository $userRepository): JsonResponse
{
$result = [];
$user = $userRepository->find($id);
if (!$user) {
return $this->json(['error' => 'User not found'], 404);
}
$roleAdmin = $this->entityManager->getRepository(Roles::class)->findOneBy(['name' => 'ADMIN']);
$uos = $this->uoRepository->findBy(['user' => $user, 'role' => $roleAdmin]);
foreach ($uos as $uo) {
$result[] = [
'id' => $uo->getUsers()->getId(),
'name' => $uo->getUsers()->getName(),
'email' => $uo->getUsers()->getEmail(),
];
}
return $this->json($result);
}
}