aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/front/controller/admin/ShaarliAdminController.php
blob: 3385006c0271446c7d7ab460734cc2361b2941ea (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php

declare(strict_types=1);

namespace Shaarli\Front\Controller\Admin;

use Shaarli\Container\ShaarliContainer;
use Shaarli\Front\Controller\Visitor\ShaarliVisitorController;
use Shaarli\Front\Exception\UnauthorizedException;
use Shaarli\Front\Exception\WrongTokenException;
use Shaarli\Security\SessionManager;
use Slim\Http\Request;

/**
 * Class ShaarliAdminController
 *
 * All admin controllers (for logged in users) MUST extend this abstract class.
 * It makes sure that the user is properly logged in, and otherwise throw an exception
 * which will redirect to the login page.
 *
 * @package Shaarli\Front\Controller\Admin
 */
abstract class ShaarliAdminController extends ShaarliVisitorController
{
    public function __construct(ShaarliContainer $container)
    {
        parent::__construct($container);

        if (true !== $this->container->loginManager->isLoggedIn()) {
            throw new UnauthorizedException();
        }
    }

    /**
     * Any persistent action to the config or data store must check the XSRF token validity.
     */
    protected function checkToken(Request $request): void
    {
        if (!$this->container->sessionManager->checkToken($request->getParam('token'))) {
            throw new WrongTokenException();
        }
    }

    /**
     * Save a SUCCESS message in user session, which will be displayed on any template page.
     */
    protected function saveSuccessMessage(string $message): void
    {
        $this->saveMessage(SessionManager::KEY_SUCCESS_MESSAGES, $message);
    }

    /**
     * Save a WARNING message in user session, which will be displayed on any template page.
     */
    protected function saveWarningMessage(string $message): void
    {
        $this->saveMessage(SessionManager::KEY_WARNING_MESSAGES, $message);
    }

    /**
     * Save an ERROR message in user session, which will be displayed on any template page.
     */
    protected function saveErrorMessage(string $message): void
    {
        $this->saveMessage(SessionManager::KEY_ERROR_MESSAGES, $message);
    }

    /**
     * Use the sessionManager to save the provided message using the proper type.
     *
     * @param string $type successed/warnings/errors
     */
    protected function saveMessage(string $type, string $message): void
    {
        $messages = $this->container->sessionManager->getSessionParameter($type) ?? [];
        $messages[] = $message;

        $this->container->sessionManager->setSessionParameter($type, $messages);
    }
}