1<?php
2
3use dokuwiki\plugin\oauth\OAuthManager;
4use dokuwiki\plugin\oauth\Session;
5use dokuwiki\Subscriptions\RegistrationSubscriptionSender;
6use OAuth\Common\Exception\Exception as OAuthException;
7
8/**
9 * DokuWiki Plugin oauth (Auth Component)
10 *
11 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
12 * @author  Andreas Gohr <andi@splitbrain.org>
13 */
14class auth_plugin_oauth extends auth_plugin_authplain
15{
16    /** @var helper_plugin_oauth */
17    protected $hlp;
18
19    /** @var OAuthManager */
20    protected $om;
21
22    // region standard auth methods
23
24    /** @inheritDoc */
25    public function __construct()
26    {
27        parent::__construct();
28        $this->cando['external'] = true;
29        $this->hlp = $this->loadHelper('oauth');
30    }
31
32    /** @inheritDoc */
33    public function trustExternal($user, $pass, $sticky = false)
34    {
35        global $INPUT;
36
37        // handle redirects from farmer to animal wiki instances
38        if ($INPUT->has('state') && plugin_load('helper', 'farmer')) {
39            $this->handleFarmState($INPUT->str('state'));
40        }
41
42        try {
43            // either oauth or "normal" plain auth login via form
44            $this->om = new OAuthManager();
45            if ($this->om->continueFlow()) return true;
46            if ($this->getConf('singleService')) {
47                return false; // no normal login in singleService mode
48            }
49            return null; // triggers the normal auth_login()
50        } catch (OAuthException $e) {
51            $this->hlp->showException($e);
52            auth_logoff(); // clears all session and cookie data
53            return false;
54        }
55    }
56
57    /**
58     * Enhance function to check against duplicate emails
59     *
60     * @inheritdoc
61     */
62    public function createUser($user, $pwd, $name, $mail, $grps = null)
63    {
64        if ($this->getUserByEmail($mail)) {
65            msg($this->getLang('emailduplicate'), -1);
66            return false;
67        }
68
69        return parent::createUser($user, $pwd, $name, $mail, $grps);
70    }
71
72    /**
73     * Enhance function to check against duplicate emails
74     *
75     * @inheritdoc
76     */
77    public function modifyUser($user, $changes)
78    {
79        global $conf;
80
81        if (isset($changes['mail'])) {
82            $found = $this->getUserByEmail($changes['mail']);
83            if ($found && $found != $user) {
84                msg($this->getLang('emailduplicate'), -1);
85                return false;
86            }
87        }
88
89        $ok = parent::modifyUser($user, $changes);
90
91        // refresh session cache
92        touch($conf['cachedir'] . '/sessionpurge');
93        return $ok;
94    }
95
96    /**
97     * Unset additional stuff in session on logout
98     */
99    public function logOff()
100    {
101        parent::logOff();
102        if (isset($this->om)) {
103            $this->om->logout();
104        }
105        (Session::getInstance())->clear();
106    }
107
108    // endregion
109
110    /**
111     * Register a new user logged in by oauth
112     *
113     * It ensures the username is unique, by adding a number if needed.
114     * Default and service name groups are set here.
115     * Registration notifications are triggered.
116     *
117     * @param array $userinfo This will be updated with the new username
118     * @param string $servicename
119     *
120     * @return bool
121     * @todo - should this be part of the OAuthManager class instead?
122     */
123    public function registerOAuthUser(&$userinfo, $servicename)
124    {
125        global $conf;
126        $user = $userinfo['user'];
127        $count = '';
128        while ($this->getUserData($user . $count)) {
129            if ($count) {
130                $count++;
131            } else {
132                $count = 1;
133            }
134        }
135        $user .= $count;
136        $userinfo['user'] = $user;
137        $groups_on_creation = [];
138        $groups_on_creation[] = $conf['defaultgroup'];
139        $groups_on_creation[] = $this->cleanGroup($servicename); // add service as group
140        $userinfo['grps'] = array_merge((array)$userinfo['grps'], $groups_on_creation);
141
142        // the password set here will remain unknown to the user
143        $ok = $this->triggerUserMod(
144            'create',
145            [
146                $user,
147                auth_pwgen($user),
148                $userinfo['name'],
149                $userinfo['mail'],
150                $userinfo['grps'],
151            ]
152        );
153        if (!$ok) {
154            return false;
155        }
156
157        // send notification about the new user
158        $subscriptionSender = new RegistrationSubscriptionSender();
159        $subscriptionSender->sendRegister($user, $userinfo['name'], $userinfo['mail']);
160
161        return true;
162    }
163
164    /**
165     * Find a user by email address
166     *
167     * @param $mail
168     * @return bool|string
169     */
170    public function getUserByEmail($mail)
171    {
172        if ($this->users === null) {
173            $this->loadUserData();
174        }
175        $mail = strtolower($mail);
176
177        foreach ($this->users as $user => $userinfo) {
178            if (strtolower($userinfo['mail']) === $mail) return $user;
179        }
180
181        return false;
182    }
183
184    /**
185     * Fall back to plain auth strings
186     *
187     * @inheritdoc
188     */
189    public function getLang($id)
190    {
191        $result = parent::getLang($id);
192        if ($result) return $result;
193
194        $parent = new auth_plugin_authplain();
195        return $parent->getLang($id);
196    }
197
198    /**
199     * Farmer plugin support
200     *
201     * When coming back to farmer instance via OAUTH redirectURI, we need to redirect again
202     * to a proper animal instance detected from $state
203     *
204     * @param $state
205     */
206    protected function handleFarmState($state)
207    {
208        /** @var \helper_plugin_farmer $farmer */
209        $farmer = plugin_load('helper', 'farmer', false, true);
210        $data = json_decode(base64_decode(urldecode($state)));
211        if (empty($data->animal) || $farmer->getAnimal() == $data->animal) {
212            return;
213        }
214        $animal = $data->animal;
215        $allAnimals = $farmer->getAllAnimals();
216        if (!in_array($animal, $allAnimals)) {
217            msg('Animal ' . $animal . ' does not exist!');
218            return;
219        }
220        global $INPUT;
221        $url = $farmer->getAnimalURL($animal) . '/doku.php?' . $INPUT->server->str('QUERY_STRING');
222        send_redirect($url);
223    }
224}
225