Passed
Push — devel-3.0 ( 6b6d4a...0e3c8b )
by Rubén
03:12
created

ControllerBase::prepareSignedUriOnView()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 5
nop 0
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      https://syspass.org
7
 * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace SP\Modules\Web\Controllers;
26
27
defined('APP_ROOT') || die();
28
29
use DI\Container;
30
use Psr\Container\ContainerInterface;
31
use SP\Core\Crypt\Hash;
32
use SP\Core\Exceptions\FileNotFoundException;
33
use SP\Core\Exceptions\SPException;
34
use SP\DataModel\ProfileData;
35
use SP\Modules\Web\Controllers\Helpers\LayoutHelper;
36
use SP\Modules\Web\Controllers\Traits\WebControllerTrait;
37
use SP\Mvc\View\Template;
38
use SP\Providers\Auth\Browser\Browser;
39
use SP\Services\Auth\AuthException;
40
use SP\Services\User\UserLoginResponse;
41
42
/**
43
 * Clase base para los controladores
44
 */
45
abstract class ControllerBase
46
{
47
    use WebControllerTrait;
48
49
    /**
50
     * Constantes de errores
51
     */
52
    const ERR_UNAVAILABLE = 0;
53
    const ERR_ACCOUNT_NO_PERMISSION = 1;
54
    const ERR_PAGE_NO_PERMISSION = 2;
55
    const ERR_UPDATE_MPASS = 3;
56
    const ERR_OPERATION_NO_PERMISSION = 4;
57
    const ERR_EXCEPTION = 5;
58
59
    /**
60
     * @var Template Instancia del motor de plantillas a utilizar
61
     */
62
    protected $view;
63
    /**
64
     * @var  UserLoginResponse
65
     */
66
    protected $userData;
67
    /**
68
     * @var  ProfileData
69
     */
70
    protected $userProfileData;
71
    /**
72
     * @var ContainerInterface
73
     */
74
    protected $dic;
75
    /**
76
     * @var
77
     */
78
    protected $isAjax = false;
79
80
    /**
81
     * Constructor
82
     *
83
     * @param Container $container
84
     * @param           $actionName
85
     *
86
     * @throws \Psr\Container\ContainerExceptionInterface
87
     * @throws \Psr\Container\NotFoundExceptionInterface
88
     */
89
    public final function __construct(Container $container, $actionName)
90
    {
91
        $this->dic = $container;
92
        $this->actionName = $actionName;
93
94
        $this->setUp($container);
95
96
        $this->view = $this->dic->get(Template::class);
97
98
        $this->view->setBase(strtolower($this->controllerName));
99
100
        $this->isAjax = $this->request->isAjax();
101
102
        if ($this->session->isLoggedIn()) {
103
            $this->userData = clone $this->session->getUserData();
104
            $this->userProfileData = clone $this->session->getUserProfile();
105
106
            $this->setViewVars();
107
        }
108
109
        if (method_exists($this, 'initialize')) {
110
            $this->initialize();
111
        }
112
    }
113
114
    /**
115
     * Set view variables
116
     */
117
    private function setViewVars()
118
    {
119
        $this->view->assign('timeStart', $this->router->request()->server()->get('REQUEST_TIME_FLOAT'));
120
        $this->view->assign('queryTimeStart', microtime());
121
        $this->view->assign('ctx_userId', $this->userData->getId());
122
        $this->view->assign('ctx_userGroupId', $this->userData->getUserGroupId());
123
        $this->view->assign('ctx_userIsAdminApp', $this->userData->getIsAdminApp());
124
        $this->view->assign('ctx_userIsAdminAcc', $this->userData->getIsAdminAcc());
125
        $this->view->assign('themeUri', $this->view->getTheme()->getThemeUri());
126
        $this->view->assign('isDemo', $this->configData->isDemoEnabled());
127
        $this->view->assign('icons', $this->theme->getIcons());
128
        $this->view->assign('configData', $this->configData);
129
130
        // Pass the action name to the template as a variable
131
        $this->view->assign($this->actionName);
132
    }
133
134
    /**
135
     * Mostrar los datos de la plantilla
136
     */
137
    protected function view()
138
    {
139
        try {
140
            $this->router->response()
141
                ->body($this->view->render())
142
                ->send();
143
        } catch (FileNotFoundException $e) {
144
            processException($e);
145
146
            $this->router->response()
147
                ->body(__($e->getMessage()))
148
                ->send(true);
149
        }
150
    }
151
152
    /**
153
     * Renderizar los datos de la plantilla y devolverlos
154
     */
155
    protected function render()
156
    {
157
        try {
158
            return $this->view->render();
159
        } catch (FileNotFoundException $e) {
160
            processException($e);
161
162
            return $e->getMessage();
163
        }
164
    }
165
166
    /**
167
     * Upgrades a View to use a full page layout
168
     *
169
     * @param string $page
170
     */
171
    protected function upgradeView($page = null)
172
    {
173
        $this->view->upgrade();
174
175
        if ($this->view->isUpgraded() === false) {
176
            return;
177
        }
178
179
        $this->view->assign('contentPage', $page ?: strtolower($this->controllerName));
180
181
        try {
182
            $this->dic->get(LayoutHelper::class)->getFullLayout('main', $this->acl);
183
        } catch (\Exception $e) {
184
            processException($e);
185
        }
186
    }
187
188
    /**
189
     * Obtener los datos para la vista de depuración
190
     */
191
    protected function getDebug()
192
    {
193
        global $memInit;
194
195
        $this->view->addTemplate('debug', 'common');
196
197
        $this->view->assign('time', getElapsedTime($this->router->request()->server()->get('REQUEST_TIME_FLOAT')));
198
        $this->view->assign('memInit', $memInit / 1000);
199
        $this->view->assign('memEnd', memory_get_usage() / 1000);
200
    }
201
202
    /**
203
     * Comprobar si el usuario está logado.
204
     *
205
     * @param bool $requireAuthCompleted
206
     *
207
     * @throws AuthException
208
     * @throws \DI\DependencyException
209
     * @throws \DI\NotFoundException
210
     */
211
    protected function checkLoggedIn($requireAuthCompleted = true)
212
    {
213
        if ($this->session->isLoggedIn()
214
            && $this->session->getAuthCompleted() === $requireAuthCompleted
215
        ) {
216
            $browser = $this->dic->get(Browser::class);
217
218
            // Comprobar si se ha identificado mediante el servidor web y el usuario coincide
219
            if ($browser->checkServerAuthUser($this->userData->getLogin()) === false
220
                && $browser->checkServerAuthUser($this->userData->getSsoLogin()) === false
221
            ) {
222
                throw new AuthException('Invalid browser auth');
223
            }
224
        }
225
226
        $this->checkLoggedInSession(
227
            $this->session,
228
            $this->request,
229
            function ($redirect) {
230
                $this->router->response()
231
                    ->redirect($redirect)
232
                    ->send(true);
233
            },
234
            $requireAuthCompleted
235
        );
236
    }
237
238
    /**
239
     * prepareSignedUriOnView
240
     *
241
     * Prepares view's variables to pass in a signed URI
242
     */
243
    final protected function prepareSignedUriOnView()
244
    {
245
        $from = $this->request->analyzeString('from');
246
247
        if ($from) {
248
            try {
249
                $this->request->verifySignature($this->configData->getPasswordSalt());
250
251
                $this->view->assign('from', $from);
252
                $this->view->assign('from_hash', Hash::signMessage($from, $this->configData->getPasswordSalt()));
253
            } catch (SPException $e) {
254
                processException($e);
255
            }
256
        }
257
    }
258
259
    /**
260
     * Comprobar si está permitido el acceso al módulo/página.
261
     *
262
     * @param null $action La acción a comprobar
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $action is correct as it would always require null to be passed?
Loading history...
263
     *
264
     * @return bool
265
     */
266
    protected function checkAccess($action)
267
    {
268
        return $this->userData->getIsAdminApp() || $this->acl->checkUserAccess($action);
269
    }
270
}