friendship ended with social-app. php is my new best friend
1<?php
2/**
3 * Class Imgur
4 *
5 * @created 28.07.2019
6 * @author smiley <smiley@chillerlan.net>
7 * @copyright 2019 smiley
8 * @license MIT
9 */
10declare(strict_types=1);
11
12namespace chillerlan\OAuth\Providers;
13
14use chillerlan\OAuth\Core\{AccessToken, AuthenticatedUser, CSRFToken, OAuth2Provider, TokenRefresh, UserInfo};
15use function sprintf, time;
16
17/**
18 * Imgur OAuth2
19 *
20 * Note: imgur sends an "expires_in" of 315360000 (10 years!) for access tokens,
21 * but states in the docs that tokens expire after one month.
22 *
23 * @link https://apidocs.imgur.com/
24 */
25class Imgur extends OAuth2Provider implements CSRFToken, TokenRefresh, UserInfo{
26
27 public const IDENTIFIER = 'IMGUR';
28
29 protected string $authorizationURL = 'https://api.imgur.com/oauth2/authorize';
30 protected string $accessTokenURL = 'https://api.imgur.com/oauth2/token';
31 protected string $apiURL = 'https://api.imgur.com';
32 protected string|null $userRevokeURL = 'https://imgur.com/account/settings/apps';
33 protected string|null $apiDocs = 'https://apidocs.imgur.com';
34 protected string|null $applicationURL = 'https://api.imgur.com/oauth2/addclient';
35
36 public function getAccessToken(string $code, string|null $state = null):AccessToken{
37 $this->checkState($state);
38
39 $body = $this->getAccessTokenRequestBodyParams($code);
40 $response = $this->sendAccessTokenRequest($this->accessTokenURL, $body);
41 $token = $this->parseTokenResponse($response);
42
43 // set the expiry to a sane period to allow auto-refreshing
44 $token->expires = (time() + 2592000); // 30 days
45
46 $this->storage->storeAccessToken($token, $this->name);
47
48 return $token;
49 }
50
51 /** @codeCoverageIgnore */
52 public function me():AuthenticatedUser{
53 $json = $this->getMeResponseData('/3/account/me');
54
55 $userdata = [
56 'data' => $json,
57 'avatar' => $json['data']['avatar'],
58 'handle' => $json['data']['url'],
59 'id' => $json['data']['id'],
60 'url' => sprintf('https://imgur.com/user/%s', $json['data']['url']),
61 ];
62
63 return new AuthenticatedUser($userdata);
64 }
65
66}