Skip to content
Snippets Groups Projects
Commit 5f53bd5d authored by David Pashaev's avatar David Pashaev
Browse files

Issue #3364413 by davps, ALexeyAL1: Make compatible version with Social Auth 4.x

parent ed03cce0
No related branches found
No related tags found
1 merge request!1Issue #3364413: Make compatible version with Social Auth 4.x
Pipeline #127203 passed with warnings
Showing
with 415 additions and 422 deletions
......@@ -8,12 +8,12 @@
"minimum-stability": "dev",
"support": {
"issues": "https://www.drupal.org/project/issues/social_auth_vk",
"source": "http://cgit.drupalcode.org/social_auth_vk"
"source": "https://git.drupalcode.org/project/social_auth_vk"
},
"require": {
"vkcom/vk-php-sdk": "^5.80",
"drupal/social_auth": "^3",
"drupal/core": "^8 || ^9 || ^10"
"vkcom/vk-php-sdk": "^5.100",
"drupal/social_auth": "^4",
"drupal/core": "^9 || ^10"
},
"authors": [
{
......
social_auth_vk.settings:
type: config_object
label: 'Social Auth Vkontakte settings'
label: 'Social Auth VK settings'
mapping:
client_id:
type: string
......
<svg width="101" height="100" viewBox="0 0 101 100" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_2_40)">
<path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#0077FF"/>
<path d="M53.7085 72.042C30.9168 72.042 17.9169 56.417 17.3752 30.417H28.7919C29.1669 49.5003 37.5834 57.5836 44.25 59.2503V30.417H55.0004V46.8752C61.5837 46.1669 68.4995 38.667 70.8329 30.417H81.5832C79.7915 40.5837 72.2915 48.0836 66.9582 51.1669C72.2915 53.6669 80.8336 60.2086 84.0836 72.042H72.2499C69.7082 64.1253 63.3754 58.0003 55.0004 57.1669V72.042H53.7085Z" fill="white"/>
</g>
<defs>
<clipPath id="clip0_2_40">
<rect width="100" height="100" fill="white" transform="translate(0.5)"/>
</clipPath>
</defs>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="192" height="192" viewBox="0 0 192 192">
<g fill="none" fill-rule="evenodd">
<path fill="#5181B8" d="M66.56,0 C120.32,0 71.68,0 125.44,0 C179.2,0 192,12.8 192,66.56 C192,120.32 192,71.68 192,125.44 C192,179.2 179.2,192 125.44,192 C71.68,192 120.32,192 66.56,192 C12.8,192 0,179.2 0,125.44 C0,71.68 0,96.580329 0,66.56 C0,12.8 12.8,0 66.56,0 Z"/>
<path fill="#FFFFFF" d="M157.233993,66.1462211 C158.123557,63.1797719 157.233994,61 153.000244,61 L139.000244,61 C135.440505,61 133.799415,62.8830035 132.909356,64.9593945 C132.909356,64.9593945 125.789878,82.3129373 115.704198,93.5851974 C112.441227,96.8481681 110.957879,97.8863636 109.178009,97.8863636 C108.288198,97.8863636 107,96.8481681 107,93.8819658 L107,66.1462211 C107,62.586482 105.96694,61 103.000244,61 L81.0002441,61 C78.7757158,61 77.4378669,62.6521562 77.4378669,64.2179674 C77.4378669,67.5925348 82.4804603,68.3707494 83.0002441,77.8633869 L83.0002441,98.4799003 C83.0002441,103 82.1839388,103.819509 80.4040693,103.819509 C75.6579974,103.819509 64.1131647,86.388441 57.2660122,66.4427426 C55.9241353,62.5659897 54.5782535,61 51.0002441,61 L37.0002441,61 C33.0002441,61 32.2001953,62.8830035 32.2001953,64.9593945 C32.2001953,68.6675178 36.9465141,87.059256 54.2998099,111.383646 C65.8685915,127.995268 82.1682449,137 97.0002441,137 C105.899345,137 107.000244,135 107.000244,131.555007 L107.000244,119 C107.000244,115 107.843292,114.201711 110.661357,114.201711 C112.737749,114.201711 116.297488,115.239906 124.603545,123.249196 C134.095936,132.741586 135.660882,137 141.000244,137 L155.000244,137 C159.000244,137 161.000244,135 159.846475,131.053112 C158.583906,127.119411 154.051802,121.412135 148.038124,114.646617 C144.774906,110.790356 139.88045,106.637574 138.397102,104.560689 C136.320711,101.891255 136.914001,100.704429 138.397102,98.3315162 C138.397102,98.3315162 155.454123,74.3036478 157.233993,66.1462211 Z"/>
</g>
</svg>
......@@ -2,7 +2,11 @@ name: Social Auth Vkontakte
type: module
description: 'Social Auth integration for Vkontakte.'
package: Social
core_version_requirement: ^8 || ^9 || ^10
configure: social_auth_vk.settings_form
core_version_requirement: ^9 || ^10
configure: social_auth.network.settings_form
configure_parameters:
network: 'vk'
dependencies:
- social_auth:social_auth
......@@ -5,18 +5,12 @@
* Install, update, and uninstall functions for Social Auth Vkontakte.
*/
use Drupal\social_auth\Controller\SocialAuthController;
/**
* Implements hook_install().
*/
function social_auth_vk_install() {
SocialAuthController::setLoginButtonSettings('social_auth_vk', 'social_auth_vk.redirect_to_vkontakte', 'img/vkontakte_logo.svg');
}
function social_auth_vk_install() {}
/**
* Implements hook_uninstall().
*/
function social_auth_vk_uninstall() {
SocialAuthController::deleteLoginButtonSettings('social_auth_vk');
}
function social_auth_vk_uninstall() {}
social_auth_vk.settings.tab:
title: 'Vkontakte'
route_name: social_auth_vk.settings_form
title: 'VK'
route_name: social_auth.network.settings_form
route_parameters:
network: 'vk'
base_route: social_auth.integrations
......@@ -2,7 +2,7 @@
/**
* @file
* Hook implementations for Social Auth Vkontakte module.
* Hook implementations for Social Auth Vk module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
......@@ -14,7 +14,7 @@ function social_auth_vk_help($route_name, RouteMatchInterface $route_match) {
$output = '';
switch ($route_name) {
case 'simple_vkontakte_connect.settings_form':
case 'help.page.social_auth_vk':
$output = '<h3>' . t('Configuration instructions') . '</h3>';
$output .= '<p>';
$output .= t('Configuration instructions and other useful documentation can be found from <a href="@handbook-url">Social Auth Vkontakte Handbook</a>.', ['@handbook-url' => 'https://www.drupal.org/node/2764227']);
......
social_auth_vk.redirect_to_vkontakte:
path: 'user/login/vkontakte'
defaults:
_controller: '\Drupal\social_auth_vk\Controller\VkontakteAuthController::redirectToProvider'
requirements:
# Anonymous users can log in, but authenticated users can also associate a new provider.
_access: 'TRUE'
options:
no_cache: TRUE
social_auth_vk.callback:
path: 'user/login/vkontakte/callback'
defaults:
_controller: '\Drupal\social_auth_vk\Controller\VkontakteAuthController::callback'
requirements:
# Anonymous users can log in, but authenticated users can also associate a new provider.
_access: 'TRUE'
options:
no_cache: TRUE
social_auth_vk.settings_form:
path: 'admin/config/social-api/social-auth/vkontakte'
defaults:
_title: 'Social Auth Vkontakte settings'
_form: '\Drupal\social_auth_vk\Form\VkontakteAuthSettingsForm'
requirements:
_permission: 'administer social api authentication'
services:
social_auth_vk.manager:
class: Drupal\social_auth_vk\VkontakteAuthManager
class: Drupal\social_auth_vk\VkAuthManager
arguments:
- '@config.factory'
- '@logger.factory'
......
<?php
namespace Drupal\social_auth_vk\Controller;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\social_api\Plugin\NetworkManager;
use Drupal\social_auth\Controller\OAuth2ControllerBase;
use Drupal\social_auth\SocialAuthDataHandler;
use Drupal\social_auth\User\UserAuthenticator;
use Drupal\social_auth_vk\VkontakteAuthManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Returns responses for Social Auth Vkontakte routes.
*/
class VkontakteAuthController extends OAuth2ControllerBase {
/**
* VkontakteAuthController constructor.
*
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger service.
* @param \Drupal\social_api\Plugin\NetworkManager $network_manager
* Used to get an instance of social_auth_vk network plugin.
* @param \Drupal\social_auth\User\UserAuthenticator $user_authenticator
* Used to manage user authentication/registration.
* @param \Drupal\social_auth_vk\VkontakteAuthManager $vk_manager
* Used to manage authentication methods.
* @param \Symfony\Component\HttpFoundation\RequestStack $request
* Used to access GET parameters.
* @param \Drupal\social_auth\SocialAuthDataHandler $data_handler
* The Social Auth data handler.
*/
public function __construct(MessengerInterface $messenger,
NetworkManager $network_manager,
UserAuthenticator $user_authenticator,
VkontakteAuthManager $vk_manager,
RequestStack $request,
SocialAuthDataHandler $data_handler) {
parent::__construct('Social Auth Vkontakte', 'social_auth_vk', $messenger, $network_manager, $user_authenticator, $vk_manager, $request, $data_handler);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('messenger'),
$container->get('plugin.network.manager'),
$container->get('social_auth.user_authenticator'),
$container->get('social_auth_vk.manager'),
$container->get('request_stack'),
$container->get('social_auth.data_handler')
);
}
/**
* Response for path 'user/login/vkontakte/callback'.
*
* Vkontakte returns the user here after user has authenticated.
*/
public function callback() {
// Checks if authentication failed.
if ($this->request->getCurrentRequest()->query->has('error')) {
$this->messenger->addError($this->t('You could not be authenticated.'));
return $this->redirect('user.login');
}
/* @var array|null $profile */
$profile = $this->processCallback();
// If authentication was successful.
if ($profile !== NULL) {
$full_name = $profile['first_name'] . ' ' . $profile['last_name'];
return $this->userAuthenticator->authenticateUser($full_name, $profile['email'], $profile['id'], $this->providerManager->getAccessToken(), $profile['photo_max_orig'], NULL);
}
return $this->redirect('user.login');
}
}
<?php
namespace Drupal\social_auth_vk\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Path\PathValidatorInterface;
use Drupal\Core\Routing\RequestContext;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\social_auth\Form\SocialAuthSettingsForm;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Settings form for Social Auth Vkontakte.
*/
class VkontakteAuthSettingsForm extends SocialAuthSettingsForm {
/**
* The request context.
*
* @var \Drupal\Core\Routing\RequestContext
*/
protected $requestContext;
/**
* Constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
* Used to check if route exists.
* @param \Drupal\Core\Path\PathValidatorInterface $path_validator
* Used to check if path is valid and exists.
* @param \Drupal\Core\Routing\RequestContext $request_context
* Holds information about the current request.
*/
public function __construct(ConfigFactoryInterface $config_factory, RouteProviderInterface $route_provider, PathValidatorInterface $path_validator, RequestContext $request_context) {
parent::__construct($config_factory, $route_provider, $path_validator);
$this->requestContext = $request_context;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
// Instantiates this class.
return new static(
// Load the services required to construct this class.
$container->get('config.factory'),
$container->get('router.route_provider'),
$container->get('path.validator'),
$container->get('router.request_context')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'social_auth_vk_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return array_merge(
parent::getEditableConfigNames(),
['social_auth_vk.settings']
);
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('social_auth_vk.settings');
$form['vkontakte_settings'] = [
'#type' => 'details',
'#title' => $this->t('Vkontakte Client settings'),
'#open' => TRUE,
'#description' => $this->t('You need to first create a Vkontakte App at <a href="@vkontakte-dev">@vkontakte-dev</a>', ['@vkontakte-dev' => 'https://vk.com/apps?act=manage']),
];
$form['vkontakte_settings']['client_id'] = [
'#type' => 'textfield',
'#required' => TRUE,
'#title' => $this->t('Application ID'),
'#default_value' => $config->get('client_id'),
'#description' => $this->t('Copy the Client ID here.'),
];
$form['vkontakte_settings']['client_secret'] = [
'#type' => 'textfield',
'#required' => TRUE,
'#title' => $this->t('Secure key'),
'#default_value' => $config->get('client_secret'),
'#description' => $this->t('Copy the Client Secret here.'),
];
$form['vkontakte_settings']['authorized_redirect_url'] = [
'#type' => 'textfield',
'#disabled' => TRUE,
'#title' => $this->t('Authorized redirect URIs'),
'#description' => $this->t('Copy this value to <em>Authorized redirect URIs</em> field of your Vkontakte App settings.'),
'#default_value' => $GLOBALS['base_url'] . '/user/login/vkontakte/callback',
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$this->config('social_auth_vk.settings')
->set('client_id', $values['client_id'])
->set('client_secret', $values['client_secret'])
->save();
parent::submitForm($form, $form_state);
}
}
<?php
namespace Drupal\social_auth_vk\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Token\AccessToken;
use Psr\Http\Message\ResponseInterface;
use VK\Client\VKApiClient;
use VK\OAuth\VKOAuth;
/**
* Custom provider to use official sdk.
*/
class VkSdkDecorator extends AbstractProvider {
public const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'user_id';
/**
* OAuth from SDK.
*
* @var \VK\OAuth\VKOAuth
*/
protected VKOAuth $oauth;
/**
* API client from SDK.
*
* @var \VK\Client\VKApiClient
*/
protected VKApiClient $apiClient;
/**
* {@inheritDoc}
*/
public function __construct(array $options = [], array $collaborators = []) {
parent::__construct($options, $collaborators);
$this->oauth = new VKOAuth();
$this->apiClient = new VKApiClient();
}
/**
* {@inheritDoc}
*/
public function getAuthorizationUrl(array $options = []): string {
if (empty($options['state'])) {
$options['state'] = $this->getRandomState();
$this->state = $options['state'];
}
return $this->oauth->getAuthorizeUrl(
$options['response_type'],
$this->clientId,
$this->redirectUri,
$options['display'],
$options['scope'],
$options['state']
);
}
/**
* {@inheritDoc}
*/
public function getAccessToken($grant, array $options = []): AccessToken {
$response = $this->oauth->getAccessToken($this->clientId, $this->clientSecret, $this->redirectUri, $options['code']);
$response['resource_owner_id'] = $response['user_id'];
return new AccessToken($response);
}
/**
* {@inheritDoc}
*/
protected function fetchResourceOwnerDetails(AccessToken $token) {
$response = $this->apiClient->users()->get($token->getToken(), [
'user_ids' => [$token->getResourceOwnerId()],
'fields' => ['email', 'first_name', 'last_name', 'photo_max_orig'],
]);
return reset($response);
}
/**
* {@inheritDoc}
*/
protected function createResourceOwner(array $response, AccessToken $token) {
$values = $token->getValues();
if (isset($values['email'])) {
$response['email'] = $values['email'];
}
return new VkUser($response);
}
/**
* {@inheritDoc}
*/
public function getBaseAuthorizationUrl() {
throw new \BadMethodCallException('Not implemented/used');
}
/**
* {@inheritDoc}
*/
public function getBaseAccessTokenUrl(array $params) {
throw new \BadMethodCallException('Not implemented/used');
}
/**
* {@inheritDoc}
*/
public function getResourceOwnerDetailsUrl(AccessToken $token) {
throw new \BadMethodCallException('Not implemented/used');
}
/**
* {@inheritDoc}
*/
protected function getDefaultScopes() {
throw new \BadMethodCallException('Not implemented/used');
}
/**
* {@inheritDoc}
*/
protected function checkResponse(ResponseInterface $response, $data) {
throw new \BadMethodCallException('Not implemented/used');
}
}
<?php
namespace Drupal\social_auth_vk\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
use League\OAuth2\Client\Tool\ArrayAccessorTrait;
/**
* Represents a VK use resource.
*/
class VkUser implements ResourceOwnerInterface {
use ArrayAccessorTrait;
/**
* Data from API response.
*
* @var array
*/
protected array $response;
/**
* Constructs object.
*
* @param array $response
* Data from API response.
*/
public function __construct(array $response) {
$this->response = $response;
}
/**
* Gets resource owner attribute by key. The key supports dot notation.
*
* @param string $key
* Field key.
*
* @return mixed
* Value by key from response.
*/
public function getAttribute(string $key): mixed {
return $this->getValueByKey($this->response, (string) $key);
}
/**
* Get user first name.
*
* @return string
* User first name.
*/
public function getFirstName(): string {
return $this->getAttribute('first_name');
}
/**
* Get user last name.
*
* @return string
* User last name.
*/
public function getLastName(): string {
return $this->getAttribute('last_name');
}
/**
* Get user user id.
*
* @return string
* User ID.
*/
public function getId(): string {
return $this->getAttribute('id');
}
/**
* Get user image url.
*
* @return string|null
* Image URL.
*/
public function getImageUrl(): ?string {
return $this->getAttribute('photo_max_orig');
}
/**
* Get user email, if available.
*
* @return string|null
* User email.
*/
public function getEmail(): ?string {
return $this->getAttribute('email');
}
/**
* Return owner details available as an array.
*
* @return array
* Owner details.
*/
public function toArray(): array {
return $this->response;
}
}
<?php
namespace Drupal\social_auth_vk\Plugin\Network;
use Drupal\social_auth\Plugin\Network\NetworkBase;
/**
* Defines a Network Plugin for Social Auth LinkedIn.
*
* @Network(
* id = "social_auth_vk",
* short_name = "vk",
* social_network = "VK",
* img_path = "img/vk_logo.svg",
* type = "social_auth",
* class_name = "\Drupal\social_auth_vk\OAuth2\Client\Provider\VkSdkDecorator",
* auth_manager = "\Drupal\social_auth_vk\VkAuthManager",
* routes = {
* "redirect": "social_auth.network.redirect",
* "callback": "social_auth.network.callback",
* "settings_form": "social_auth.network.settings_form",
* },
* handlers = {
* "settings": {
* "class": "\Drupal\social_auth\Settings\SettingsBase",
* "config_id": "social_auth_vk.settings"
* }
* }
* )
*/
class Vk extends NetworkBase {}
<?php
namespace Drupal\social_auth_vk\Plugin\Network;
use Drupal\social_api\SocialApiException;
use Drupal\social_auth\Plugin\Network\NetworkBase;
use Drupal\social_auth_vk\Settings\VkontakteAuthSettings;
use VK\Client\VKApiClient;
/**
* Defines a Network Plugin for Social Auth Vkontakte.
*
* @package Drupal\simple_vkontakte_connect\Plugin\Network
*
* @Network(
* id = "social_auth_vk",
* social_network = "Vkontakte",
* type = "social_auth",
* handlers = {
* "settings": {
* "class": "\Drupal\social_auth_vk\Settings\VkontakteAuthSettings",
* "config_id": "social_auth_vk.settings"
* }
* }
* )
*/
class VkontakteAuth extends NetworkBase implements VkontakteAuthInterface {
/**
* Sets the underlying SDK library.
*
* @return \VK\Client\VKApiClient
* The initialized 3rd party library instance.
*
* @throws \Drupal\social_api\SocialApiException
* If the SDK library does not exist.
*/
protected function initSdk() {
$class_name = VKApiClient::class;
if (!class_exists($class_name)) {
throw new SocialApiException(sprintf('The Vkontakte Library not found. Class: %s.', $class_name));
}
if ($this->validateConfig($this->settings)) {
return new VKApiClient();
}
return FALSE;
}
/**
* Checks that module is configured.
*
* @param \Drupal\social_auth_vk\Settings\VkontakteAuthSettings $settings
* The Vkontakte auth settings.
*
* @return bool
* True if module is configured.
* False otherwise.
*/
protected function validateConfig(VkontakteAuthSettings $settings) {
$client_id = $settings->getClientId();
$client_secret = $settings->getClientSecret();
$is_valid = $client_id && $client_secret;
if (!$is_valid) {
$this->loggerFactory
->get('social_auth_vk')
->error('Define Client ID and Client Secret on module settings.');
}
return $is_valid;
}
}
<?php
namespace Drupal\social_auth_vk\Plugin\Network;
use Drupal\social_api\Plugin\NetworkInterface;
/**
* Defines the Vkontakte Auth interface.
*/
interface VkontakteAuthInterface extends NetworkInterface {}
<?php
namespace Drupal\social_auth_vk\Settings;
use Drupal\social_api\Settings\SettingsBase;
/**
* Defines methods to get Social Auth Vkontakte settings.
*/
class VkontakteAuthSettings extends SettingsBase implements VkontakteAuthSettingsInterface {
/**
* Client ID.
*
* @var string
*/
protected $clientId;
/**
* Client secret.
*
* @var string
*/
protected $clientSecret;
/**
* {@inheritdoc}
*/
public function getClientId() {
if (!$this->clientId) {
$this->clientId = $this->config->get('client_id');
}
return $this->clientId;
}
/**
* {@inheritdoc}
*/
public function getClientSecret() {
if (!$this->clientSecret) {
$this->clientSecret = $this->config->get('client_secret');
}
return $this->clientSecret;
}
}
<?php
namespace Drupal\social_auth_vk\Settings;
/**
* Defines an interface for Social Auth Vkontakte settings.
*/
interface VkontakteAuthSettingsInterface {
/**
* Gets the client ID.
*
* @return string
* The client ID.
*/
public function getClientId();
/**
* Gets the client secret.
*
* @return string
* The client secret.
*/
public function getClientSecret();
}
<?php
namespace Drupal\social_auth_vk;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\social_auth\AuthManager\OAuth2Manager;
use Drupal\social_auth\User\SocialAuthUser;
use Drupal\social_auth\User\SocialAuthUserInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use VK\OAuth\Scopes\VKOAuthUserScope;
use VK\OAuth\VKOAuthDisplay;
use VK\OAuth\VKOAuthResponseType;
/**
* Contains all the logic for VK OAuth2 authentication.
*/
class VkAuthManager extends OAuth2Manager {
/**
* Auth manager.
*
* @param \Drupal\Core\Config\ConfigFactory $configFactory
* The configuration factory.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $loggerFactory
* The logger factory.
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
* The request stack.
*/
public function __construct(
ConfigFactory $configFactory,
LoggerChannelFactoryInterface $loggerFactory,
RequestStack $requestStack
) {
parent::__construct(
$configFactory->get('social_auth_vk.settings'),
$loggerFactory,
$this->request = $requestStack->getCurrentRequest()
);
}
/**
* {@inheritdoc}
*/
public function getAuthorizationUrl(): string {
$scopes = [VKOAuthUserScope::EMAIL, VKOAuthUserScope::OFFLINE];
$extraScopes = $this->getScopes();
if (!empty($extraScopes)) {
$scopes = array_unique($scopes + explode(',', $extraScopes));
}
// Returns the URL where user will be redirected.
return $this->client->getAuthorizationUrl([
'response_type' => VKOAuthResponseType::CODE,
'display' => VKOAuthDisplay::PAGE,
'scope' => $scopes,
]);
}
/**
* {@inheritdoc}
*/
public function authenticate(): void {
try {
$code = $this->request->query->get('code');
$this->setAccessToken($this->client->getAccessToken(NULL, ['code' => $code]));
}
catch (\Throwable $exception) {
$this->loggerFactory->get('social_auth_vk')
->error('There was an error during authentication. Exception: ' . $exception->getMessage());
}
}
/**
* {@inheritdoc}
*/
public function getUserInfo(): ?SocialAuthUserInterface {
if (!$this->user) {
try {
/** @var \Drupal\social_auth_vk\OAuth2\Client\Provider\VkUser $owner */
$owner = $this->client->getResourceOwner($this->getAccessToken());
$user = new SocialAuthUser(
trim("{$owner->getFirstName()} {$owner->getLastName()}"),
$owner->getId(),
$this->getAccessToken(),
$owner->getEmail(),
$owner->getImageUrl(),
);
$user->setFirstName($owner->getFirstName());
$user->setLastName($owner->getLastName());
$this->user = $user;
}
catch (\Throwable $exception) {
$this->loggerFactory->get('social_auth_vk')
->error('There was an error during retrieving user data. Exception: ' . $exception->getMessage());
return NULL;
}
}
return $this->user;
}
/**
* {@inheritdoc}
*/
public function getState(): string {
return $this->client->getState();
}
/**
* {@inheritDoc}
*/
public function requestEndPoint(string $method, string $path, ?string $domain = NULL, array $options = []): mixed {
throw new \BadMethodCallException('Not implemented/used');
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment