Completed
Push — feature/EVO-7278-security-and-... ( 0e0414 )
by
unknown
13:20
created

SecurityUtils::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * Simple service helper to find and user Security User
4
 */
5
namespace Graviton\SecurityBundle\Service;
6
7
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
8
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
9
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
10
use Symfony\Component\Security\Core\User\UserInterface;
11
use Graviton\SecurityBundle\Entities\SecurityUser;
12
13
/**
14
 * Service Security Helper
15
 *
16
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
17
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
18
 * @link     http://swisscom.ch
19
 */
20
class SecurityUtils
21
{
22
    /** @var SecurityUser */
23
    private $securityUser;
24
    
25
    /** @var string  */
26
    private $threadId;
27
28
    /**
29
     * StoreManager constructor.
30
     * @param TokenStorage $tokenStorage Sf Auth token storage
31
     */
32
    public function __construct(
33
        TokenStorage $tokenStorage
34
    ) {
35
        $this->tokenStorage = $tokenStorage;
36
    }
37
38
    /**
39
     * Check if there is a security user
40
     *
41
     * @return bool
42
     */
43
    public function isSecurityUser()
44
    {
45
        if ($this->securityUser) {
46
            return true;
47
        }
48
        
49
        /** @var PreAuthenticatedToken $token */
50 View Code Duplication
        if (($token = $this->tokenStorage->getToken())
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51
            && ($user = $token->getUser()) instanceof UserInterface ) {
52
            $this->securityUser = $user;
53
            return true;
54
        }
55
        return false;
56
    }
57
    
58
    /**
59
     * Find current user
60
     *
61
     * @return string|bool
0 ignored issues
show
Documentation introduced by
Should the return type not be SecurityUser?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
62
     * @throws UsernameNotFoundException
63
     */
64
    public function getSecurityUser()
65
    {
66
        if ($this->isSecurityUser()) {
67
            return $this->securityUser;
68
        }
69
        throw new UsernameNotFoundException('No security user');
70
    }
71
72
    /**
73
     * Return users username
74
     *
75
     * @return string
76
     * @throws UsernameNotFoundException
77
     */
78
    public function getSecurityUsername()
79
    {
80
        if ($this->isSecurityUser()) {
81
            return $this->securityUser->getUsername();
82
        }
83
        throw new UsernameNotFoundException('No security user');
84
    }
85
86
    /**
87
     * Check if current user is in Role
88
     *
89
     * @param string $role User role expected
90
     * @return bool
91
     * @throws UsernameNotFoundException
92
     */
93
    public function hasRole($role)
94
    {
95
        if ($this->isSecurityUser()) {
96
            return (bool) $this->securityUser->hasRole($role);
97
        }
98
        throw new UsernameNotFoundException('No security user');
99
    }
100
101
    /**
102
     * Generate a unique Thread Id.
103
     *
104
     * @return string
105
     */
106
    public function getThreadId()
107
    {
108
        if ($this->threadId) {
109
            return $this->threadId;
110
        }
111
        
112
        if (!function_exists('openssl_random_pseudo_bytes')) {
113
            $this->threadId = uniqid('unq', true);
114
        } else {
115
            $data = openssl_random_pseudo_bytes(16);
116
            // set version to 0100
117
            $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
118
            // set bits 6-7 to 10
119
            $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
120
            $this->threadId = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
121
        }
122
123
        return $this->threadId;
124
    }
125
}
126