Next major version 2 with PHP 8.1, Symfony 6, Tabler UI, 2FA ... (#2902)

This commit is contained in:
Kevin Papst
2022-12-31 21:19:55 +01:00
committed by GitHub
parent 95e06746bd
commit 90a0fd8a22
2164 changed files with 83700 additions and 86426 deletions

View File

@@ -1,7 +1,5 @@
<?php
declare(strict_types=1);
/*
* This file is part of the Kimai time-tracking app.
*
@@ -23,93 +21,67 @@ use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Request\ParamFetcherInterface;
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandlerInterface;
use HandcraftedInTheAlps\RestRoutingBundle\Controller\Annotations\RouteResource;
use Nelmio\ApiDocBundle\Annotation\Security as ApiSecurity;
use OpenApi\Attributes as OA;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Swagger\Annotations as SWG;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
/**
* @RouteResource("User")
* @SWG\Tag(name="User")
*
* @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
*/
#[Route(path: '/users')]
#[Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")]
#[OA\Tag(name: 'User')]
final class UserController extends BaseApiController
{
public const GROUPS_ENTITY = ['Default', 'Entity', 'User', 'User_Entity'];
public const GROUPS_FORM = ['Default', 'Entity', 'User', 'User_Entity'];
public const GROUPS_COLLECTION = ['Default', 'Collection', 'User'];
/**
* @var UserRepository
*/
private $repository;
/**
* @var ViewHandlerInterface
*/
private $viewHandler;
/**
* @var UserPasswordEncoderInterface
*/
private $encoder;
/**
* @var SystemConfiguration
*/
private $configuration;
public function __construct(ViewHandlerInterface $viewHandler, UserRepository $repository, UserPasswordEncoderInterface $encoder, SystemConfiguration $config)
{
$this->viewHandler = $viewHandler;
$this->repository = $repository;
$this->encoder = $encoder;
$this->configuration = $config;
public function __construct(
private ViewHandlerInterface $viewHandler,
private UserRepository $repository,
private UserPasswordHasherInterface $passwordHasher,
private SystemConfiguration $configuration
) {
}
/**
* Returns the collection of all registered users
*
* @SWG\Response(
* response=200,
* description="Returns the collection of all registered users. Required permission: view_user",
* @SWG\Schema(
* type="array",
* @SWG\Items(ref="#/definitions/UserCollection")
* )
* )
*
* @Rest\QueryParam(name="visible", requirements="1|2|3", strict=true, nullable=true, description="Visibility status to filter users. Allowed values: 1=visible, 2=hidden, 3=all (default: 1)")
* @Rest\QueryParam(name="orderBy", requirements="id|username|alias|email", strict=true, nullable=true, description="The field by which results will be ordered. Allowed values: id, username, alias, email (default: username)")
* @Rest\QueryParam(name="order", requirements="ASC|DESC", strict=true, nullable=true, description="The result order. Allowed values: ASC, DESC (default: ASC)")
* @Rest\QueryParam(name="term", description="Free search term")
*
* @Security("is_granted('view_user')")
*
* @ApiSecurity(name="apiUser")
* @ApiSecurity(name="apiToken")
* Returns the collection of users (which are visible to the user)
*/
#[Security("is_granted('view_user')")]
#[OA\Response(response: 200, description: 'Returns the collection of users. Required permission: view_user', content: new OA\JsonContent(type: 'array', items: new OA\Items(ref: '#/components/schemas/UserCollection')))]
#[Rest\Get(path: '', name: 'get_users')]
#[ApiSecurity(name: 'apiUser')]
#[ApiSecurity(name: 'apiToken')]
#[Rest\QueryParam(name: 'visible', requirements: '1|2|3', default: 1, strict: true, nullable: true, description: 'Visibility status to filter users: 1=visible, 2=hidden, 3=all')]
#[Rest\QueryParam(name: 'orderBy', requirements: 'id|username|alias|email', strict: true, nullable: true, description: 'The field by which results will be ordered. Allowed values: id, username, alias, email (default: username)')]
#[Rest\QueryParam(name: 'order', requirements: 'ASC|DESC', strict: true, nullable: true, description: 'The result order. Allowed values: ASC, DESC (default: ASC)')]
#[Rest\QueryParam(name: 'term', description: 'Free search term')]
public function cgetAction(ParamFetcherInterface $paramFetcher): Response
{
$query = new UserQuery();
$query->setCurrentUser($this->getUser());
if (null !== ($visible = $paramFetcher->get('visible'))) {
$query->setVisibility($visible);
$visible = $paramFetcher->get('visible');
if (\is_string($visible) && $visible !== '') {
$query->setVisibility((int) $visible);
}
if (null !== ($order = $paramFetcher->get('order'))) {
$order = $paramFetcher->get('order');
if (\is_string($order) && $order !== '') {
$query->setOrder($order);
}
if (null !== ($orderBy = $paramFetcher->get('orderBy'))) {
$orderBy = $paramFetcher->get('orderBy');
if (\is_string($orderBy) && $orderBy !== '') {
$query->setOrderBy($orderBy);
}
if (!empty($term = $paramFetcher->get('term'))) {
$term = $paramFetcher->get('term');
if (\is_string($term) && $term !== '') {
$query->setSearchTerm(new SearchTerm($term));
}
@@ -122,40 +94,20 @@ final class UserController extends BaseApiController
/**
* Return one user entity
*
* @SWG\Response(
* response=200,
* description="Return one user entity.",
* @SWG\Schema(ref="#/definitions/UserEntity"),
* )
* @SWG\Parameter(
* name="id",
* in="path",
* type="integer",
* description="User ID to fetch",
* required=true,
* )
*
* @ApiSecurity(name="apiUser")
* @ApiSecurity(name="apiToken")
*/
public function getAction(int $id, EventDispatcherInterface $dispatcher): Response
#[Security("is_granted('view', profile)")]
#[OA\Response(response: 200, description: 'Return one user entity.', content: new OA\JsonContent(ref: '#/components/schemas/UserEntity'))]
#[OA\Parameter(name: 'id', in: 'path', description: 'User ID to fetch', required: true)]
#[Rest\Get(path: '/{id}', name: 'get_user', requirements: ['id' => '\d+'])]
#[ApiSecurity(name: 'apiUser')]
#[ApiSecurity(name: 'apiToken')]
public function getAction(User $profile, EventDispatcherInterface $dispatcher): Response
{
$user = $this->repository->find($id);
if (null === $user) {
throw new NotFoundException();
}
if (!$this->isGranted('view', $user)) {
throw new AccessDeniedHttpException('You are not allowed to view this profile');
}
// we need to prepare the user preferences, which is done via an EventSubscriber
$event = new PrepareUserEvent($user);
$event = new PrepareUserEvent($profile);
$dispatcher->dispatch($event);
$view = new View($user, 200);
$view = new View($profile, 200);
$view->getContext()->setGroups(self::GROUPS_ENTITY);
return $this->viewHandler->handle($view);
@@ -163,18 +115,11 @@ final class UserController extends BaseApiController
/**
* Return the current user entity
*
* @SWG\Response(
* response=200,
* description="Return the current user entity.",
* @SWG\Schema(ref="#/definitions/UserEntity"),
* )
*
* @Rest\Get(path="/users/me")
*
* @ApiSecurity(name="apiUser")
* @ApiSecurity(name="apiToken")
*/
#[OA\Response(response: 200, description: 'Return the current user entity.', content: new OA\JsonContent(ref: '#/components/schemas/UserEntity'))]
#[Rest\Get(path: '/me', name: 'me_user')]
#[ApiSecurity(name: 'apiUser')]
#[ApiSecurity(name: 'apiToken')]
public function meAction(): Response
{
$view = new View($this->getUser(), 200);
@@ -185,27 +130,13 @@ final class UserController extends BaseApiController
/**
* Creates a new user
*
* @SWG\Post(
* description="Creates a new user and returns it afterwards",
* @SWG\Response(
* response=200,
* description="Returns the new created user",
* @SWG\Schema(ref="#/definitions/UserEntity",),
* )
* )
* @SWG\Parameter(
* name="body",
* in="body",
* required=true,
* @SWG\Schema(ref="#/definitions/UserCreateForm")
* )
*
* @Security("is_granted('create_user')")
*
* @ApiSecurity(name="apiUser")
* @ApiSecurity(name="apiToken")
*/
#[Security("is_granted('create_user')")]
#[OA\Post(description: 'Creates a new user and returns it afterwards')]
#[OA\RequestBody(required: true, content: new OA\JsonContent(ref: '#/components/schemas/UserCreateForm'))]
#[Rest\Post(path: '', name: 'post_user')]
#[ApiSecurity(name: 'apiUser')]
#[ApiSecurity(name: 'apiToken')]
public function postAction(Request $request): Response
{
$user = new User();
@@ -223,11 +154,15 @@ final class UserController extends BaseApiController
$form->submit($request->request->all());
if ($form->isValid()) {
$password = $this->encoder->encodePassword($user, $user->getPlainPassword());
$plainPassword = $user->getPlainPassword();
if ($plainPassword === null) {
throw new BadRequestHttpException('Password cannot be empty');
}
$password = $this->passwordHasher->hashPassword($user, $plainPassword);
$user->setPassword($password);
if ($user->getPlainApiToken() !== null) {
$user->setApiToken($this->encoder->encodePassword($user, $user->getPlainApiToken()));
$user->setApiToken($this->passwordHasher->hashPassword($user, $user->getPlainApiToken()));
}
$this->repository->saveUser($user);
@@ -248,51 +183,23 @@ final class UserController extends BaseApiController
/**
* Update an existing user
*
* @SWG\Patch(
* description="Update an existing user, you can pass all or just a subset of all attributes (passing roles will replace all existing ones)",
* @SWG\Response(
* response=200,
* description="Returns the updated user",
* @SWG\Schema(ref="#/definitions/UserEntity")
* )
* )
* @SWG\Parameter(
* name="body",
* in="body",
* required=true,
* @SWG\Schema(ref="#/definitions/UserEditForm")
* )
* @SWG\Parameter(
* name="id",
* in="path",
* type="integer",
* description="User ID to update",
* required=true,
* )
*
* @ApiSecurity(name="apiUser")
* @ApiSecurity(name="apiToken")
*/
public function patchAction(Request $request, int $id): Response
#[Security("is_granted('edit', profile)")]
#[OA\Patch(description: 'Update an existing user, you can pass all or just a subset of all attributes (passing roles will replace all existing ones)', responses: [new OA\Response(response: 200, description: 'Returns the updated user', content: new OA\JsonContent(ref: '#/components/schemas/UserEntity'))])]
#[OA\RequestBody(required: true, content: new OA\JsonContent(ref: '#/components/schemas/UserEditForm'))]
#[OA\Parameter(name: 'id', in: 'path', description: 'User ID to update', required: true)]
#[Rest\Patch(path: '/{id}', name: 'patch_user', requirements: ['id' => '\d+'])]
#[ApiSecurity(name: 'apiUser')]
#[ApiSecurity(name: 'apiToken')]
public function patchAction(Request $request, User $profile): Response
{
$user = $this->repository->getUserById($id);
if (null === $user) {
throw new NotFoundException();
}
if (!$this->isGranted('edit', $user)) {
throw new AccessDeniedHttpException('Not allowed to edit user');
}
$form = $this->createForm(UserApiEditForm::class, $user, [
'include_roles' => $this->isGranted('roles', $user),
'include_active_flag' => ($user->getId() !== $this->getUser()->getId()),
'include_preferences' => $this->isGranted('preferences', $user),
$form = $this->createForm(UserApiEditForm::class, $profile, [
'include_roles' => $this->isGranted('roles', $profile),
'include_active_flag' => ($profile->getId() !== $this->getUser()->getId()),
'include_preferences' => $this->isGranted('preferences', $profile),
]);
$form->setData($user);
$form->setData($profile);
$form->submit($request->request->all(), false);
if (false === $form->isValid()) {
@@ -302,9 +209,9 @@ final class UserController extends BaseApiController
return $this->viewHandler->handle($view);
}
$this->repository->saveUser($user);
$this->repository->saveUser($profile);
$view = new View($user, Response::HTTP_OK);
$view = new View($profile, Response::HTTP_OK);
$view->getContext()->setGroups(self::GROUPS_ENTITY);
return $this->viewHandler->handle($view);