Passed
Push — 3.0 ( 5e1ed3...5a5495 )
by Rubén
04:22
created

SessionContext::getSecurityKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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