summaryrefslogtreecommitdiffstats
path: root/modules/setup/application/forms/AdminAccountPage.php
blob: b33749efc92dc6ddead493f4ae682db36dcea4f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
<?php
/* Icinga Web 2 | (c) 2014 Icinga Development Team | GPLv2+ */

namespace Icinga\Module\Setup\Forms;

use Exception;
use Icinga\Application\Config;
use Icinga\Authentication\User\ExternalBackend;
use Icinga\Authentication\User\UserBackend;
use Icinga\Authentication\User\DbUserBackend;
use Icinga\Authentication\User\LdapUserBackend;
use Icinga\Authentication\UserGroup\UserGroupBackend;
use Icinga\Authentication\UserGroup\LdapUserGroupBackend;
use Icinga\Data\ConfigObject;
use Icinga\Data\ResourceFactory;
use Icinga\Data\Selectable;
use Icinga\Exception\NotImplementedError;
use Icinga\Protocol\Ldap\LdapQuery;
use Icinga\Web\Form;

/**
 * Wizard page to define the initial administrative account
 */
class AdminAccountPage extends Form
{
    /**
     * The resource configuration to use
     *
     * @var array
     */
    protected $resourceConfig;

    /**
     * The user backend configuration to use
     *
     * @var array
     */
    protected $backendConfig;

    /**
     * The user group backend configuration to use
     *
     * @var array
     */
    protected $groupConfig;

    /**
     * Initialize this page
     */
    public function init()
    {
        $this->setName('setup_admin_account');
        $this->setTitle($this->translate('Administration', 'setup.page.title'));
        $this->addDescription($this->translate(
            'Now it\'s time to configure your first administrative account or group for Icinga Web 2.'
        ));
    }

    /**
     * Set the resource configuration to use
     *
     * @param   array   $config
     *
     * @return  $this
     */
    public function setResourceConfig(array $config)
    {
        $this->resourceConfig = $config;
        return $this;
    }

    /**
     * Set the user backend configuration to use
     *
     * @param   array   $config
     *
     * @return  $this
     */
    public function setBackendConfig(array $config)
    {
        $this->backendConfig = $config;
        return $this;
    }

    /**
     * Set the user group backend configuration to use
     *
     * @param   array   $config
     *
     * @return  $this
     */
    public function setGroupConfig(array $config = null)
    {
        $this->groupConfig = $config;
        return $this;
    }

    /**
     * @see Form::createElements()
     */
    public function createElements(array $formData)
    {
        $choices = array();
        $groups = [];
        if ($this->backendConfig['backend'] !== 'db') {
            $choices['by_name'] = $this->translate('By Name', 'setup.admin');
            $choice = isset($formData['user_type']) ? $formData['user_type'] : 'by_name';

            if (in_array($this->backendConfig['backend'], array('ldap', 'msldap'))) {
                $groups = $this->fetchGroups();
                if (! empty($groups)) {
                    $choices['user_group'] = $this->translate('User Group', 'setup.admin');
                }
            }
        } else {
            $choices['new_user'] = $this->translate('New User', 'setup.admin');
            $choice = isset($formData['user_type']) ? $formData['user_type'] : 'new_user';
        }

        $users = [];
        if (in_array($this->backendConfig['backend'], array('db', 'ldap', 'msldap'))) {
            $users = $this->fetchUsers();
            if (! empty($users)) {
                $choices['existing_user'] = $this->translate('Existing User', 'setup.admin');
            }
        }

        if (count($choices) > 1) {
            $this->addElement(
                'select',
                'user_type',
                array(
                    'required'      => true,
                    'autosubmit'    => true,
                    'label'         => $this->translate('Type Of Definition'),
                    'description'   => $this->translate('Choose how to define the desired account.'),
                    'multiOptions'  => $choices,
                    'value'         => $choice
                )
            );
        } else {
            $this->addElement(
                'hidden',
                'user_type',
                array(
                    'required'  => true,
                    'value'     => key($choices)
                )
            );
        }

        if ($choice === 'by_name') {
            $this->addElement(
                'text',
                'by_name',
                array(
                    'required'      => true,
                    'value'         => $this->getUsername(),
                    'label'         => $this->translate('Username'),
                    'description'   => $this->translate(
                        'Define the initial administrative account by providing a username that reflects'
                        . ' a user created later or one that is authenticated using external mechanisms.'
                    )
                )
            );
        }

        if ($choice === 'user_group') {
            $this->addElement(
                'select',
                'user_group',
                array(
                    'required'      => true,
                    'label'         => $this->translate('Group Name'),
                    'description'   => $this->translate(
                        'Choose a user group reported by the LDAP backend'
                        . ' to permit its members administrative access.',
                        'setup.admin'
                    ),
                    'multiOptions'  => array_combine($groups, $groups)
                )
            );
        }

        if ($choice === 'existing_user') {
            $this->addElement(
                'select',
                'existing_user',
                array(
                    'required'      => true,
                    'label'         => $this->translate('Username'),
                    'description'   => sprintf(
                        $this->translate(
                            'Choose a user reported by the %s backend as the initial administrative account.',
                            'setup.admin'
                        ),
                        $this->backendConfig['backend'] === 'db'
                            ? $this->translate('database', 'setup.admin.authbackend')
                            : 'LDAP'
                    ),
                    'multiOptions'  => array_combine($users, $users)
                )
            );
        }

        if ($choice === 'new_user') {
            $this->addElement(
                'text',
                'new_user',
                array(
                    'required'      => true,
                    'label'         => $this->translate('Username'),
                    'description'   => $this->translate(
                        'Enter the username to be used when creating an initial administrative account.'
                    )
                )
            );
            $this->addElement(
                'password',
                'new_user_password',
                array(
                    'required'          => true,
                    'renderPassword'    => true,
                    'label'             => $this->translate('Password'),
                    'description'       => $this->translate(
                        'Enter the password to assign to the newly created account.'
                    ),
                    'autocomplete'      => 'new-password'
                )
            );
            $this->addElement(
                'password',
                'new_user_2ndpass',
                array(
                    'required'          => true,
                    'renderPassword'    => true,
                    'label'             => $this->translate('Repeat password'),
                    'description'       => $this->translate(
                        'Please repeat the password given above to avoid typing errors.'
                    ),
                    'validators'        => array(
                        array('identical', false, array('new_user_password'))
                    )
                )
            );
        }
    }

    /**
     * Validate the given request data and ensure that any new user does not already exist
     *
     * @param   array   $data   The request data to validate
     *
     * @return  bool
     */
    public function isValid($data)
    {
        if (false === parent::isValid($data)) {
            return false;
        }

        if ($data['user_type'] === 'new_user' && $this->hasUser($data['new_user'])) {
            $this->getElement('new_user')->addError($this->translate('Username already exists.'));
            return false;
        }

        return true;
    }

    /**
     * Return the name of the externally authenticated user
     *
     * @return  string
     */
    protected function getUsername()
    {
        list($name, $_) = ExternalBackend::getRemoteUserInformation();
        if ($name === null) {
            return '';
        }

        if (isset($this->backendConfig['strip_username_regexp']) && $this->backendConfig['strip_username_regexp']) {
            // No need to silence or log anything here because the pattern has
            // already been successfully compiled during backend configuration
            $name = preg_replace($this->backendConfig['strip_username_regexp'], '', $name);
        }

        return $name;
    }

    /**
     * Return the names of all users the user backend currently provides
     *
     * @return  array
     */
    protected function fetchUsers()
    {
        try {
            $query = $this
                ->createUserBackend()
                ->select(array('user_name'))
                ->order('user_name', 'asc', true);
            if (in_array($this->backendConfig['backend'], array('ldap', 'msldap'))) {
                /** @var LdapQuery $ldapQuery */
                $ldapQuery = $query->getQuery();
                $ldapQuery->setUsePagedResults();
            }

            return $query->fetchColumn();
        } catch (Exception $_) {
            // No need to handle anything special here. Error means no users found.
            return array();
        }
    }

    /**
     * Return whether the user backend provides a user with the given name
     *
     * @param   string  $username
     *
     * @return  bool
     */
    protected function hasUser($username)
    {
        try {
            return $this
                ->createUserBackend()
                ->select()
                ->where('user_name', $username)
                ->count() > 1;
        } catch (Exception $_) {
            return false;
        }
    }

    /**
     * Create and return the user backend
     *
     * @return  DbUserBackend|LdapUserBackend
     */
    protected function createUserBackend()
    {
        $resourceConfig = new Config();
        $resourceConfig->setSection($this->resourceConfig['name'], $this->resourceConfig);
        ResourceFactory::setConfig($resourceConfig);

        $config = new ConfigObject($this->backendConfig);
        $config->resource = $this->resourceConfig['name'];
        return UserBackend::create(null, $config);
    }

    /**
     * Return the names of all user groups the user group backend currently provides
     *
     * @return  array
     */
    protected function fetchGroups()
    {
        try {
            $query = $this
                ->createUserGroupBackend()
                ->select(array('group_name'));
            if (in_array($this->backendConfig['backend'], array('ldap', 'msldap'))) {
                /** @var LdapQuery $ldapQuery */
                $ldapQuery = $query->getQuery();
                $ldapQuery->setUsePagedResults();
            }

            return $query->fetchColumn();
        } catch (Exception $_) {
            // No need to handle anything special here. Error means no groups found.
            return array();
        }
    }

    /**
     * Return whether the user group backend provides a user group with the given name
     *
     * @param   string  $groupname
     *
     * @return  bool
     */
    protected function hasGroup($groupname)
    {
        try {
            return $this
                ->createUserGroupBackend()
                ->select()
                ->where('group_name', $groupname)
                ->count() > 1;
        } catch (Exception $_) {
            return false;
        }
    }

    /**
     * Create and return the user group backend
     *
     * @return  LdapUserGroupBackend
     */
    protected function createUserGroupBackend()
    {
        $resourceConfig = new Config();
        $resourceConfig->setSection($this->resourceConfig['name'], $this->resourceConfig);
        ResourceFactory::setConfig($resourceConfig);

        $backendConfig = new Config();
        $backendConfig->setSection($this->backendConfig['name'], array_merge(
            $this->backendConfig,
            array('resource' => $this->resourceConfig['name'])
        ));
        UserBackend::setConfig($backendConfig);

        if (empty($this->groupConfig)) {
            $groupConfig = new ConfigObject(array(
                'backend'       => $this->backendConfig['backend'], // _Should_ be "db" or "msldap"
                'resource'      => $this->resourceConfig['name'],
                'user_backend'  => $this->backendConfig['name'] // Gets ignored if 'backend' is "db"
            ));
        } else {
            $groupConfig = new ConfigObject($this->groupConfig);
        }

        $backend = UserGroupBackend::create(null, $groupConfig);
        if (! $backend instanceof Selectable) {
            throw new NotImplementedError('Unsupported, until #9772 has been resolved');
        }

        return $backend;
    }
}