Passed
Push — 3.0 ( d2a6b7...b247bd )
by Rubén
04:14
created

AuthProvider::authDatabase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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