Passed
Push — master ( b2388c...5da13c )
by Andreas
18:44
created

midcom_services_auth::get_user()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 7.9295

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 13
nop 1
dl 0
loc 24
ccs 11
cts 15
cp 0.7332
crap 7.9295
rs 8.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midcom.services
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use Symfony\Component\HttpFoundation\Request;
10
11
/**
12
 * Main Authentication/Authorization service class, it provides means to authenticate
13
 * users and to check for permissions.
14
 *
15
 * <b>Authentication</b>
16
 *
17
 * Whenever the system successfully creates a new login session (during auth service startup),
18
 * it checks whether the key <i>midcom_services_auth_login_success_url</i> is present in the HTTP
19
 * Request data. If this is the case, it relocates to the URL given in it. This member isn't set
20
 * by default in the MidCOM core, it is intended for custom authentication forms. The MidCOM
21
 * relocate function is used to for relocation, thus you can take full advantage of the
22
 * convenience functions in there. See midcom_application::relocate() for details.
23
 *
24
 * <b>Checking Privileges</b>
25
 *
26
 * This class offers various methods to verify the privilege state of a user, all of them prefixed
27
 * with can_* for privileges and is_* for membership checks.
28
 *
29
 * Each function is available in a simple check version, which returns true or false, and a
30
 * require_* prefixed variant, which has no return value. The require variants of these calls
31
 * instead check if the given condition is met, if yes, they return silently, otherwise they
32
 * throw an access denied error.
33
 *
34
 * @todo Fully document authentication.
35
 * @package midcom.services
36
 */
37
class midcom_services_auth
38
{
39
    /**
40
     * The currently authenticated user or null in case of anonymous access.
41
     * It is to be considered read-only.
42
     *
43
     * @var midcom_core_user
44
     */
45
    public $user;
46
47
    /**
48
     * Admin user level state. This is true if the currently authenticated user is an
49
     * Midgard Administrator, false otherwise.
50
     *
51
     * This effectively maps to midcom_connection::is_admin(); but it is suggested to use the auth class
52
     * for consistency reasons nevertheless.
53
     *
54
     * @var boolean
55
     */
56
    public $admin = false;
57
58
    /**
59
     * The ACL management system.
60
     *
61
     * @var midcom_services_auth_acl
62
     */
63
    public $acl;
64
65
    /**
66
     * Internal cache of all loaded groups, indexed by their identifiers.
67
     *
68
     * @var Array
69
     */
70
    private $_group_cache = [];
71
72
    /**
73
     * Internal cache of all loaded users, indexed by their identifiers.
74
     *
75
     * @var Array
76
     */
77
    private $_user_cache = [];
78
79
    /**
80
     * This flag indicates if sudo mode is active during execution. This will only be the
81
     * case if the sudo system actually grants this privileges, and only until components
82
     * release the rights again. This does override the full access control system at this time
83
     * and essentially give you full admin privileges (though this might change in the future).
84
     *
85
     * Note, that this is no boolean but an int, otherwise it would be impossible to trace nested
86
     * sudo invocations, which are quite possible with multiple components calling each others
87
     * callback. A value of 0 indicates that sudo is inactive. A value greater than zero indicates
88
     * sudo mode is active, with the count being equal to the depth of the sudo callers.
89
     *
90
     * It is thus still safely possible to evaluate this member in a boolean context to check
91
     * for an enabled sudo mode.
92
     *
93
     * @var int
94
     * @see request_sudo()
95
     * @see drop_sudo()
96
     */
97
    private $_component_sudo = 0;
98
99
    /**
100
     * The authentication backend we should use by default.
101
     *
102
     * @var midcom_services_auth_backend
103
     */
104
    private $backend;
105
106
    /**
107
     * The authentication frontend we should use by default.
108
     *
109
     * @var midcom_services_auth_frontend
110
     */
111
    private $frontend;
112
113
    /**
114
     * Initialize the service:
115
     *
116
     * - Start up the login session service
117
     * - Load the core privileges.
118
     * - Initialize to the Midgard Authentication, then synchronize with the auth
119
     *   drivers' currently authenticated user overriding the Midgard Auth if
120
     *   necessary.
121
     */
122
    public function __construct(midcom_services_auth_acl $acl)
123
    {
124
        $this->acl = $acl;
125
126
        // Initialize from midgard
127
        if (   midcom_connection::get_user()
128
            && $user = $this->get_user(midcom_connection::get_user())) {
129
            $this->set_user($user);
130
        }
131
132
        $this->_prepare_authentication_drivers();
133
    }
134
135
    /**
136
     * Checks if the current authentication fronted has new credentials
137
     * ready. If yes, it processes the login accordingly. Otherwise look for existing session
138
     *
139
     * @param Request $request The request object
140
     */
141 1
    public function check_for_login_session(Request $request)
142
    {
143
        // Try to start up a new session, this will authenticate as well.
144 1
        if ($credentials = $this->frontend->read_login_data($request)) {
145
            if (!$this->login($credentials['username'], $credentials['password'], $request->getClientIp())) {
146
                return;
147
            }
148
            debug_add('Authentication was successful, we have a new login session now. Updating timestamps');
149
150
            $person_class = midcom::get()->config->get('person_class');
151
            $person = new $person_class($this->user->guid);
152
            if (   midcom::get()->config->get('auth_save_prev_login')
153
                && $person->get_parameter('midcom', 'last_login')) {
154
                $person->set_parameter('midcom', 'prev_login', $person->get_parameter('midcom', 'last_login'));
155
            }
156
157
            $person->set_parameter('midcom', 'last_login', time());
158
159
            if (!$person->get_parameter('midcom', 'first_login')) {
160
                $person->set_parameter('midcom', 'first_login', time());
161
            }
162
163
            // Now we check whether there is a success-relocate URL given somewhere.
164
            if ($request->get('midcom_services_auth_login_success_url')) {
165
                return new midcom_response_relocate($request->get('midcom_services_auth_login_success_url'));
0 ignored issues
show
Bug introduced by
It seems like $request->get('midcom_se...uth_login_success_url') can also be of type null; however, parameter $url of midcom_response_relocate::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

165
                return new midcom_response_relocate(/** @scrutinizer ignore-type */ $request->get('midcom_services_auth_login_success_url'));
Loading history...
166
            }
167
        }
168
        // No new login detected, so we check if there is a running session.
169 1
        elseif ($user = $this->backend->check_for_active_login_session($request)) {
170
            $this->set_user($user);
171
        }
172 1
    }
173
174
    /**
175
     * @param midcom_core_user $user
176
     */
177 59
    private function set_user(midcom_core_user $user)
178
    {
179 59
        $this->user = $user;
180 59
        $this->admin = $user->is_admin();
181 59
    }
182
183
    /**
184
     * Internal startup helper, loads all configured authentication drivers.
185
     */
186
    private function _prepare_authentication_drivers()
187
    {
188
        $classname = midcom::get()->config->get('auth_backend');
189
        if (strpos($classname, "_") === false) {
190
            $classname = 'midcom_services_auth_backend_' . $classname;
191
        }
192
        $this->backend = new $classname($this);
193
194
        $classname = midcom::get()->config->get('auth_frontend');
195
        if (strpos($classname, "_") === false) {
196
            $classname = 'midcom_services_auth_frontend_' . $classname;
197
        }
198
        $this->frontend = new $classname();
199
    }
200
201
    /**
202
     * Checks whether a user has a certain privilege on the given content object.
203
     * Works on the currently authenticated user by default, but can take another
204
     * user as an optional argument.
205
     *
206
     * @param string $privilege The privilege to check for
207
     * @param MidgardObject $content_object A Midgard Content Object
0 ignored issues
show
Bug introduced by
The type MidgardObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
208
     * @param midcom_core_user $user The user against which to check the privilege, defaults to the currently authenticated user.
209
     *     You may specify "EVERYONE" instead of an object to check what an anonymous user can do.
210
     */
211 435
    public function can_do($privilege, $content_object, $user = null) : bool
212
    {
213 435
        if (!is_object($content_object)) {
214 1
            return false;
215
        }
216
217 435
        if ($this->is_admin($user)) {
218
            // Administrators always have access.
219 2
            return true;
220
        }
221
222 435
        $user_id = $this->acl->get_user_id($user);
223
224
        //if we're handed the correct object type, we use its class right away
225 435
        if (midcom::get()->dbclassloader->is_midcom_db_object($content_object)) {
226 435
            $content_object_class = get_class($content_object);
227
        }
228
        //otherwise, we assume (hope) that it's a midgard object
229
        else {
230
            $content_object_class = midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($content_object);
231
        }
232
233 435
        return $this->acl->can_do_byguid($privilege, $content_object->guid, $content_object_class, $user_id);
234
    }
235
236 445
    private function is_admin($user) : bool
237
    {
238 445
        if ($user === null) {
239 445
            return $this->user && $this->admin;
240
        }
241 5
        if (is_a($user, midcom_core_user::class)) {
242 2
            return $user->is_admin();
243
        }
244 3
        return false;
245
    }
246
247
    /**
248
     * Checks, whether the given user have the privilege assigned to him in general.
249
     * Be aware, that this does not take any permissions overridden by content objects
250
     * into account. Whenever possible, you should user the can_do() variant of this
251
     * call therefore. can_user_do is only of interest in cases where you do not have
252
     * any content object available, for example when creating root topics.
253
     *
254
     * @param string $privilege The privilege to check for
255
     * @param midcom_core_user $user The user against which to check the privilege, defaults to the currently authenticated user,
256
     *     you may specify 'EVERYONE' here to check what an anonymous user can do.
257
     * @param string $class Optional parameter to set if the check should take type specific permissions into account. The class must be default constructible.
258
     */
259 334
    public function can_user_do($privilege, $user = null, $class = null) : bool
260
    {
261 334
        if ($this->is_admin($user)) {
262
            // Administrators always have access.
263 2
            return true;
264
        }
265 334
        if ($this->_component_sudo) {
266 331
            return true;
267
        }
268 7
        if ($user === null) {
269 7
            $user =& $this->user;
270
        }
271
272 7
        if ($user == 'EVERYONE') {
0 ignored issues
show
introduced by
The condition $user == 'EVERYONE' is always false.
Loading history...
273
            $user = null;
274
        }
275
276 7
        return $this->acl->can_do_byclass($privilege, $user, $class);
277
    }
278
279
    /**
280
     * Request superuser privileges for the domain passed.
281
     *
282
     * STUB IMPLEMENTATION ONLY, WILL ALWAYS GRANT SUDO.
283
     *
284
     * You have to call midcom_services_auth::drop_sudo() as soon as you no longer
285
     * need the elevated privileges, which will reset the authentication data to the
286
     * initial credentials.
287
     *
288
     * @param string $domain The domain to request sudo for. This is a component name.
289
     */
290 735
    public function request_sudo($domain = null) : bool
291
    {
292 735
        if (!midcom::get()->config->get('auth_allow_sudo')) {
293 1
            debug_add("SUDO is not allowed on this website.", MIDCOM_LOG_ERROR);
294 1
            return false;
295
        }
296
297 735
        if ($domain === null) {
298 1
            $domain = midcom_core_context::get()->get_key(MIDCOM_CONTEXT_COMPONENT);
299 1
            debug_add("Domain was not supplied, falling back to '{$domain}' which we got from the current component context.");
300
        }
301
302 735
        if ($domain == '') {
303 1
            debug_add("SUDO request for an empty domain, this should not happen. Denying sudo.", MIDCOM_LOG_INFO);
304 1
            return false;
305
        }
306
307 735
        $this->_component_sudo++;
308
309 735
        debug_add("Entered SUDO mode for domain {$domain}.", MIDCOM_LOG_INFO);
310
311 735
        return true;
312
    }
313
314
    /**
315
     * Drops previously acquired superuser privileges.
316
     *
317
     * @see request_sudo()
318
     */
319 735
    public function drop_sudo()
320
    {
321 735
        if ($this->_component_sudo > 0) {
322 735
            debug_add('Leaving SUDO mode.');
323 735
            $this->_component_sudo--;
324
        } else {
325 1
            debug_add('Requested to leave SUDO mode, but sudo was already disabled. Ignoring request.', MIDCOM_LOG_INFO);
326
        }
327 735
    }
328
329 735
    public function is_component_sudo() : bool
330
    {
331 735
        return $this->_component_sudo > 0;
332
    }
333
334
    /**
335
     * Check, whether a user is member of a given group. By default, the query is run
336
     * against the currently authenticated user.
337
     *
338
     * It always returns true for administrative users.
339
     *
340
     * @param mixed $group Group to check against, this can be either a midcom_core_group object or a group string identifier.
341
     * @param midcom_core_user $user The user which should be checked, defaults to the current user.
342
     */
343
    public function is_group_member($group, $user = null) : bool
344
    {
345
        if ($this->is_admin($user)) {
346
            // Administrators always have access.
347
            return true;
348
        }
349
        // Default parameter
350
        if ($user === null) {
351
            if ($this->user === null) {
352
                // not authenticated
353
                return false;
354
            }
355
            $user = $this->user;
356
        }
357
358
        return $user->is_in_group($group);
359
    }
360
361
    /**
362
     * Returns true if there is an authenticated user, false otherwise.
363
     */
364 146
    public function is_valid_user() : bool
365
    {
366 146
        return $this->user !== null;
367
    }
368
369
    /**
370
     * Validates that the current user has the given privilege granted on the
371
     * content object passed to the function.
372
     *
373
     * If this is not the case, an Access Denied error is generated, the message
374
     * defaulting to the string 'access denied: privilege %s not granted' of the
375
     * MidCOM main L10n table.
376
     *
377
     * The check is always done against the currently authenticated user. If the
378
     * check is successful, the function returns silently.
379
     *
380
     * @param string $privilege The privilege to check for
381
     * @param MidgardObject $content_object A Midgard Content Object
382
     * @param string $message The message to show if the privilege has been denied.
383
     */
384 182
    public function require_do($privilege, $content_object, $message = null)
385
    {
386 182
        if (!$this->can_do($privilege, $content_object)) {
387
            throw $this->access_denied($message, 'privilege %s not granted', $privilege);
388
        }
389 182
    }
390
391
    /**
392
     * Validates, whether the given user have the privilege assigned to him in general.
393
     * Be aware, that this does not take any permissions overridden by content objects
394
     * into account. Whenever possible, you should user the require_do() variant of this
395
     * call therefore. require_user_do is only of interest in cases where you do not have
396
     * any content object available, for example when creating root topics.
397
     *
398
     * If this is not the case, an Access Denied error is generated, the message
399
     * defaulting to the string 'access denied: privilege %s not granted' of the
400
     * MidCOM main L10n table.
401
     *
402
     * The check is always done against the currently authenticated user. If the
403
     * check is successful, the function returns silently.
404
     *
405
     * @param string $privilege The privilege to check for
406
     * @param string $message The message to show if the privilege has been denied.
407
     * @param string $class Optional parameter to set if the check should take type specific permissions into account. The class must be default constructible.
408
     */
409 77
    public function require_user_do($privilege, $message = null, $class = null)
410
    {
411 77
        if (!$this->can_user_do($privilege, null, $class)) {
412
            throw $this->access_denied($message, 'privilege %s not granted', $privilege);
413
        }
414 77
    }
415
416
    /**
417
     * Validates that the current user is a member of the given group.
418
     *
419
     * If this is not the case, an Access Denied error is generated, the message
420
     * defaulting to the string 'access denied: user is not member of the group %s' of the
421
     * MidCOM main L10n table.
422
     *
423
     * The check is always done against the currently authenticated user. If the
424
     * check is successful, the function returns silently.
425
     *
426
     * @param mixed $group Group to check against, this can be either a midcom_core_group object or a group string identifier.
427
     * @param string $message The message to show if the user is not member of the given group.
428
     */
429
    function require_group_member($group, $message = null)
430
    {
431
        if (!$this->is_group_member($group)) {
432
            if (is_object($group)) {
433
                $group = $group->name;
434
            }
435
            throw $this->access_denied($message, 'user is not member of the group %s', $group);
436
        }
437
    }
438
439
    /**
440
     * Validates that we currently have admin level privileges, which can either
441
     * come from the current user, or from the sudo service.
442
     *
443
     * If the check is successful, the function returns silently.
444
     *
445
     * @param string $message The message to show if the admin level privileges are missing.
446
     */
447 4
    public function require_admin_user($message = null)
448
    {
449 4
        if (!$this->admin && !$this->_component_sudo) {
450
            throw $this->access_denied($message, 'admin level privileges required');
451
        }
452 4
    }
453
454
    private function access_denied($message, $fallback, $data = null) : midcom_error_forbidden
455
    {
456
        if ($message === null) {
457
            $message = midcom::get()->i18n->get_string('access denied: ' . $fallback, 'midcom');
458
            if ($data !== null) {
459
                $message = sprintf($message, $data);
460
            }
461
        }
462
        debug_print_function_stack("access_denied was called from here:");
463
        return new midcom_error_forbidden($message);
464
    }
465
466
    /**
467
     * Require either a configured IP address or admin credentials
468
     *
469
     * @param string $domain Domain for IP sudo
470
     * @throws midcom_error In case request_sudo fails
471
     * @return boolean True if IP sudo is active, false otherwise
472
     */
473
    public function require_admin_or_ip($domain) : bool
474
    {
475
        $ips = midcom::get()->config->get('indexer_reindex_allowed_ips');
476
        if (   $ips
477
            && in_array($_SERVER['REMOTE_ADDR'], $ips)) {
478
            if (!$this->request_sudo($domain)) {
479
                throw new midcom_error('Failed to acquire SUDO rights. Aborting.');
480
            }
481
            return true;
482
        }
483
484
        // Require user to Basic-authenticate for security reasons
485
        $this->require_valid_user('basic');
486
        $this->require_admin_user();
487
        return false;
488
    }
489
490
    /**
491
     * Validates that there is an authenticated user.
492
     *
493
     * If this is not the case, midcom_error_forbidden is thrown, or a
494
     * basic auth challenge is triggered
495
     *
496
     * If the check is successful, the function returns silently.
497
     *
498
     * @param string $method Preferred authentication method: form or basic
499
     */
500 144
    public function require_valid_user($method = 'form')
501
    {
502 144
        if ($method === 'basic') {
503 3
            $this->_http_basic_auth();
504
        }
505 144
        if (!$this->is_valid_user()) {
506
            throw new midcom_error_forbidden(null, MIDCOM_ERRAUTH, $method);
507
        }
508 144
    }
509
510
    /**
511
     * Handles HTTP Basic authentication
512
     */
513 3
    private function _http_basic_auth()
514
    {
515 3
        if (isset($_SERVER['PHP_AUTH_USER'])) {
516
            if ($user = $this->backend->authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
517
                $this->set_user($user);
518
            } else {
519
                // Wrong password
520
                unset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
521
            }
522
        }
523 3
    }
524
525
    /**
526
     * Resolve any assignee identifier known by the system into an appropriate user/group object.
527
     *
528
     * @param string $id A valid user or group identifier usable as assignee (e.g. the $id member
529
     *     of any midcom_core_user or midcom_core_group object).
530
     * @return object|false corresponding object or false on failure.
531
     */
532 122
    public function get_assignee($id)
533
    {
534 122
        $parts = explode(':', $id);
535
536 122
        if ($parts[0] == 'user') {
537 120
            return $this->get_user($id);
538
        }
539 5
        if ($parts[0] == 'group') {
540 3
            return $this->get_group($id);
541
        }
542 2
        debug_add("The identifier {$id} cannot be resolved into an assignee, it cannot be mapped to a type.", MIDCOM_LOG_WARN);
543
544 2
        return null;
545
    }
546
547
    /**
548
     * This is a wrapper for get_user, which allows user retrieval by its name.
549
     * If the username is unknown, false is returned.
550
     *
551
     * @param string $name The name of the user to look up.
552
     * @return midcom_core_user|false The user object matching the username, or false if the username is unknown.
553
     */
554 3
    public function get_user_by_name($name)
555
    {
556 3
        $mc = new midgard_collector('midgard_user', 'login', $name);
557 3
        $mc->set_key_property('person');
558 3
        $mc->add_constraint('authtype', '=', midcom::get()->config->get('auth_type'));
559 3
        $mc->execute();
560 3
        $keys = $mc->list_keys();
561 3
        if (count($keys) != 1) {
562
            return false;
563
        }
564
565 3
        $person_class = midcom::get()->config->get('person_class');
566 3
        $person = new $person_class(key($keys));
567
568 3
        return $this->get_user($person);
569
    }
570
571
    /**
572
     * This is a wrapper for get_group, which allows Midgard Group retrieval by its name.
573
     * If the group name is unknown, false is returned.
574
     *
575
     * In the case that more than one group matches the given name, the first one is returned.
576
     * Note, that this should not happen as midgard group names should be unique according to the specs.
577
     *
578
     * @param string $name The name of the group to look up.
579
     * @return midcom_core_group|false The group object matching the name, or false if the group name is unknown.
580
     */
581
    public function get_midgard_group_by_name($name)
582
    {
583
        $qb = new midgard_query_builder('midgard_group');
584
        $qb->add_constraint('name', '=', $name);
585
586
        $result = $qb->execute();
587
        if (empty($result)) {
588
            return false;
589
        }
590
        return $this->get_group($result[0]);
591
    }
592
593
    /**
594
     * Load a user from the database and returns an object instance.
595
     *
596
     * @param mixed $id A valid identifier for a MidgardPerson: An existing midgard_person class
597
     *     or subclass thereof, a Person ID or GUID or a midcom_core_user identifier.
598
     * @return midcom_core_user|false The user object matching the identifier or false on failure.
599
     */
600 168
    public function get_user($id)
601
    {
602 168
        $param = $id;
603
604 168
        if (isset($param->id)) {
605 3
            $id = $param->id;
606 168
        } elseif (!is_string($id) && !is_int($id)) {
607
            debug_add('The passed argument was an object of an unsupported type: ' . gettype($param), MIDCOM_LOG_WARN);
608
            debug_print_r('Complete object dump:', $param);
609
            return false;
610
        }
611 168
        if (!array_key_exists($id, $this->_user_cache)) {
612
            try {
613 108
                if (is_a($param, midcom_db_person::class)) {
614
                    $param = $param->__object;
615
                }
616 108
                $this->_user_cache[$id] = new midcom_core_user($param);
617 3
            } catch (midcom_error $e) {
618
                // Keep it silent while missing user object can mess here
619 3
                $this->_user_cache[$id] = false;
620
            }
621
        }
622
623 168
        return $this->_user_cache[$id];
624
    }
625
626
    /**
627
     * Returns a midcom_core_group instance. Valid arguments are either a valid group identifier
628
     * (group:...), any valid identifier for the midcom_core_group
629
     * constructor or a valid object of that type.
630
     *
631
     * @param mixed $id The identifier of the group as outlined above.
632
     * @return midcom_core_group|false A group object instance matching the identifier, or false on failure.
633
     */
634 3
    public function get_group($id)
635
    {
636 3
        $param = $id;
637
638 3
        if (isset($param->id)) {
639
            $id = $param->id;
640 3
        } elseif (!is_string($id) && !is_int($id)) {
641
            debug_add('The group identifier is of an unsupported type: ' . gettype($param), MIDCOM_LOG_WARN);
642
            debug_print_r('Complete dump:', $param);
643
            return false;
644
        }
645
646 3
        if (!array_key_exists($id, $this->_group_cache)) {
647
            try {
648 3
                if (is_a($param, midcom_core_dbaobject::class)) {
649
                    $param = $param->__object;
650
                }
651 3
                $this->_group_cache[$id] = new midcom_core_group($param);
652
            } catch (midcom_error $e) {
653
                debug_add("Group with identifier {$id} could not be loaded: " . $e->getMessage(), MIDCOM_LOG_WARN);
654
                $this->_group_cache[$id] = false;
655
            }
656
        }
657 3
        return $this->_group_cache[$id];
658
    }
659
660
    /**
661
     * This call tells the backend to log in.
662
     */
663 59
    public function login($username, $password, $clientip = null) : bool
664
    {
665 59
        if ($user = $this->backend->login($username, $password, $clientip)) {
666 59
            $this->set_user($user);
667 59
            return true;
668
        }
669
        debug_add('The login information for ' . $username . ' was invalid.', MIDCOM_LOG_WARN);
670
        return false;
671
    }
672
673
    public function trusted_login($username) : bool
674
    {
675
        if (midcom::get()->config->get('auth_allow_trusted') !== true) {
676
            debug_add("Trusted logins are prohibited", MIDCOM_LOG_ERROR);
677
            return false;
678
        }
679
680
        if ($user = $this->backend->login($username, '', null, true)) {
681
            $this->set_user($user);
682
            return true;
683
        }
684
        return false;
685
    }
686
687
    /**
688
     * This call clears any authentication state
689
     */
690 1
    public function logout()
691
    {
692 1
        if ($this->user === null) {
693
            debug_add('The backend has no authenticated user set, so we should be fine');
694
        } else {
695 1
            $this->backend->logout($this->user);
696 1
            $this->user = null;
697
        }
698 1
        $this->admin = false;
699 1
    }
700
701
    /**
702
     * Render the main login form.
703
     * This only includes the form, no heading or whatsoever.
704
     *
705
     * It is recommended to call this function only as long as the headers are not yet sent (which
706
     * is usually given thanks to MidCOMs output buffering).
707
     *
708
     * What gets rendered depends on the authentication frontend, but will usually be some kind
709
     * of form.
710
     */
711
    public function show_login_form()
712
    {
713
        $this->frontend->show_login_form();
714
    }
715
716
    public function has_login_data() : bool
717
    {
718
        return $this->frontend->has_login_data();
719
    }
720
}
721