Passed
Push — master ( 38457e...3f9740 )
by Andreas
37:47
created

midcom_services_auth::set_user()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
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
     * This flag indicates if sudo mode is active during execution. This will only be the
74
     * case if the sudo system actually grants this privileges, and only until components
75
     * release the rights again. This does override the full access control system at this time
76
     * and essentially give you full admin privileges (though this might change in the future).
77
     *
78
     * Note, that this is no boolean but an int, otherwise it would be impossible to trace nested
79
     * sudo invocations, which are quite possible with multiple components calling each others
80
     * callback. A value of 0 indicates that sudo is inactive. A value greater than zero indicates
81
     * sudo mode is active, with the count being equal to the depth of the sudo callers.
82
     *
83
     * It is thus still safely possible to evaluate this member in a boolean context to check
84
     * for an enabled sudo mode.
85
     *
86
     * @var int
87
     * @see request_sudo()
88
     * @see drop_sudo()
89
     */
90
    private $_component_sudo = 0;
91
92
    /**
93
     * The authentication backend we should use by default.
94
     *
95
     * @var midcom_services_auth_backend
96
     */
97
    private $backend;
98
99
    /**
100
     * The authentication frontend we should use by default.
101
     *
102
     * @var midcom_services_auth_frontend
103
     */
104
    private $frontend;
105
106
    /**
107
     * Loads all configured authentication drivers.
108
     */
109
    public function __construct(midcom_services_auth_acl $acl, midcom_services_auth_backend $backend, midcom_services_auth_frontend $frontend)
110
    {
111
        $this->acl = $acl;
112
        $this->backend = $backend;
113
        $this->frontend = $frontend;
114
    }
115
116
    /**
117
     * Checks if the current authentication fronted has new credentials
118
     * ready. If yes, it processes the login accordingly. Otherwise look for existing session
119
     *
120
     * @param Request $request The request object
121
     */
122 1
    public function check_for_login_session(Request $request)
123
    {
124
        // Try to start up a new session, this will authenticate as well.
125 1
        if ($credentials = $this->frontend->read_login_data($request)) {
126
            if (!$this->login($credentials['username'], $credentials['password'], $request->getClientIp())) {
127
                return;
128
            }
129
            debug_add('Authentication was successful, we have a new login session now. Updating timestamps');
130
131
            $person_class = midcom::get()->config->get('person_class');
132
            $person = new $person_class($this->user->guid);
133
134
            if (!$person->get_parameter('midcom', 'first_login')) {
135
                $person->set_parameter('midcom', 'first_login', time());
136
            } elseif (midcom::get()->config->get('auth_save_prev_login')) {
137
                $person->set_parameter('midcom', 'prev_login', $person->get_parameter('midcom', 'last_login'));
138
            }
139
            $person->set_parameter('midcom', 'last_login', time());
140
141
            // Now we check whether there is a success-relocate URL given somewhere.
142
            if ($request->get('midcom_services_auth_login_success_url')) {
143
                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

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