User.php 6.11 KB
Newer Older
1
2
3
<?php
namespace UnicaenAuth\Service;

4
5
use PDOException;
use UnicaenApp\Exception;
6
use UnicaenApp\Mapper\Ldap\People as LdapPeopleMapper;
7
use UnicaenAuth\Options\ModuleOptions;
8
use UnicaenAuth\Event\UserAuthenticatedEvent;
9
10
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
11
12
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
13
14
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
15
16
use ZfcUser\Authentication\Adapter\AdapterChainEvent as AuthEvent;
use ZfcUser\Options\AuthenticationOptionsInterface;
17
use ZfcUser\Options\ModuleOptions as ZfcUserModuleOptions;
18
19

/**
20
 * Service d'enregistrement dans la table des utilisateurs de l'application
21
 * de l'utilisateur authentifié avec succès.
22
23
 *
 * Est notifié via la méthode 'userAuthenticated()' lorsque l'authentification
24
 * est terminée avec succès.
25
 *
26
 * @see \UnicaenAuth\Authentication\Adapter\AbstractFactory
27
28
 * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
 */
29
class User implements ServiceLocatorAwareInterface, EventManagerAwareInterface
30
{
31
    use ServiceLocatorAwareTrait;
32

33
34

    const EVENT_USER_AUTHENTICATED_PRE_PERSIST = 'userAuthenticated.prePersist';
35

36
37
38
39
40
    /**
     * @var EventManagerInterface
     */
    protected $eventManager;

41
    /**
42
     * @var ModuleOptions
43
44
45
46
     */
    protected $options;

    /**
47
     * @var AuthenticationOptionsInterface
48
49
     */
    protected $zfcUserOptions;
50

51
    /**
52
     * @var LdapPeopleMapper
53
     */
54
    protected $ldapPeopleMapper;
55

56
57
    /**
     * Save authenticated user in database from LDAP data.
58
     *
59
60
61
62
63
64
65
66
67
68
     * @return bool
     */
    public function userAuthenticated(AuthEvent $e)
    {
        if (!$this->getOptions()->getSaveLdapUserInDatabase()) {
            return false;
        }
        if (!($username = $e->getIdentity())) {
            return false;
        }
69

70
        if (is_int($username)) {
71
            // c'est un id : cela signifie que l'utilisateur existe déjà dans la bdd (et pas dans le LDAP), rien à faire
72
73
            return true;
        }
74

75
        if (!is_string($username)) {
76
            throw new Exception("Identité rencontrée inattendue.");
77
        }
78

79
        // recherche de l'individu dans l'annuaire LDAP
80
        $ldapPeople = $this->getLdapPeopleMapper()->findOneByUsername($username);
81
82
83
        if (!$ldapPeople) {
            return false;
        }
84

85
        // update/insert de l'utilisateur dans la table de l'appli
86
        $mapper = $this->getServiceLocator()->get('zfcuser_user_mapper'); /* @var $mapper \ZfcUserDoctrineORM\Mapper\User */
87
88
        try {
            $entity = $mapper->findByUsername($username);
89
90
91
92
93
94
95
96
97
98
99
100
101
            if (!$entity) {
                $entityClass = $this->getZfcUserOptions()->getUserEntityClass();
                $entity = new $entityClass;
                $entity->setUsername($username);
                $method = 'insert';
            }
            else {
                $method = 'update';
            }
            $entity->setEmail($ldapPeople->getMail());
            $entity->setDisplayName($ldapPeople->getDisplayName());
            $entity->setPassword('ldap');
            $entity->setState(in_array('deactivated', ldap_explode_dn($ldapPeople->getDn(), 1)) ? 0 : 1);
102
103

            // déclenche l'événement donnant aux applications clientes l'opportunité de modifier l'entité
104
105
106
107
108
109
            // utilisateur avant qu'elle ne soit persistée
            $event = new UserAuthenticatedEvent(UserAuthenticatedEvent::PRE_PERSIST);
            $event
                    ->setDbUser($entity)
                    ->setLdapUser($ldapPeople)
                    ->setTarget($this);
110
            $this->getEventManager()->trigger($event);
111

112
            // persist
113
114
            $mapper->$method($entity);
        }
115
        catch (PDOException $pdoe) {
116
            throw new Exception("Impossible d'enregistrer l'utilisateur authentifié dans la base de données.", null, $pdoe);
117
        }
118

119
120
        return true;
    }
121
122


123
124
125
126
127
128
129
130
131
132
133
    /**
     * Retrieve the event manager
     *
     * Lazy-loads an EventManager instance if none registered.
     *
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        return $this->eventManager;
    }
134

135
136
137
138
139
140
141
142
    /**
     * Inject an EventManager instance
     *
     * @param  EventManagerInterface $eventManager
     * @return void
     */
    public function setEventManager(EventManagerInterface $eventManager)
    {
143
        $eventManager->setIdentifiers([
144
145
            __CLASS__,
            get_called_class(),
146
        ]);
147
148
149
        $this->eventManager = $eventManager;
        return $this;
    }
150
151

    /**
152
     * get ldap people mapper
153
     *
154
     * @return LdapPeopleMapper
155
     */
156
    public function getLdapPeopleMapper()
157
    {
158
        if (null === $this->ldapPeopleMapper) {
159
            $this->ldapPeopleMapper = $this->getServiceLocator()->get('ldap_people_mapper');
160
        }
161
        return $this->ldapPeopleMapper;
162
163
164
    }

    /**
165
     * set ldap people mapper
166
     *
167
     * @param LdapPeopleMapper $mapper
168
169
     * @return User
     */
170
    public function setLdapPeopleMapper(LdapPeopleMapper $mapper)
171
    {
172
        $this->ldapPeopleMapper = $mapper;
173
174
175
176
        return $this;
    }

    /**
177
     * @param ModuleOptions $options
178
     */
179
    public function setOptions(ModuleOptions $options)
180
181
    {
        $this->options = $options;
182
        return $this;
183
184
185
    }

    /**
186
     * @return ModuleOptions
187
188
189
     */
    public function getOptions()
    {
190
        if (!$this->options instanceof ModuleOptions) {
191
            $this->setOptions($this->getServiceLocator()->get('unicaen-auth_module_options'));
192
193
194
195
196
        }
        return $this->options;
    }

    /**
197
     * @param ZfcUserModuleOptions $options
198
     */
199
    public function setZfcUserOptions(ZfcUserModuleOptions $options)
200
201
    {
        $this->zfcUserOptions = $options;
202
        return $this;
203
204
205
    }

    /**
206
     * @return ZfcUserModuleOptions
207
208
209
     */
    public function getZfcUserOptions()
    {
210
        if (!$this->zfcUserOptions instanceof ZfcUserModuleOptions) {
211
212
213
214
            $this->setZfcUserOptions($this->getServiceManager()->get('zfcuser_module_options'));
        }
        return $this->zfcUserOptions;
    }
215
}