1<?php
2
3use dokuwiki\plugin\oauth\Adapter;
4use dokuwiki\plugin\oauth\Exception;
5use dokuwiki\plugin\oauthdiscordserver\Discord;
6
7/**
8 * Service Implementation for oAuth Doorkeeper authentication
9 */
10class action_plugin_oauthdiscordserver extends Adapter
11{
12    /**
13     * @inheritdoc
14     */
15    public function registerServiceClass()
16    {
17        return Discord::class;
18    }
19
20    /**
21     * @inheritDoc
22     */
23    public function getUser()
24    {
25        $oauth = $this->getOAuthService();
26        $data = array();
27
28        $requestURL = 'https://discord.com/api/users/@me/guilds';
29        $result = json_decode($oauth->request($requestURL), true);
30        if ($result === NULL) throw new Exception("No response received for server list");
31
32        $inServer = false;
33        $serverID = $this->getConf('serverID');
34        foreach ($result as $server) {
35            if ($server['id'] == $serverID) $inServer = true;
36        }
37
38        if (!$inServer) throw new Exception('Not a member of the correct server');
39
40        $requestURL .= '/' . $serverID . '/member';
41        $result = json_decode($oauth->request($requestURL), true);
42
43        if (!$result || !$result['user']) throw new Exception("No response received for server membership");
44
45        $roleID = $this->getConf('roleID');
46        if ($roleID) {
47            $inRole = false;
48            foreach ($result['roles'] as $role) {
49                if ($role == $roleID) $inRole = true;
50            }
51            if (!$inRole) throw new Exception("User doesn't have the correct role");
52        }
53
54        // prefer server nickname, if none, use user global name, if none, use username
55        $prefs = [$result['nick'], $result['user']['global_name'], $result['user']['username']];
56        $i = 0;
57        while (!($prefs[$i] || $prefs[$i] === "0")) $i++;
58        $data['user'] = $prefs[$i];
59        $data['name'] = $prefs[$i];
60        $data['mail'] = $result['user']['id'] . "@discord.com";
61
62        return $data;
63    }
64
65    /**
66     * @inheritdoc
67     */
68    public function getScopes()
69    {
70        return [Discord::SCOPE_MEMBER, Discord::SCOPE_SERVERS];
71    }
72
73    /**
74     * @inheritDoc
75     */
76    public function getLabel()
77    {
78        return 'Discord';
79    }
80
81    /**
82     * @inheritDoc
83     */
84    public function getColor()
85    {
86        return '#7289da';
87    }
88}
89