aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/api/oauth2/clients.php
blob: edf11709ef14d1d57956152a96280778686271f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
<?php

use Studip\OAuth2\Models\Client;

class Api_Oauth2_ClientsController extends AuthenticatedController
{
    /**
     * @param string $action
     * @param string[] $args
     *
     * @return void
     */
    public function before_filter(&$action, &$args)
    {
        parent::before_filter($action, $args);

        $GLOBALS['perm']->check('root');
    }

    public function add_action(): void
    {
        Navigation::activateItem('/admin/config/oauth2');
        PageLayout::setTitle(_('OAuth2-Client hinzufügen'));
    }

    public function store_action(): void
    {
        CSRFProtection::verifyUnsafeRequest();

        $this->redirect('admin/oauth2');

        [$valid, $data, $errors] = $this->validateCreateClientRequest();

        if (!$valid) {
            PageLayout::postError(_('Das Erstellen eines OAuth2-Clients war nicht erfolgreich.'), $errors);
            return;
        }

        $client = $this->createAuthCodeClient($data);
        $this->outputClientCredentials($client);
    }

    public function delete_action(Client $client): void
    {
        CSRFProtection::verifyUnsafeRequest();

        $clientId = $client['id'];
        $clientName = $client['name'];
        $client->delete();

        PageLayout::postSuccess(sprintf(_('Der OAuth2-Client #%d ("%s") wurde gelöscht.'), $clientId, $clientName));
        $this->redirect('admin/oauth2');
    }

    /**
     * Create a authorization code client.
     *
     * @param array<string, mixed> $data
     */
    private function createAuthCodeClient(array $data): Client
    {
        return Client::createClient(
            $data['name'],
            $data['redirect'],
            $data['confidential'],
            $data['owner'],
            $data['homepage'],
            $data['description'],
            $data['admin_notes']
        );
    }

    /**
     * Show feedback to the user depending on the confidentiality of the `$client`.
     */
    private function outputClientCredentials(Client $client): void
    {
        if ($client->confidential()) {
            $this->flash['oauth2-message'] = MessageBox::warning(
                _('Der OAuth2-Client wurde erstellt.'),
                [
                    sprintf(
                        _('Die <em lang="en"> client_id </em> lautet: <pre>%s</pre>'),
                        htmlReady($client['id'])
                    ),
                    sprintf(
                        _('Das <em lang="en"> client_secret </em> lautet: <pre>%s</pre>'),
                        htmlReady($client->plainsecret)
                    ),
                    _('Notieren Sie sich bitte das <em lang="en"> client_secret </em>. Es wird Ihnen nur <strong> dieses eine Mal </strong> angezeigt.'),
                ]
            );
        } else {
            $this->flash['oauth2-message'] = MessageBox::success(
                _('Der OAuth2-Client wurde erstellt.'),
                [
                    sprintf(
                        _('Die <em lang="en"> client_id </em> lautet: <pre>%s</pre>'),
                        htmlReady($client['id'])
                    ),
                ]
            );
        }
    }

    /**
     * Validate the request parameters when creating a new client.
     *
     * @return array{0: bool, 1: array<string, mixed>, 2: string[]}
     */
    private function validateCreateClientRequest()
    {
        $valid = true;
        $data = [];
        $errors = [];

        // required
        $name = Request::get('name');
        $redirectURIs = Request::get('redirect');
        $confidentiality = Request::get('confidentiality');
        $owner = Request::get('owner');
        $homepage = Request::get('homepage');

        // optional
        $data['description'] = Request::get('description');
        $data['admin_notes'] = Request::get('admin_notes');

        foreach (compact('name', 'redirectURIs', 'confidentiality', 'owner', 'homepage') as $key => $value) {
            if (!isset($value)) {
                $errors[] = sprintf(_('Parameter "%s" fehlt.'), $key);
                $valid = false;
            }
        }

        // validate $name
        $data['name'] = trim($name);
        if ($name === '') {
            $errors[] = _('Der Parameter "name" darf nicht leer sein.');
            $valid = false;
        }

        // validate $redirectURIS
        $redirect = [];
        $redirectLines = preg_split("/[\n\r]/", $redirectURIs, -1, PREG_SPLIT_NO_EMPTY);
        foreach ($redirectLines as $line) {
            $url = filter_var($line, FILTER_SANITIZE_URL);
            if (false === filter_var($url, FILTER_VALIDATE_URL)) {
                $errors = _('Der Parameter "redirect" darf nur gültige URLs enthalten.');
                $valid = false;
                break;
            }
            $redirect[] = $url;
        }
        $data['redirect'] = join(',', $redirect);

        // validate $confidentiality
        if (!in_array($confidentiality, ['public', 'confidential'])) {
            $errors[] = _('Der Parameter "confidentiality" darf nur gültige URLs enthalten.');
            $valid = false;
        }
        $data['confidential'] = $confidentiality === 'confidential';

        // validate $owner
        $data['owner'] = trim($owner);
        if ($owner === '') {
            $errors[] = _('Der Parameter "owner" darf nicht leer sein.');
            $valid = false;
        }

        // validate $homepage
        $data['homepage'] = filter_var($homepage, FILTER_SANITIZE_URL);
        if (false === filter_var($homepage, FILTER_VALIDATE_URL)) {
            $errors = _('Der Parameter "homepage" muss eine gültige URL enthalten.');
            $valid = false;
        }

        return [$valid, $data, $errors];
    }
}