File: Consumer.php

package info (click to toggle)
simplesamlphp 1.19.7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 42,920 kB
  • sloc: php: 202,044; javascript: 14,867; xml: 2,700; sh: 225; perl: 82; makefile: 70; python: 5
file content (251 lines) | stat: -rw-r--r-- 7,522 bytes parent folder | download | duplicates (3)
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<?php

namespace SimpleSAML\Module\oauth;

require_once(dirname(dirname(__FILE__)).'/libextinc/OAuth.php');

/**
 * OAuth Consumer
 *
 * @author Andreas Åkre Solberg, <andreas.solberg@uninett.no>, UNINETT AS.
 * @package SimpleSAMLphp
 */
class Consumer
{
    /** @var \OAuthConsumer */
    private $consumer;

    /** @var \OAuthSignatureMethod */
    private $signer;


    /**
     * @param string $key
     * @param string $secret
     */
    public function __construct($key, $secret)
    {
        $this->consumer = new \OAuthConsumer($key, $secret, null);
        $this->signer = new \OAuthSignatureMethod_HMAC_SHA1();
    }


    /**
     * Used only to load the libextinc library early
     * @return void
     */
    public static function dummy()
    {
    }


    /**
     * @param array $hrh
     * @return string|null
     */
    public static function getOAuthError($hrh)
    {
        foreach ($hrh as $h) {
            if (preg_match('|OAuth-Error:\s([^;]*)|i', $h, $matches)) {
                return $matches[1];
            }
        }
        return null;
    }


    /**
     * @param array $hrh
     * @return string|null
     */
    public static function getContentType($hrh)
    {
        foreach ($hrh as $h) {
            if (preg_match('|Content-Type:\s([^;]*)|i', $h, $matches)) {
                return $matches[1];
            }
        }
        return null;
    }


    /**
     * This static helper function wraps \SimpleSAML\Utils\HTTP::fetch
     * and throws an exception with diagnostics messages if it appear
     * to be failing on an OAuth endpoint.
     *
     * If the status code is not 200, an exception is thrown. If the content-type
     * of the response if text/plain, the content of the response is included in
     * the text of the Exception thrown.
     *
     * @param string $url
     * @param string $context
     * @return string
     * @throws \Exception
     */
    public static function getHTTP($url, $context = '')
    {
        try {
            $response = \SimpleSAML\Utils\HTTP::fetch($url, [], false);
        } catch (\SimpleSAML\Error\Exception $e) {
            $statuscode = 'unknown';

            /** @psalm-suppress UndefinedVariable */
            if (preg_match('/^HTTP.*\s([0-9]{3})/', $http_response_header[0], $matches)) {
                $statuscode = $matches[1];
            }

            $error = $context.' [statuscode: '.$statuscode.']: ';
            /** @psalm-suppress UndefinedVariable */
            $oautherror = self::getOAuthError($http_response_header);

            if (!empty($oautherror)) {
                $error .= $oautherror;
            }

            throw new \Exception($error.':'.$url);
        }
        // Fall back to return response, if could not reckognize HTTP header. Should not happen.
        /** @var string $response */
        return $response;
    }


    /**
     * @param string $url
     * @param array|null $parameters
     * @return \OAuthToken
     * @throws \Exception
     */
    public function getRequestToken($url, $parameters = null)
    {
        $req_req = \OAuthRequest::from_consumer_and_token($this->consumer, null, "GET", $url, $parameters);
        $req_req->sign_request($this->signer, $this->consumer, null);

        $response_req = self::getHTTP(
            $req_req->to_url(),
            'Contacting request_token endpoint on the OAuth Provider'
        );

        parse_str($response_req, $responseParsed);

        if (array_key_exists('error', $responseParsed)) {
            throw new \Exception('Error getting request token: '.$responseParsed['error']);
        }

        $requestToken = $responseParsed['oauth_token'];
        $requestTokenSecret = $responseParsed['oauth_token_secret'];

        return new \OAuthToken($requestToken, $requestTokenSecret);
    }


    /**
     * @param string $url
     * @param \OAuthToken $requestToken
     * @param bool $redirect
     * @param callable|null $callback
     * @return string
     */
    public function getAuthorizeRequest($url, $requestToken, $redirect = true, $callback = null)
    {
        $params = ['oauth_token' => $requestToken->key];
        if ($callback) {
            $params['oauth_callback'] = $callback;
        }
        $authorizeURL = \SimpleSAML\Utils\HTTP::addURLParameters($url, $params);
        if ($redirect) {
            \SimpleSAML\Utils\HTTP::redirectTrustedURL($authorizeURL);
            exit;
        }
        return $authorizeURL;
    }


    /**
     * @param string $url
     * @param \OAuthToken $requestToken
     * @param array|null $parameters
     * @return \OAuthToken
     * @throws \Exception
     */
    public function getAccessToken($url, $requestToken, $parameters = null)
    {
        $acc_req = \OAuthRequest::from_consumer_and_token($this->consumer, $requestToken, "GET", $url, $parameters);
        $acc_req->sign_request($this->signer, $this->consumer, $requestToken);

        try {
            /** @var string $response_acc */
            $response_acc = \SimpleSAML\Utils\HTTP::fetch($acc_req->to_url(), [], false);
        } catch (\SimpleSAML\Error\Exception $e) {
            throw new \Exception('Error contacting request_token endpoint on the OAuth Provider');
        }

        \SimpleSAML\Logger::debug('oauth: Reponse to get access token: '.$response_acc);

        $accessResponseParsed = [];
        parse_str($response_acc, $accessResponseParsed);

        if (array_key_exists('error', $accessResponseParsed)) {
            throw new \Exception('Error getting request token: '.$accessResponseParsed['error']);
        }

        $accessToken = $accessResponseParsed['oauth_token'];
        $accessTokenSecret = $accessResponseParsed['oauth_token_secret'];

        return new \OAuthToken($accessToken, $accessTokenSecret);
    }


    /**
     * @param string $url
     * @param \OAuthToken $accessToken
     * @param array $parameters
     * @return array|string
     * @throws \SimpleSAML\Error\Exception
     */
    public function postRequest($url, $accessToken, $parameters)
    {
        $data_req = \OAuthRequest::from_consumer_and_token($this->consumer, $accessToken, "POST", $url, $parameters);
        $data_req->sign_request($this->signer, $this->consumer, $accessToken);
        $postdata = $data_req->to_postdata();

        $opts = [
            'ssl' => [
                'verify_peer' => false,
                'capture_peer_cert' => true,
                'capture_peer_chain' => true
            ],
            'http' => [
                'method' => 'POST',
                'content' => $postdata,
                'header' => 'Content-Type: application/x-www-form-urlencoded',
            ],
        ];

        try {
            $response = \SimpleSAML\Utils\HTTP::fetch($url, $opts);
        } catch (\SimpleSAML\Error\Exception $e) {
            throw new \SimpleSAML\Error\Exception('Failed to push definition file to '.$url);
        }
        return $response;
    }


    /**
     * @param string $url
     * @param \OAuthToken $accessToken
     * @param array $opts
     * @return array|null
     */
    public function getUserInfo($url, $accessToken, $opts = [])
    {
        $data_req = \OAuthRequest::from_consumer_and_token($this->consumer, $accessToken, "GET", $url, null);
        $data_req->sign_request($this->signer, $this->consumer, $accessToken);

        /** @var string $data */
        $data = \SimpleSAML\Utils\HTTP::fetch($data_req->to_url(), $opts);

        return json_decode($data, true);
    }
}