EmailUser::loadUserByUsername()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
c 0
b 0
f 0
rs 9.584
cc 4
nc 4
nop 1
1
<?php
2
3
namespace Kaliop\IdentityManagementBundle\Security\User\Provider;
4
5
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
6
use eZ\Publish\Core\MVC\Symfony\Security\User;
7
use eZ\Publish\Core\MVC\Symfony\Security\UserInterface;
8
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
9
use eZ\Publish\Core\MVC\Symfony\Security\User\Provider;
10
11
/**
12
 * Used to log in users by either their email or login
13
 */
14
class EmailUser extends Provider
15
{
16
    /**
17
     * Loads the user for the given user 'ID'.
18
     * $user can be either the user ID or an instance of \eZ\Publish\Core\MVC\Symfony\Security\User
19
     * (anonymous user we try to check access via SecurityContext::isGranted()).
20
     *
21
     * @param string|\eZ\Publish\Core\MVC\Symfony\Security\User $user Either the user ID to load an instance of User object. A value of -1 represents an anonymous user.
22
     *
23
     * @return \eZ\Publish\Core\MVC\Symfony\Security\UserInterface
24
     *
25
     * @throws \Symfony\Component\Security\Core\Exception\UsernameNotFoundException if the user is not found
26
     */
27
    public function loadUserByUsername($user)
28
    {
29
        try {
30
            // SecurityContext always tries to authenticate anonymous users when checking granted access.
31
            // In that case $user is an instance of \eZ\Publish\Core\MVC\Symfony\Security\User.
32
            // We don't need to reload the user here.
33
            if ($user instanceof UserInterface) {
34
                return $user;
35
            }
36
            // 1st try to find user by login
37
            return new User($this->repository->getUserService()->loadUserByLogin($user), array('ROLE_USER'));
38
        } catch (NotFoundException $e) {
39
            // Then we try to find the user via email address
40
            $users = $this->repository->getUserService()->loadUsersByEmail($user);
41
            if (!count($users)) {
42
                throw new UsernameNotFoundException();
43
            }
44
            /// @todo log a warning if many users do match the email
45
            return new User($users[0], array('ROLE_USER'));
46
        }
47
    }
48
}