Easy_solution/src/Controller/UserController.php

383 lines
17 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\Apps;
use App\Entity\Organizations;
use App\Entity\Roles;
use App\Entity\User;
use App\Entity\UserOrganizatonApp;
use App\Entity\UsersOrganizations;
use App\Form\UserForm;
use App\Service\ActionService;
use App\Service\AwsService;
use App\Service\UserOrganizationAppService;
use App\Service\UserOrganizationService;
use App\Service\UserService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Asset\Packages;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
#[Route(path: '/user', name: 'user_')]
class UserController extends AbstractController
{
private const NOT_FOUND = 'Entity not found';
private const ACCESS_DENIED = 'Access denied';
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly UserService $userService,
private readonly ActionService $actionService,
private readonly UserOrganizationAppService $userOrganizationAppService,
private readonly UserOrganizationService $userOrganizationService,
)
{
}
#[Route('/', name: 'index', methods: ['GET'])]
public function index(): Response
{
$this->denyAccessUnlessGranted('ROLE_USER');
$user = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->isGranted('ROLE_SUPER_ADMIN')) {
$uo = $this->entityManager->getRepository(UsersOrganizations::class)->findUsersWithOrganization();
$noOrgUsers = $this->userService->formatNoOrgUsersAsAssoc(
$this->entityManager->getRepository(User::class)->findUsersWithoutOrganization());
$usersByOrganization = $this->userService->groupByOrganization($uo);
$usersByOrganization += $noOrgUsers;
//Log action
$this->actionService->createAction("View all users", $user, null, "All");
} elseif ($this->isGranted('ROLE_ADMIN')) {
$orgIds = $this->userService->getAdminOrganizationsIds($user);
if (empty($orgIds)) {
$usersByOrganization = [];
} else {
$uo = $this->entityManager->getRepository(UsersOrganizations::class)->findUsersWithOrganization($orgIds);
$usersByOrganization = $this->userService->groupByOrganization($uo);
$this->actionService->createAction("View all users for organizations", $user, null, implode(", ", $orgIds));
}
} else {
$usersByOrganization = [];
}
return $this->render('user/index.html.twig', [
'usersByOrganization' => $usersByOrganization,
]);
}
#[Route('/view/{id}', name: 'show', methods: ['GET'])]
public function view(int $id, Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_USER');
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->userService->hasAccessTo($actingUser)) {
$user = $this->entityManager->getRepository(User::class)->find($id);
try {
$orgId = $request->query->get('organizationId');
if ($orgId) {
$orgs = $this->entityManager->getRepository(Organizations::class)->findBy(['id' => $orgId]);
$uo = $this->entityManager->getRepository(UsersOrganizations::class)->findBy(['users' => $user, 'organization' => $orgs]);
if (!$uo) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$uoActive = $uo[0]->isActive();
} else {
$uo = $this->entityManager->getRepository(UsersOrganizations::class)->findBy(['users' => $user, 'isActive' => true]);
foreach ($uo as $u) {
$orgs[] = $u->getOrganization();
}
}
$uoa = $this->entityManager->getRepository(UserOrganizatonApp::class)->findBy(['userOrganization' => $uo, 'isActive' => true]);
$uoas = $this->userOrganizationAppService->groupUserOrganizationAppsByApplication($uoa);
$this->actionService->createAction("View user information", $actingUser, null, $user->getUserIdentifier());
} catch (\Exception $e) {
//ignore
}
} else {
throw $this->createAccessDeniedException(self::ACCESS_DENIED);
}
return $this->render('user/show.html.twig', [
'user' => $user,
'uoas' => $uoas ?? null,
'orgs' => $orgs ?? null,
'organizationId' => $orgId ?? null,
'uoActive' => $uoActive ?? null// specific for single organization context and deactivate user from said org
]);
}
#[Route('/edit/{id}', name: 'edit', methods: ['GET', 'POST'])]
public function edit(int $id, Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_USER');
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->userService->hasAccessTo($actingUser)) {
$user = $this->entityManager->getRepository(User::class)->find($id);
if (!$user) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$form = $this->createForm(UserForm::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Handle file upload
$picture = $form->get('pictureUrl')->getData();
if ($picture) {
$this->userService->handleProfilePicture($user, $picture);
}
$user->setModifiedAt(new \DateTimeImmutable('now'));
$this->entityManager->persist($user);
$this->entityManager->flush();
if ($request->get('organizationId')) {
$org = $this->entityManager->getRepository(Organizations::class)->find($request->get('organizationId'));
if ($org) {
$this->actionService->createAction("Edit user information", $actingUser, $org, $user->getUserIdentifier());
}
} else {
$this->actionService->createAction("Edit user information", $actingUser, null, $user->getUserIdentifier());
}
return $this->redirectToRoute('user_show', ['id' => $user->getId(), 'organizationId' => $request->get('organizationId')]);
}
return $this->render('user/edit.html.twig', [
'user' => $user,
'form' => $form->createView(),
'organizationId' => $request->get('organizationId')
]);
}
throw $this->createAccessDeniedException(self::ACCESS_DENIED);
}
#[Route('/new', name: 'new', methods: ['GET', 'POST'])]
public function new(Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->userService->hasAccessTo($actingUser)) {
$user = new User();
$form = $this->createForm(UserForm::class, $user);
$form->handleRequest($request);
$orgId = $request->get('organizationId');
if ($form->isSubmitted() && $form->isValid()) {
// Handle file upload
$picture = $form->get('pictureUrl')->getData();
if ($picture) {
$this->userService->handleProfilePicture($user, $picture);
}
// else {
// $user->setPictureUrl("");
// }
//FOR TEST PURPOSES, SETTING A DEFAULT RANDOM PASSWORD
$user->setPassword($this->userService->generateRandomPassword());
if ($orgId) {
$org = $this->entityManager->getRepository(Organizations::class)->find($orgId);
if ($org) {
$uo = new UsersOrganizations();
$uo->setUsers($user);
$uo->setOrganization($org);
$this->entityManager->persist($uo);
$this->actionService->createAction("Create new user", $user, $org, "Added user to organization" . $user->getUserIdentifier() . " for organization " . $org->getName());
}
}
$this->actionService->createAction("Create new user", $actingUser, null, $user->getUserIdentifier());
$this->entityManager->persist($user);
$this->entityManager->flush();
return $this->redirectToRoute('user_index');
}
return $this->render('user/new.html.twig', [
'user' => $user,
'form' => $form->createView(),
'organizationId' => $orgId
]);
}
throw $this->createAccessDeniedException(self::ACCESS_DENIED);
}
#[Route('/deactivate/{id}', name: 'deactivate', methods: ['GET', 'POST'])]
public function deactivate(int $id): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->userService->hasAccessTo($actingUser, true)) {
$user = $this->entityManager->getRepository(User::class)->find($id);
if (!$user) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$user->setIsActive(false);
$user->setModifiedAt(new \DateTimeImmutable('now'));
$this->userOrganizationService->deactivateAllUserOrganizationLinks($user, $actingUser);
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->actionService->createAction("Deactivate user", $actingUser, null, $user->getUserIdentifier());
return $this->redirectToRoute('user_index');
}
throw $this->createAccessDeniedException(self::ACCESS_DENIED);
}
#[Route('/activate/{id}', name: 'activate', methods: ['GET', 'POST'])]
public function activate(int $id): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->userService->hasAccessTo($actingUser, true)) {
$user = $this->entityManager->getRepository(User::class)->find($id);
if (!$user) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$user->setIsActive(true);
$user->setModifiedAt(new \DateTimeImmutable('now'));
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->actionService->createAction("Activate user", $actingUser, null, $user->getUserIdentifier());
return $this->redirectToRoute('user_index');
}
throw $this->createAccessDeniedException(self::ACCESS_DENIED);
}
#[Route('/organization/deactivate/{id}', name: 'deactivate_organization', methods: ['GET', 'POST'])]
public function deactivateUserInOrganization(int $id, Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->userService->hasAccessTo($actingUser, true)) {
$orgId = $request->get('organizationId');
$org = $this->entityManager->getRepository(Organizations::class)->find($orgId);
if (!$org) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$user = $this->entityManager->getRepository(User::class)->find($id);
if (!$user) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$uo = $this->entityManager->getRepository(UsersOrganizations::class)->findOneBy(['users' => $user,
'organization' => $org,
'isActive' => true]);
if (!$uo) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$uo->setIsActive(false);
$this->userOrganizationAppService->deactivateAllUserOrganizationsAppLinks($uo);
$this->entityManager->persist($uo);
$this->entityManager->flush();
$this->actionService->createAction("Deactivate user in organization", $actingUser, $org, $org->getName() . " for user " . $user->getUserIdentifier());
return $this->redirectToRoute('user_index');
}
throw $this->createAccessDeniedException(self::ACCESS_DENIED);
}
#[Route('/organization/activate/{id}', name: 'activate_organization', methods: ['GET', 'POST'])]
public function activateUserInOrganization(int $id, Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->userService->hasAccessTo($actingUser, true)) {
$orgId = $request->get('organizationId');
$org = $this->entityManager->getRepository(Organizations::class)->find($orgId);
if (!$org) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$user = $this->entityManager->getRepository(User::class)->find($id);
if (!$user) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$uo = $this->entityManager->getRepository(UsersOrganizations::class)->findOneBy(['users' => $user,
'organization' => $org,
'isActive' => false]);
if (!$uo) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$uo->setIsActive(true);
$this->entityManager->persist($uo);
$this->entityManager->flush();
$this->actionService->createAction("Activate user in organization", $actingUser, $org, $org->getName() . " for user " . $user->getUserIdentifier());
return $this->redirectToRoute('user_index');
}
throw $this->createAccessDeniedException(self::ACCESS_DENIED);
}
#[Route('/delete/{id}', name: 'delete', methods: ['GET'])]
public function delete(int $id, Request $request): Response
{
$this->denyAccessUnlessGranted("ROLE_SUPER_ADMIN");
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
$user = $this->entityManager->getRepository(User::class)->find($id);
if (!$user) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$user->setIsActive(false);
$user->setModifiedAt(new \DateTimeImmutable('now'));
$this->userOrganizationService->deactivateAllUserOrganizationLinks($user, $actingUser);
$user->setIsDeleted(true);
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->actionService->createAction("Delete user", $actingUser, null, $user->getUserIdentifier());
return $this->redirectToRoute('user_index');
}
#[Route(path: '/application/roles/{id}', name: 'application_role', methods: ['GET', 'POST'])]
public function applicationRole(int $id, Request $request): Response
{
$this->denyAccessUnlessGranted("ROLE_ADMIN");
$actingUser = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
if ($this->userService->hasAccessTo($actingUser, true)) {
$uo = $this->userOrganizationService->getByIdOrFail($id);
$application = $this->entityManager->getRepository(Apps::class)->find($request->get('applicationId'));
if (!$application) {
throw $this->createNotFoundException(self::NOT_FOUND);
}
$selectedRolesIds = $request->get('roles', []);
$roleUser = $this->entityManager->getRepository(Roles::class)->findOneBy(['name' => 'USER']);
if (!$roleUser) {
throw $this->createNotFoundException('Default role not found');
}
if (in_array($roleUser->getId(), $selectedRolesIds)) {
$this->userOrganizationAppService->syncRolesForUserOrganizationApp(
$uo,
$application,
$selectedRolesIds,
$actingUser
);
} else {
$this->userOrganizationAppService->deactivateAllUserOrganizationsAppLinks($uo, $application);
}
$user = $uo->getUsers();
return $this->redirectToRoute('user_show', [
'user' => $user,
'id' => $user->getId(),
'organizationId'=> $uo->getOrganization()->getId()
]);
}
throw $this->createAccessDeniedException();
}
}