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

SessionContext::getPluginKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 10
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\Core\Context;
26
27
use SP\Config\ConfigData;
28
use SP\Core\Crypt\Vault;
29
use SP\DataModel\Dto\AccountCache;
30
use SP\DataModel\ProfileData;
31
use SP\Services\Account\AccountSearchFilter;
32
use SP\Services\User\UserLoginResponse;
33
34
/**
35
 * Class Session
36
 *
37
 * @package SP\Core\Session
38
 */
39
final class SessionContext extends ContextBase
40
{
41
    const MAX_SID_TIME = 120;
42
43
    private static $isReset = false;
44
    private static $isLocked = false;
45
46
    /**
47
     * @return bool
48
     */
49
    public static function isLocked()
50
    {
51
        return self::$isLocked;
52
    }
53
54
    /**
55
     * Closes session
56
     */
57
    public static function close()
58
    {
59
        logger('Session closed');
60
61
        session_write_close();
62
63
        self::$isLocked = true;
64
    }
65
66
    /**
67
     * Destruir la sesión y reiniciar
68
     */
69
    public static function restart()
70
    {
71
        self::$isReset = true;
72
73
        session_unset();
74
        session_destroy();
75
        session_start();
76
    }
77
78
    /**
79
     * Devuelve el tema visual utilizado en sysPass
80
     *
81
     * @return string
82
     */
83
    public function getTheme()
84
    {
85
        return $this->getContextKey('theme');
86
    }
87
88
    /**
89
     * Devolver una variable de sesión
90
     *
91
     * @param string $key
92
     * @param mixed  $default
93
     *
94
     * @return mixed
95
     */
96
    protected function getContextKey(string $key, $default = null)
97
    {
98
        try {
99
            return parent::getContextKey($key, $default);
100
        } catch (ContextException $e) {
101
            processException($e);
102
        }
103
104
        return $default;
105
    }
106
107
    /**
108
     * Establece el tema visual utilizado en sysPass
109
     *
110
     * @param $theme string El tema visual a utilizar
111
     */
112
    public function setTheme($theme)
113
    {
114
        $this->setContextKey('theme', $theme);
115
    }
116
117
    /**
118
     * Establecer una variable de sesión
119
     *
120
     * @param string $key   El nombre de la variable
121
     * @param mixed  $value El valor de la variable
122
     *
123
     * @return mixed
124
     */
125
    protected function setContextKey(string $key, $value)
126
    {
127
        try {
128
            if (self::$isLocked) {
129
                logger('Session locked; key=' . $key);
130
            } else {
131
                parent::setContextKey($key, $value);
132
            }
133
134
            return $value;
135
        } catch (ContextException $e) {
136
            processException($e);
137
        }
138
139
        return null;
140
    }
141
142
    /**
143
     * Establecer la configuración
144
     *
145
     * @param ConfigData $config
146
     */
147
    public function setConfig(ConfigData $config)
148
    {
149
        $this->setContextKey('config', $config);
150
    }
151
152
    /**
153
     * Establecer la hora de carga de la configuración
154
     *
155
     * @param int $time
156
     */
157
    public function setConfigTime($time)
158
    {
159
        $this->setContextKey('configTime', (int)$time);
160
    }
161
162
    /**
163
     * Devolver la hora de carga de la configuración
164
     *
165
     * @return int
166
     */
167
    public function getConfigTime()
168
    {
169
        return $this->getContextKey('configTime');
170
    }
171
172
    /**
173
     * Establece los datos del usuario en la sesión.
174
     *
175
     * @param UserLoginResponse $userLoginResponse
176
     */
177
    public function setUserData(UserLoginResponse $userLoginResponse = null)
178
    {
179
        $this->setContextKey('userData', $userLoginResponse);
180
    }
181
182
    /**
183
     * Obtiene el objeto de perfil de usuario de la sesión.
184
     *
185
     * @return ProfileData
186
     */
187
    public function getUserProfile()
188
    {
189
        return $this->getContextKey('userProfile');
190
    }
191
192
    /**
193
     * Establece el objeto de perfil de usuario en la sesión.
194
     *
195
     * @param ProfileData $ProfileData
196
     */
197
    public function setUserProfile(ProfileData $ProfileData)
198
    {
199
        $this->setContextKey('userProfile', $ProfileData);
200
    }
201
202
    /**
203
     * @return AccountSearchFilter
204
     */
205
    public function getSearchFilters()
206
    {
207
        return $this->getContextKey('searchFilters', null);
208
    }
209
210
    /**
211
     * @param AccountSearchFilter $searchFilters
212
     */
213
    public function setSearchFilters(AccountSearchFilter $searchFilters)
214
    {
215
        $this->setContextKey('searchFilters', $searchFilters);
216
    }
217
218
    public function resetAccountAcl()
219
    {
220
        $this->setContextKey('accountAcl', null);
221
    }
222
223
    /**
224
     * Returns if user is logged in
225
     *
226
     * @return bool
227
     */
228
    public function isLoggedIn()
229
    {
230
        return self::$isReset === false && $this->getUserData()->getLogin()
231
            && is_object($this->getUserData()->getPreferences());
232
    }
233
234
    /**
235
     * Devuelve los datos del usuario en la sesión.
236
     *
237
     * @return UserLoginResponse
238
     */
239
    public function getUserData()
240
    {
241
        return $this->getContextKey('userData', new UserLoginResponse());
242
    }
243
244
    /**
245
     * Establecer si el usuario está completamente autorizado
246
     *
247
     * @param $bool
248
     */
249
    public function setAuthCompleted($bool)
250
    {
251
        $this->setContextKey('authCompleted', (bool)$bool);
252
    }
253
254
    /**
255
     * Devolver si el usuario está completamente logeado
256
     */
257
    public function getAuthCompleted()
258
    {
259
        return $this->getContextKey('authCompleted', false);
260
    }
261
262
    /**
263
     * Devolver la clave maestra temporal
264
     *
265
     * @return string
266
     */
267
    public function getTemporaryMasterPass()
268
    {
269
        return $this->getContextKey('tempmasterpass');
270
    }
271
272
    /**
273
     * Sets a temporary master password
274
     *
275
     * @param string $password
276
     */
277
    public function setTemporaryMasterPass(string $password)
278
    {
279
        $this->setContextKey('tempmasterpass', $password);
280
    }
281
282
    /**
283
     * @return mixed
284
     */
285
    public function getSecurityKey()
286
    {
287
        return $this->getContextKey('sk');
288
    }
289
290
    /**
291
     * @return string
292
     */
293
    public function generateSecurityKey()
294
    {
295
        return $this->setSecurityKey(sha1(time() . $this->getConfig()->getPasswordSalt()));
296
    }
297
298
    /**
299
     * @param $sk
300
     *
301
     * @return mixed
302
     */
303
    public function setSecurityKey($sk)
304
    {
305
        return $this->setContextKey('sk', $sk);
306
    }
307
308
    /**
309
     * Devolver la configuración
310
     *
311
     * @return ConfigData
312
     */
313
    public function getConfig()
314
    {
315
        return $this->getContextKey('config');
316
    }
317
318
    /**
319
     * Devolver la clave pública
320
     *
321
     * @return mixed
322
     */
323
    public function getPublicKey()
324
    {
325
        return $this->getContextKey('pubkey');
326
    }
327
328
    /**
329
     * Establecer la clave pública
330
     *
331
     * @param $key
332
     */
333
    public function setPublicKey($key)
334
    {
335
        $this->setContextKey('pubkey', $key);
336
    }
337
338
    /**
339
     * Devuelve el timeout de la sesión
340
     *
341
     * @return int|null El valor en segundos
342
     */
343
    public function getSessionTimeout()
344
    {
345
        return $this->getContextKey('sessionTimeout');
346
    }
347
348
    /**
349
     * Establecer el timeout de la sesión
350
     *
351
     * @param int $timeout El valor en segundos
352
     *
353
     * @return int
354
     */
355
    public function setSessionTimeout($timeout)
356
    {
357
        $this->setContextKey('sessionTimeout', $timeout);
358
359
        return $timeout;
360
    }
361
362
    /**
363
     * Devuelve la hora de la última actividad
364
     *
365
     * @return int
366
     */
367
    public function getLastActivity()
368
    {
369
        return $this->getContextKey('lastActivity', 0);
370
    }
371
372
    /**
373
     * Establece la hora de la última actividad
374
     *
375
     * @param $time int La marca de hora
376
     */
377
    public function setLastActivity($time)
378
    {
379
        $this->setContextKey('lastActivity', $time);
380
    }
381
382
    /**
383
     * Devuelve la hora en la que el SID de sesión fue creado
384
     *
385
     * @return int
386
     */
387
    public function getSidStartTime()
388
    {
389
        return $this->getContextKey('sidStartTime', 0);
390
    }
391
392
    /**
393
     * Establece la hora de creación del SID
394
     *
395
     * @param $time int La marca de hora
396
     *
397
     * @return int
398
     */
399
    public function setSidStartTime($time)
400
    {
401
        $this->setContextKey('sidStartTime', $time);
402
403
        return $time;
404
    }
405
406
    /**
407
     * Devuelve la hora de inicio de actividad.
408
     *
409
     * @return int
410
     */
411
    public function getStartActivity()
412
    {
413
        return $this->getContextKey('startActivity', 0);
414
    }
415
416
    /**
417
     * Establece la hora de inicio de actividad
418
     *
419
     * @param $time int La marca de hora
420
     *
421
     * @return int
422
     */
423
    public function setStartActivity($time)
424
    {
425
        $this->setContextKey('startActivity', $time);
426
427
        return $time;
428
    }
429
430
    /**
431
     * Establecer el lenguaje de la sesión
432
     *
433
     * @param $locale
434
     */
435
    public function setLocale($locale)
436
    {
437
        $this->setContextKey('locale', $locale);
438
    }
439
440
    /**
441
     * Devuelve el lenguaje de la sesión
442
     *
443
     * @return string
444
     */
445
    public function getLocale()
446
    {
447
        return $this->getContextKey('locale');
448
    }
449
450
    /**
451
     * Devolver el color asociado a una cuenta
452
     *
453
     * @return string
454
     */
455
    public function getAccountColor()
456
    {
457
        return $this->getContextKey('accountcolor');
458
    }
459
460
    /**
461
     * Establece el color asociado a una cuenta
462
     *
463
     * @param array $color
464
     */
465
    public function setAccountColor(array $color)
466
    {
467
        $this->setContextKey('accountcolor', $color);
468
    }
469
470
    /**
471
     * Devuelve el estado de la aplicación
472
     *
473
     * @return bool
474
     */
475
    public function getAppStatus()
476
    {
477
        return $this->getContextKey('status');
478
    }
479
480
    /**
481
     * Establecer el estado de la aplicación
482
     *
483
     * @param string $status
484
     */
485
    public function setAppStatus($status)
486
    {
487
        $this->setContextKey('status', $status);
488
    }
489
490
    /**
491
     * Reset del estado de la aplicación
492
     *
493
     * @return bool
494
     */
495
    public function resetAppStatus()
496
    {
497
        return $this->setContextKey('status', null);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->setContextKey('status', null) targeting SP\Core\Context\SessionContext::setContextKey() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
498
    }
499
500
    /**
501
     * Devuelve la clave maestra encriptada
502
     *
503
     * @return Vault
504
     */
505
    public function getVault()
506
    {
507
        return $this->getContextKey('vault');
508
    }
509
510
    /**
511
     * Establecer la clave maestra encriptada
512
     *
513
     * @param Vault $vault
514
     */
515
    public function setVault(Vault $vault)
516
    {
517
        $this->setContextKey('vault', $vault);
518
    }
519
520
    /**
521
     * Establece la cache de cuentas
522
     *
523
     * @param array $accountsCache
524
     */
525
    public function setAccountsCache(array $accountsCache)
526
    {
527
        $this->setContextKey('accountsCache', $accountsCache);
528
    }
529
530
    /**
531
     * Devuelve la cache de cuentas
532
     *
533
     * @return AccountCache[]
534
     */
535
    public function getAccountsCache()
536
    {
537
        return $this->getContextKey('accountsCache');
538
    }
539
540
    /**
541
     * @throws ContextException
542
     */
543
    public function initialize()
544
    {
545
        // Si la sesión no puede ser iniciada, devolver un error 500
546
        if (session_start() === false) {
547
            throw new ContextException(__u('La sesión no puede ser inicializada'));
548
        }
549
550
        $this->setContextReference($_SESSION);
551
    }
552
553
    /**
554
     * @param string $ctxKeyName
555
     * @param string $key
556
     * @param mixed  $value
557
     *
558
     * @return mixed
559
     */
560
    public function setPluginKey(string $ctxKeyName, string $key, $value)
561
    {
562
        /** @var ContextCollection $ctxKey */
563
        $ctxKey = $this->getContextKey($ctxKeyName, new ContextCollection());
564
565
        $this->setContextKey($ctxKeyName, $ctxKey->set($key, $value));
566
567
        return $value;
568
    }
569
570
    /**
571
     * @param string $ctxKeyName
572
     * @param string $key
573
     *
574
     * @return mixed
575
     */
576
    public function getPluginKey(string $ctxKeyName, string $key)
577
    {
578
        /** @var ContextCollection $ctxKey */
579
        $ctxKey = $this->getContextKey($ctxKeyName);
580
581
        if ($ctxKey !== null) {
582
            return $ctxKey->get($key);
583
        }
584
585
        return null;
586
    }
587
}
588