Passed
Push — devel-3.0 ( 84adb8...e69242 )
by Rubén
03:09
created

AuthProvider::authLdap()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 25
nc 8
nop 0
dl 0
loc 38
rs 8.8977
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\Providers\Auth;
26
27
use DI\Container;
28
use SP\Config\ConfigData;
29
use SP\DataModel\UserLoginData;
30
use SP\Providers\Auth\Browser\Browser;
31
use SP\Providers\Auth\Browser\BrowserAuthData;
32
use SP\Providers\Auth\Database\Database;
33
use SP\Providers\Auth\Database\DatabaseAuthData;
34
use SP\Providers\Auth\Ldap\LdapAuth;
35
use SP\Providers\Auth\Ldap\LdapAuthData;
36
use SP\Providers\Auth\Ldap\LdapConnection;
37
use SP\Providers\Auth\Ldap\LdapMsAds;
38
use SP\Providers\Auth\Ldap\LdapParams;
39
use SP\Providers\Auth\Ldap\LdapStd;
40
use SP\Providers\Provider;
41
use SP\Services\Auth\AuthException;
42
43
defined('APP_ROOT') || die();
44
45
/**
46
 * Class Auth
47
 *
48
 * Esta clase es la encargada de realizar la autentificación de usuarios de sysPass.
49
 *
50
 * @package SP\Providers\Auth
51
 */
52
final class AuthProvider extends Provider
53
{
54
    /**
55
     * @var array
56
     */
57
    protected $auths = [];
58
    /**
59
     * @var UserLoginData
60
     */
61
    protected $userLoginData;
62
    /**
63
     * @var ConfigData
64
     */
65
    protected $configData;
66
    /**
67
     * @var Browser
68
     */
69
    protected $browser;
70
    /**
71
     * @var Database
72
     */
73
    protected $database;
74
75
    /**
76
     * Probar los métodos de autentificación
77
     *
78
     * @param UserLoginData $userLoginData
79
     *
80
     * @return false|AuthResult[]
81
     */
82
    public function doAuth(UserLoginData $userLoginData)
83
    {
84
        $this->userLoginData = $userLoginData;
85
86
        $auths = [];
87
88
        foreach ($this->auths as $authType) {
89
            /** @var AuthDataBase $data */
90
            $data = $this->{$authType}();
91
92
            if ($data !== false) {
93
                $auths[] = new AuthResult($authType, $data);
94
            }
95
        }
96
97
        return count($auths) > 0 ? $auths : false;
98
    }
99
100
    /**
101
     * Autentificación de usuarios con LDAP.
102
     *
103
     * @return bool|LdapAuthData
104
     */
105
    public function authLdap()
106
    {
107
        $data = LdapParams::getServerAndPort($this->configData->getLdapServer());
108
109
        $ldapParams = (new LdapParams())
110
            ->setServer($data['server'])
111
            ->setPort(isset($data['port']) ? $data['port'] : 389)
112
            ->setSearchBase($this->configData->getLdapBase())
113
            ->setBindDn($this->configData->getLdapBindUser())
114
            ->setBindPass($this->configData->getLdapBindPass())
115
            ->setAds($this->configData->isLdapAds());
116
117
        $ldapConnection = new LdapConnection($ldapParams, $this->eventDispatcher, $this->configData->isDebug());
118
119
        if ($this->configData->isLdapAds()) {
120
            $ldap = new LdapAuth(
121
                new LdapMsAds($ldapConnection, $this->eventDispatcher),
122
                $this->eventDispatcher);
123
        } else {
124
            $ldap = new LdapAuth(
125
                new LdapStd($ldapConnection, $this->eventDispatcher),
126
                $this->eventDispatcher);
127
        }
128
129
        $ldapAuthData = $ldap->getLdapAuthData();
130
131
        $ldapAuthData->setAuthenticated($ldap->authenticate($this->userLoginData));
132
133
        if ($ldapAuthData->getAuthenticated()) {
134
            // Comprobamos si la cuenta está bloqueada o expirada
135
            if ($ldapAuthData->getExpire() > 0) {
136
                $ldapAuthData->setStatusCode(LdapAuth::ACCOUNT_EXPIRED);
137
            } elseif (!$ldapAuthData->isInGroup()) {
138
                $ldapAuthData->setStatusCode(LdapAuth::ACCOUNT_NO_GROUPS);
139
            }
140
        }
141
142
        return $ldapAuthData;
143
    }
144
145
    /**
146
     * Autentificación de usuarios con base de datos
147
     *
148
     * Esta función comprueba la clave del usuario. Si el usuario necesita ser migrado,
149
     * se ejecuta el proceso para actualizar la clave.
150
     *
151
     * @return DatabaseAuthData
152
     * @throws \Psr\Container\ContainerExceptionInterface
153
     * @throws \Psr\Container\NotFoundExceptionInterface
154
     */
155
    public function authDatabase()
156
    {
157
        return $this->database->authenticate($this->userLoginData);
158
    }
159
160
    /**
161
     * Autentificación de usuario con credenciales del navegador
162
     *
163
     * @return BrowserAuthData
164
     */
165
    public function authBrowser()
166
    {
167
        return $this->browser->authenticate($this->userLoginData);
168
    }
169
170
    /**
171
     * Auth constructor.
172
     *
173
     * @param Container $dic
174
     *
175
     * @throws AuthException
176
     * @throws \DI\DependencyException
177
     * @throws \DI\NotFoundException
178
     */
179
    protected function initialize(Container $dic)
180
    {
181
        $this->configData = $this->config->getConfigData();
182
183
        if ($this->configData->isAuthBasicEnabled()) {
184
            $this->registerAuth('authBrowser');
185
            $this->browser = $dic->get(Browser::class);
186
        }
187
188
        if ($this->configData->isLdapEnabled()) {
189
            $this->registerAuth('authLdap');
190
        }
191
192
        $this->registerAuth('authDatabase');
193
        $this->database = $dic->get(Database::class);
194
    }
195
196
    /**
197
     * Registrar un método de autentificación primarios
198
     *
199
     * @param string $auth Función de autentificación
200
     *
201
     * @throws AuthException
202
     */
203
    protected function registerAuth($auth)
204
    {
205
        if (!method_exists($this, $auth)) {
206
            throw new AuthException(__u('Método no disponible'), AuthException::ERROR, __FUNCTION__);
207
        }
208
209
        if (array_key_exists($auth, $this->auths)) {
210
            throw new AuthException(__u('Método ya inicializado'), AuthException::ERROR, __FUNCTION__);
211
        }
212
213
        $this->auths[$auth] = $auth;
214
    }
215
}
216