1<?php
2/**
3 *
4 * This file is part of the phpBB Forum Software package.
5 *
6 * @copyright (c) phpBB Limited <https://www.phpbb.com>
7 * @license GNU General Public License, version 2 (GPL-2.0)
8 *
9 * For full copyright and license information, please see
10 * the docs/CREDITS.txt file.
11 *
12 */
13
14namespace phpbb\auth\provider\oauth\service;
15
16/**
17 * Bitly OAuth service
18 */
19class bitly extends base
20{
21	/** @var \phpbb\config\config */
22	protected $config;
23
24	/** @var \phpbb\request\request_interface */
25	protected $request;
26
27	/**
28	 * Constructor.
29	 *
30	 * @param \phpbb\config\config				$config		Config object
31	 * @param \phpbb\request\request_interface	$request	Request object
32	 */
33	public function __construct(\phpbb\config\config $config, \phpbb\request\request_interface $request)
34	{
35		$this->config	= $config;
36		$this->request	= $request;
37	}
38
39	/**
40	 * {@inheritdoc}
41	 */
42	public function get_service_credentials()
43	{
44		return [
45			'key'		=> $this->config['auth_oauth_bitly_key'],
46			'secret'	=> $this->config['auth_oauth_bitly_secret'],
47		];
48	}
49
50	/**
51	 * {@inheritdoc}
52	 */
53	public function perform_auth_login()
54	{
55		if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Bitly))
56		{
57			throw new exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE');
58		}
59
60		try
61		{
62			// This was a callback request, get the token
63			$this->service_provider->requestAccessToken($this->request->variable('code', ''));
64		}
65		catch (\OAuth\Common\Http\Exception\TokenResponseException $e)
66		{
67			throw new exception('AUTH_PROVIDER_OAUTH_ERROR_REQUEST');
68		}
69
70		try
71		{
72			// Send a request with it
73			$result = (array) json_decode($this->service_provider->request('user/info'), true);
74		}
75		catch (\OAuth\Common\Exception\Exception $e)
76		{
77			throw new exception('AUTH_PROVIDER_OAUTH_ERROR_REQUEST');
78		}
79
80		// Prevent SQL error
81		if (!isset($result['data']['login']))
82		{
83			throw new exception('AUTH_PROVIDER_OAUTH_RETURN_ERROR');
84		}
85
86		// Return the unique identifier returned from bitly
87		return $result['data']['login'];
88	}
89
90	/**
91	 * {@inheritdoc}
92	 */
93	public function perform_token_auth()
94	{
95		if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Bitly))
96		{
97			throw new exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE');
98		}
99
100		try
101		{
102			// Send a request with it
103			$result = (array) json_decode($this->service_provider->request('user/info'), true);
104		}
105		catch (\OAuth\Common\Exception\Exception $e)
106		{
107			throw new exception('AUTH_PROVIDER_OAUTH_ERROR_REQUEST');
108		}
109
110		// Prevent SQL error
111		if (!isset($result['data']['login']))
112		{
113			throw new exception('AUTH_PROVIDER_OAUTH_RETURN_ERROR');
114		}
115
116		// Return the unique identifier
117		return $result['data']['login'];
118	}
119}
120