Completed
Pull Request — master (#399)
by Anton
04:24
created

Auth::getIdentity()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 0
dl 0
loc 12
ccs 6
cts 6
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Auth;
12
13
use Bluz\Common\Options;
14
use Bluz\Proxy\Request;
15
use Bluz\Proxy\Session;
16
17
/**
18
 * Auth class
19
 *
20
 * @package  Bluz\Auth
21
 * @author   Anton Shevchuk
22
 * @link     https://github.com/bluzphp/framework/wiki/Auth
23
 */
24
class Auth
25
{
26
    use Options;
27
28
    /**
29
     * @var EntityInterface Instance of EntityInterface
30
     */
31
    protected $identity;
32
33
    /**
34
     * Setup identity
35
     *
36
     * @param  EntityInterface $identity
37
     * @return void
38
     */
39 3
    public function setIdentity(EntityInterface $identity)
40
    {
41
        // save identity to Auth
42 3
        $this->identity = $identity;
43
        // save identity to session
44 3
        Session::set('auth:identity', $identity);
45
        // save user agent to session
46 3
        Session::set('auth:agent', Request::getServer('HTTP_USER_AGENT'));
47 3
    }
48
49
    /**
50
     * Return identity if user agent is correct
51
     *
52
     * @return EntityInterface|null
53
     */
54 6
    public function getIdentity()
55
    {
56 6
        if (!$this->identity) {
57
            // check user agent
58 3
            if (Session::get('auth:agent') == Request::getServer('HTTP_USER_AGENT')) {
59 2
                $this->identity = Session::get('auth:identity');
60
            } else {
61 1
                $this->clearIdentity();
62
            }
63
        }
64 6
        return $this->identity;
65
    }
66
67
    /**
68
     * Clear identity and user agent information
69
     *
70
     * @return void
71
     */
72 640
    public function clearIdentity()
73
    {
74 640
        $this->identity = null;
75 640
        Session::delete('auth:identity');
76 640
        Session::delete('auth:agent');
77 640
    }
78
}
79