xref: /webtrees/app/Http/RequestHandlers/DeleteUser.php (revision 2ebb07b4bd8cf7010946ea4d75bb6160666157f6)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Http\RequestHandlers;
19
20use Fig\Http\Message\StatusCodeInterface;
21use Fisharebest\Webtrees\Auth;
22use Fisharebest\Webtrees\Log;
23use Fisharebest\Webtrees\Services\UserService;
24use Psr\Http\Message\ResponseInterface;
25use Psr\Http\Message\ServerRequestInterface;
26use Psr\Http\Server\RequestHandlerInterface;
27use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
28use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
29use function response;
30
31/**
32 * Delete a user.
33 */
34class DeleteUser implements RequestHandlerInterface, StatusCodeInterface
35{
36    /** @var UserService */
37    private $user_service;
38
39    /**
40     * @param UserService   $user_service
41     */
42    public function __construct(UserService $user_service)
43    {
44        $this->user_service = $user_service;
45    }
46
47    /**
48     * @param ServerRequestInterface $request
49     *
50     * @return ResponseInterface
51     */
52    public function handle(ServerRequestInterface $request): ResponseInterface
53    {
54        $user_id = (int) $request->getParsedBody()['user_id'];
55
56        $user = $this->user_service->find($user_id);
57
58        if ($user === null) {
59            throw new NotFoundHttpException('User ID ' . $user_id . ' not found');
60        }
61
62        if (Auth::isAdmin($user)) {
63            throw new AccessDeniedHttpException('Cannot delete an administrator');
64        }
65
66        Log::addAuthenticationLog('Deleted user: ' . $user->userName());
67        $this->user_service->delete($user);
68
69        return response('', StatusCodeInterface::STATUS_NO_CONTENT);
70    }
71}
72