1<?php
2/*
3 * vim:set softtabstop=4 shiftwidth=4 expandtab:
4 *
5 * LICENSE: GNU Affero General Public License, version 3 (AGPL-3.0-or-later)
6 * Copyright 2001 - 2020 Ampache.org
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20 *
21 */
22
23declare(strict_types=0);
24
25namespace Ampache\Module\Authentication\Authenticator;
26
27use Ampache\Config\AmpConfig;
28
29final class ExternalAuthenticator implements AuthenticatorInterface
30{
31    public function auth(string $username, string $password): array
32    {
33        $authenticator = AmpConfig::get('external_authenticator');
34        if (!$authenticator) {
35            return array(
36                'success' => false,
37                'error' => 'No external authenticator configured'
38            );
39        }
40
41        // FIXME: should we do input sanitization?
42        $proc = proc_open($authenticator, array(
43            0 => array('pipe', 'r'),
44            1 => array('pipe', 'w'),
45            2 => array('pipe', 'w')
46        ), $pipes);
47
48        if (is_resource($proc)) {
49            fwrite($pipes[0], $username . "\n" . $password . "\n");
50            fclose($pipes[0]);
51            fclose($pipes[1]);
52            if ($stderr = fread($pipes[2], 8192)) {
53                debug_event(__CLASS__, "external_auth fread error: " . $stderr, 3);
54            }
55            fclose($pipes[2]);
56        } else {
57            return array(
58                'success' => false,
59                'error' => 'Failed to run external authenticator'
60            );
61        }
62
63        if (proc_close($proc) == 0) {
64            return array(
65                'success' => true,
66                'type' => 'external',
67                'username' => $username
68            );
69        }
70
71        return array(
72            'success' => false,
73            'error' => 'The external authenticator did not accept the login'
74        );
75    }
76
77    public function postAuth(): ?array
78    {
79        return null;
80    }
81}
82