Passed
Push — master ( b54d6e...32f105 )
by Andreas
34:18
created

midcom_services_auth::login()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 3
dl 0
loc 8
ccs 4
cts 6
cp 0.6667
crap 2.1481
rs 10
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
153
            if (!$person->get_parameter('midcom', 'first_login')) {
154
                $person->set_parameter('midcom', 'first_login', time());
155
            } elseif (midcom::get()->config->get('auth_save_prev_login')) {
156
                $person->set_parameter('midcom', 'prev_login', $person->get_parameter('midcom', 'last_login'));
157
            }
158
            $person->set_parameter('midcom', 'last_login', time());
159
160
            // Now we check whether there is a success-relocate URL given somewhere.
161
            if ($request->get('midcom_services_auth_login_success_url')) {
162
                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

162
                return new midcom_response_relocate(/** @scrutinizer ignore-type */ $request->get('midcom_services_auth_login_success_url'));
Loading history...
163
            }
164
        }
165
        // No new login detected, so we check if there is a running session.
166 1
        elseif ($user = $this->backend->check_for_active_login_session($request)) {
167
            $this->set_user($user);
168
        }
169 1
    }
170
171
    /**
172
     * @param midcom_core_user $user
173
     */
174 59
    private function set_user(midcom_core_user $user)
175
    {
176 59
        $this->user = $user;
177 59
        $this->admin = $user->is_admin();
178 59
    }
179
180
    /**
181
     * Internal startup helper, loads all configured authentication drivers.
182
     */
183
    private function _prepare_authentication_drivers()
184
    {
185
        $classname = midcom::get()->config->get('auth_backend');
186
        if (!str_contains($classname, "_")) {
0 ignored issues
show
Bug introduced by
It seems like $classname can also be of type null; however, parameter $haystack of str_contains() 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

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