Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • project/social_auth
  • issue/social_auth-3041561
  • issue/social_auth-3099823
  • issue/social_auth-3225324
  • issue/social_auth-3227815
  • issue/social_auth-3251984
  • issue/social_auth-3281410
  • issue/social_auth-3282686
  • issue/social_auth-3292995
  • issue/social_auth-3289760
  • issue/social_auth-3313701
  • issue/social_auth-3314071
  • issue/social_auth-3315161
  • issue/social_auth-3318468
  • issue/social_auth-3059152
  • issue/social_auth-3322271
  • issue/social_auth-3322277
  • issue/social_auth-3355379
  • issue/social_auth-3360455
  • issue/social_auth-2956290
  • issue/social_auth-3400495
  • issue/social_auth-3388639
  • issue/social_auth-3312958
  • issue/social_auth-3427585
  • issue/social_auth-3434675
  • issue/social_auth-3443578
  • issue/social_auth-3436404
  • issue/social_auth-3453885
  • issue/social_auth-3471775
  • issue/social_auth-3472093
  • issue/social_auth-3450688
  • issue/social_auth-3473324
  • issue/social_auth-2947468
  • issue/social_auth-3487647
  • issue/social_auth-3487650
  • issue/social_auth-3496656
36 results
Show changes
Commits on Source (38)
Showing
with 1134 additions and 208 deletions
include:
################
# DrupalCI includes:
# As long as you include this, any future includes added by the Drupal Association will be accessible to your pipelines automatically.
# View these include files at https://git.drupalcode.org/project/gitlab_templates/
################
- project: $_GITLAB_TEMPLATES_REPO
ref: $_GITLAB_TEMPLATES_REF
file:
- '/includes/include.drupalci.main.yml'
- '/includes/include.drupalci.variables.yml'
- '/includes/include.drupalci.workflows.yml'
################
# Pipeline configuration variables
#
# These are the variables provided to the Run Pipeline form that a user may want to override.
#
# Docs at https://git.drupalcode.org/project/gitlab_templates/-/blob/1.0.x/includes/include.drupalci.variables.yml
################
variables:
# Broaden test coverage.
_PHPUNIT_CONCURRENT: 1
# Use PHP 8.1 for Drupal Core 9.5.x
CORE_PREVIOUS_PHP_MIN: 8.1
OPT_IN_TEST_PREVIOUS_MAJOR: 1
OPT_IN_TEST_PREVIOUS_MINOR: 1
OPT_IN_TEST_NEXT_MINOR: 1
OPT_IN_TEST_NEXT_MAJOR: 1
_CSPELL_IGNORE_PATHS: 'css/auth-icons.css, phpcs.xml.dist'
_CSPELL_WORDS: 'auths, socialauth'
CONTENTS OF THIS FILE
---------------------
* Introduction
* Installation
* Configuration
* Support requests
* Maintainers
INTRODUCTION
------------
This project is part of the [Drupal Social Initiative](https://groups.drupal.org/social-initiative).
Social Auth is part of the Social API. It provides a common interface for
creating modules related to user registration/login through social networks'
accounts.
* This module defines a path `/admin/config/social-api/social-auth` which
displays a table of implementers (modules to register/login through social
networks' accounts).
* It also provides a block Social Auth Login which contains links to log in
users through the enabled social networks' module clients
* Alternatively, site builders can place (and theme) a link to
`user/login/{social_network}` wherever on the site. This path is added by the
implementers. For instance Social Auth Facebook will add the path
`user/login/facebook`
RECOMMENDED MODULES
-------------------
* [Social Auth](https://www.drupal.org/project/social_auth):
Implements methods and templates that will be used by login-related modules.
* [Social Post](https://www.drupal.org/project/social_post):
Provides methods to allow auto posting to social network accounts.
* [Social Widgets](https://www.drupal.org/project/social_widgets):
Allows sub-modules to add functionality to add widgets (like buttons, embedded
content) to node, blocks, etc.
INSTALLATION
------------
Install as you would normally install a contributed Drupal module. See
[Installing Modules](https://www.drupal.org/docs/extending-drupal/installing-modules)
for details.
CONFIGURATION
-------------
* A table of implementers will be displayed at Administration » Configuration »
Social API Settings » User authentication. However, it will be empty until an
implementer has been installed and enabled.
* You should install implementer modules to get this module start working.
* You can place a Social Auth Login block at Administration » Structure »
Block layout.
SUPPORT REQUESTS
----------------
Before posting a support request, carefully read the installation
instructions provided in module documentation page.
Before posting a support request, check Recent log entries at
admin/reports/dblog.
Once you have done this, you can post a support request at module issue queue:
[https://www.drupal.org/project/issues/social_auth](https://www.drupal.org/project/issues/social_auth)
When posting a support request, please inform what does the status report say
at admin/reports/dblog and if you were able to see any errors in
Recent log entries.
MAINTAINERS
-----------
Current maintainers:
* [Christopher C. Wells (wells)](https://www.drupal.org/u/wells)
Development sponsored by:
* [Cascade Public Media](https://www.drupal.org/cascade-public-media)
INTRODUCTION
------------
This project is part of the Drupal Social Initiative
(https://groups.drupal.org/social-initiative).
Social Auth is part of the Social API. It provides a common interface for
creating modules related to user registration/login through social networks'
accounts.
* This module defines a path /admin/config/social-api/social-auth which
displays a table of implementers (modules to register/login through social
networks' accounts).
* It also provides a block Social Auth Login which contains links to login
users through the enabled social networks' module clients
* Alternatively, site builders can place (and theme) a link to
user/login/{social_network} wherever on the site. This path are added by the
implementers. For instance Social Auth Facebook will add the path
user/login/facebook
REQUIREMENTS
------------
This module requires the following modules:
* Social API (https://www.drupal.org/project/social_api)
INSTALLATION
------------
* Install as you would normally install a contributed Drupal module. See:
https://www.drupal.org/node/1897420 for further information.
CONFIGURATION
-------------
* A table of implementers will be displayed at Administration » Configuration »
Social API Settings » User authentication. However, it will be empty as we
have not enabled an implementer yet.
* You should install implementer modules to get this module start working.
* You can place a Social Auth Login block at Administration » Structure »
Block layout.
* You can find a more comprehensive guide in the Social Auth documentation
(https://www.drupal.org/node/2763731)
UPDATES IN V2
-------------
* An important aspect is that Social Auth now has its own content entity, so
data can be stored in database.
* Unique IDs are now fetched from providers and are associated with a Drupal
user. This allows a user to have multiple accounts from different providers
associated to the same Drupal account.
MAINTAINERS
-----------
Current maintainers:
* gvso - https://www.drupal.org/u/gvso
* himanshu-dixit - https://www.drupal.org/u/himanshu-dixit
Supporting organizations:
* Google Summer of Code (https://www.drupal.org/google-summer-of-code-0)
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
"homepage": "https://www.drupal.org/project/social_auth", "homepage": "https://www.drupal.org/project/social_auth",
"support": { "support": {
"issues": "https://www.drupal.org/project/issues/social_auth", "issues": "https://www.drupal.org/project/issues/social_auth",
"source": "http://cgit.drupalcode.org/social_auth" "source": "https://git.drupalcode.org/project/social_auth"
}, },
"authors": [ "authors": [
{ {
...@@ -30,14 +30,19 @@ ...@@ -30,14 +30,19 @@
} }
], ],
"require": { "require": {
"drupal/core": "^8.8 || ^9.0", "php": ">=8.1",
"drupal/social_api": "^3" "drupal/core": "^9.5 || ^10 || ^11",
"drupal/social_api": "^4.0"
}, },
"require-dev": { "require-dev": {
"drupal/coder": "^8.3" "drupal/coder": "^8.3",
"phpcompatibility/php-compatibility": "^9.3"
}, },
"minimum-stability": "dev", "minimum-stability": "dev",
"config": { "config": {
"sort-packages": true "sort-packages": true,
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
} }
} }
langcode: en
status: true
dependencies:
module:
- social_auth
id: social_auth_profiles
label: 'Social auth profiles'
module: views
description: ''
tag: ''
base_table: social_auth
base_field: id
display:
default:
id: default
display_title: Default
display_plugin: default
position: 0
display_options:
title: 'Social auth profiles'
fields:
id:
id: id
table: social_auth
field: id
relationship: none
group_type: group
admin_label: ''
entity_type: social_auth
entity_field: id
plugin_id: field
label: ID
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: number_integer
settings:
thousand_separator: ''
prefix_suffix: true
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
plugin_id:
id: plugin_id
table: social_auth
field: plugin_id
relationship: none
group_type: group
admin_label: ''
entity_type: social_auth
entity_field: plugin_id
plugin_id: field
label: 'Plugin ID'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: string
settings: { }
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
provider_user_id:
id: provider_user_id
table: social_auth
field: provider_user_id
relationship: none
group_type: group
admin_label: ''
entity_type: social_auth
entity_field: provider_user_id
plugin_id: field
label: 'Provider user ID'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: string
settings: { }
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
operations:
id: operations
table: social_auth
field: operations
relationship: none
group_type: group
admin_label: ''
entity_type: null
entity_field: null
plugin_id: entity_operations
label: Operations
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
destination: false
pager:
type: mini
options:
offset: 0
items_per_page: 10
total_pages: null
id: 0
tags:
next: ››
previous: ‹‹
expose:
items_per_page: false
items_per_page_label: 'Items per page'
items_per_page_options: '5, 10, 25, 50'
items_per_page_options_all: false
items_per_page_options_all_label: '- All -'
offset: false
offset_label: Offset
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
access:
type: none
options: { }
cache:
type: tag
options: { }
empty:
area_text_custom:
id: area_text_custom
table: views
field: area_text_custom
relationship: none
group_type: group
admin_label: ''
plugin_id: text_custom
empty: true
content: 'There are no configured third-party authentication profiles yet.'
tokenize: false
sorts: { }
arguments:
user_id:
id: user_id
table: social_auth
field: user_id
relationship: none
group_type: group
admin_label: ''
entity_type: social_auth
entity_field: user_id
plugin_id: numeric
default_action: 'not found'
exception:
value: all
title_enable: false
title: All
title_enable: false
title: ''
default_argument_type: user
default_argument_options:
user: false
summary_options:
base_path: ''
count: true
override: false
items_per_page: 25
summary:
sort_order: asc
number_of_records: 0
format: default_summary
specify_validation: true
validate:
type: 'entity:user'
fail: 'not found'
validate_options:
access: true
operation: update
multiple: 0
restrict_roles: false
roles: { }
break_phrase: false
not: false
filters: { }
style:
type: table
options:
grouping: { }
row_class: ''
default_row_class: true
columns:
operations: operations
id: id
delete_social_auth: delete_social_auth
plugin_id: plugin_id
provider_user_id: provider_user_id
default: '-1'
info:
operations:
align: ''
separator: ''
empty_column: false
responsive: ''
id:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
delete_social_auth:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
plugin_id:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
provider_user_id:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
override: true
sticky: false
summary: ''
empty_table: false
caption: ''
description: ''
row:
type: fields
query:
type: views_query
options:
query_comment: ''
disable_sql_rewrite: false
distinct: false
replica: false
query_tags: { }
relationships: { }
header: { }
footer: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url
- url.query_args
tags: { }
<ruleset name="drupal/social_auth"> <ruleset name="drupal/social_auth">
<description>Social Auth module CodeSniffer configuration.</description> <description>Social Auth module CodeSniffer configuration.</description>
<arg name="extensions" value="php,module,inc,install,test,profile,theme,css,info,txt,md,yml"/> <arg name="extensions" value="php,module,inc,install,test,profile,theme,css,info,txt,md,yml"/>
<arg name="basepath" value="."/>
<arg name="colors"/>
<arg name="parallel" value="75"/>
<arg value="p"/>
<config name="drupal_core_version" value="9"/> <config name="drupal_core_version" value="9"/>
<config name="testVersion" value="8.0-" />
<file>.</file> <file>.</file>
<exclude-pattern>vendor</exclude-pattern> <exclude-pattern>vendor</exclude-pattern>
<!-- phpstan already taking for this rule. -->
<rule ref="DrupalPractice">
<exclude name="DrupalPractice.Objects.GlobalDrupal.GlobalDrupal"/>
</rule>
<rule ref="./vendor/drupal/coder/coder_sniffer/Drupal"/> <rule ref="./vendor/drupal/coder/coder_sniffer/Drupal"/>
<rule ref="./vendor/drupal/coder/coder_sniffer/DrupalPractice"/> <rule ref="./vendor/drupal/coder/coder_sniffer/DrupalPractice"/>
<rule ref="./vendor/phpcompatibility/php-compatibility/PHPCompatibility"/>
</ruleset> </ruleset>
name: Social Auth name: Social Auth
type: module type: module
description: Allows user authentication with different services. description: Allows user authentication with different services.
core_version_requirement: ^8.8 || ^9 core_version_requirement: ^9.5 || ^10 || ^11
package: Social package: Social
configure: social_auth.integrations configure: social_auth.integrations
dependencies: dependencies:
......
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
*/ */
use Drupal\Core\Database\Database; use Drupal\Core\Database\Database;
use Drupal\views\Entity\View;
use Symfony\Component\Yaml\Yaml;
/** /**
* Add 'social_auth' table when the module is updated from 1.x to 2.x. * Add 'social_auth' table when the module is updated from 1.x to 2.x.
...@@ -118,3 +120,22 @@ function social_auth_update_8202() { ...@@ -118,3 +120,22 @@ function social_auth_update_8202() {
} }
} }
/**
* Import view to list social auths.
*/
function social_auth_update_8203() {
$message = NULL;
// Only create if the social auth profiles view doesn't exists
// and views is enabled.
if (\Drupal::moduleHandler()->moduleExists('views') && !View::load('social_auth_profiles')) {
$config_path = \Drupal::service('extension.list.module')->getPath('social_auth') . '/config/optional/views.view.social_auth_profiles.yml';
$data = Yaml::parseFile($config_path);
\Drupal::configFactory()->getEditable('views.view.social_auth_profiles')->setData($data)->save(TRUE);
$message = 'The new social auth profiles view has been created.';
}
else {
$message = 'Not creating a social auth profiles view since it already exists.';
}
return $message;
}
...@@ -4,3 +4,9 @@ social_auth.integrations: ...@@ -4,3 +4,9 @@ social_auth.integrations:
route_name: social_auth.integrations route_name: social_auth.integrations
parent: social_api.admin_config parent: social_api.admin_config
weight: -10 weight: -10
social_auth.profiles:
title: Social Auth Profiles
description: Manage Social Auth Profiles
parent: entity.user.collection
route_name: entity.social_auth.collection
...@@ -2,3 +2,14 @@ social_auth.integrations.tab: ...@@ -2,3 +2,14 @@ social_auth.integrations.tab:
title: 'Integrations' title: 'Integrations'
route_name: social_auth.integrations route_name: social_auth.integrations
base_route: social_auth.integrations base_route: social_auth.integrations
entity.social_auth.collection:
title: 'Social auth profiles'
route_name: entity.social_auth.collection
base_route: entity.user.collection
social_auth.user.social_auth_profiles_task:
title: 'Social auth profiles'
route_name: social_auth.user.profiles
base_route: entity.user.canonical
weight: 5
...@@ -5,7 +5,12 @@ ...@@ -5,7 +5,12 @@
* Allows login using different social networking services. * Allows login using different social networking services.
*/ */
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\Error;
/** /**
* Implements hook_theme(). * Implements hook_theme().
...@@ -13,7 +18,7 @@ ...@@ -13,7 +18,7 @@
function social_auth_theme() { function social_auth_theme() {
return [ return [
'login_with' => [ 'login_with' => [
'variables' => ['social_networks' => NULL, 'destination' => NULL], 'variables' => ['networks' => NULL, 'destination' => NULL],
], ],
]; ];
} }
...@@ -56,3 +61,202 @@ function social_auth_user_delete(EntityInterface $account) { ...@@ -56,3 +61,202 @@ function social_auth_user_delete(EntityInterface $account) {
]); ]);
} }
} }
/**
* Implements hook_entity_extra_field_info().
*/
function social_auth_entity_extra_field_info() {
$fields['user']['user']['form']['social_auth'] = [
'label' => t('Social authentications'),
'description' => t('Social Auth form element.'),
'weight' => 5,
];
return $fields;
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function social_auth_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// If the for is the user edit form, not user register form or others.
// @see https://www.drupal.org/node/2854977
if ($form_id == 'user_form') {
$current_user = Drupal::currentUser();
if (_social_auth_can_grant_permission($current_user)) {
// Add a button to authorize twitter auto posting.
try {
$form += _social_auth_user_edit_form($current_user);
}
catch (Exception $e) {
Error::logException(\Drupal::logger('social_auth'), $e);
}
}
}
}
/**
* Check if the user is allowed to view own social auths.
*
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*
* @return bool
* The user can see this user social auths.
*/
function _social_auth_can_grant_permission(AccountInterface $current_user): bool {
$routeMatch = Drupal::service('current_route_match');
// If the current user id is the same as the user id of parameter.
if ($current_user->id() == $routeMatch->getParameter('user')->id()) {
return TRUE;
}
return FALSE;
}
/**
* Creates elements to the user edit form.
*
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*
* @return array
* The elements to add to the user edit form.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
function _social_auth_user_edit_form(AccountInterface $current_user): array {
/** @var \Drupal\social_post\Entity\SocialPost[] $accounts */
$accounts = _social_auth_get_accounts_by_uid($current_user->id());
$networks = _social_auth_get_networks();
$form['social_auth'] = [
'#type' => 'details',
'#title' => t('Social Authentications'),
'#open' => TRUE,
];
$form['social_auth']['accounts'] = [
'#type' => 'table',
'#header' => [
t('Status'),
t('Network'),
t('Provider User ID'),
t('Operations'),
],
'#empty' => t('You have not added any accounts yet.'),
];
foreach ($networks as $network_plugin_id => $network) {
$form['social_auth']['accounts'][$network_plugin_id]['status'] = [
'#markup' => '',
];
$form['social_auth']['accounts'][$network_plugin_id]['network'] = [
'#markup' => $network['network']->getShortName(),
];
$form['social_auth']['accounts'][$network_plugin_id]['screen_name'] = [
'#markup' => '-',
];
$form['social_auth']['accounts'][$network_plugin_id]['operations'] = [
'#type' => 'operations',
'#links' => [
'authenticate' => [
'title' => t('Authenticate'),
'url' => Url::fromUserInput($network['network']->getRedirectUrl([
'query' => [
'destination' => Url::fromRoute('<current>', [], [])->toString(),
],
])->toString()),
],
],
];
foreach ($accounts as $account) {
$plugin_id = $account->hasField("plugin_id") && !$account->get("plugin_id")->isEmpty() ? $account->get("plugin_id")->first()->getValue()['value'] : t('Broken/Missing');
if ($network_plugin_id === $plugin_id) {
$provider_user_id = $account->hasField("provider_user_id") && !$account->get("provider_user_id")->isEmpty() ? $account->get("provider_user_id")->first()->getValue()['value'] : t('Broken/Missing');
$form['social_auth']['accounts'][$network_plugin_id]['status'] = [
'#type' => 'html_tag',
'#tag' => 'span',
'#value' => $networks[$plugin_id]['access_token_expired'] ? '⚠️⌛' : '✔️',
'#attributes' => [
'title' => $networks[$plugin_id]['access_token_expired'] ? t('Access token expired') : t('Connected'),
],
];
$form['social_auth']['accounts'][$network_plugin_id]['screen_name'] = [
'#markup' => $provider_user_id,
];
$form['social_auth']['accounts'][$network_plugin_id]['operations']['#links']['delete'] = [
'title' => t('Delete'),
'url' => Url::fromRoute('entity.social_auth.delete_form',
[
'social_auth' => $account->id(),
]
),
];
}
}
}
return $form;
}
/**
* Gets the accounts associated to the Drupal user.
*
* @param int $user_id
* The user id.
*
* @return \Drupal\Core\Entity\EntityInterface[]
* Accounts associated to the user id.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
function _social_auth_get_accounts_by_uid(int $user_id): array {
$entity_query = Drupal::entityTypeManager()->getStorage('social_auth')->getAggregateQuery();
$result = $entity_query
->condition('user_id', $user_id)
->aggregate('id', 'MAX')
->groupBy('plugin_id')
->accessCheck(TRUE)
->execute();
$accounts = [];
foreach ($result as $distinct_entities) {
$accounts[] = $distinct_entities['id_max'];
}
return $result ? Drupal::entityTypeManager()->getStorage('social_auth')->loadMultiple($accounts) : [];
}
/**
* Gets the networks defined.
*
* @return array
* Array of network plugins.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
function _social_auth_get_networks(): array {
/** @var \Drupal\social_api\Plugin\NetworkManager $network_manager */
$network_manager = \Drupal::service('plugin.network.manager');
/** @var \Drupal\social_auth\SocialAuthDataHandler $data_handler */
$data_handler = \Drupal::service('social_auth.data_handler');
$networks = [];
foreach ($network_manager->getDefinitions() as $definition) {
$networks[$definition['id']]['network'] = $network_manager->createInstance($definition['id']);
$data_handler->setSessionPrefix($definition['id']);
if ($access_token = $data_handler->get('access_token')) {
$networks[$definition['id']]['access_token_expired'] = $access_token->getExpires() < (new DrupalDateTime())->getTimestamp();
$networks[$definition['id']]['access_token'] = $access_token;
}
else {
$networks[$definition['id']]['access_token_expired'] = TRUE;
}
}
return $networks;
}
delete own social auth profile:
title: 'Delete own social auth profile'
description: 'Allow the deletion of social authentication profiles for their account.'
administer social auth profiles:
title: 'Administer social auth profiles'
description: 'Administer social auth profiles.'
...@@ -12,11 +12,11 @@ function social_auth_post_update_encrypt_tokens(&$sandbox = NULL) { ...@@ -12,11 +12,11 @@ function social_auth_post_update_encrypt_tokens(&$sandbox = NULL) {
$storage = \Drupal::entityTypeManager()->getStorage('social_auth'); $storage = \Drupal::entityTypeManager()->getStorage('social_auth');
// Initializes some variables during the first pass through. // Initializes some variables during the first pass through.
if (!isset($sandbox['total'])) { if (!isset($sandbox['total'])) {
$sandbox['total'] = $storage->getQuery()->count()->execute(); $sandbox['total'] = $storage->getQuery()->accessCheck(FALSE)->count()->execute();
$sandbox['progress'] = 0; $sandbox['progress'] = 0;
} }
$ids = $storage->getQuery()->range($sandbox['progress'], 50)->execute(); $ids = $storage->getQuery()->checkAccess(FALSE)->range($sandbox['progress'], 50)->execute();
/** @var \Drupal\social_auth\Entity\SocialAuth[] $social_auth_users */ /** @var \Drupal\social_auth\Entity\SocialAuth[] $social_auth_users */
$social_auth_users = $storage->loadMultiple($ids); $social_auth_users = $storage->loadMultiple($ids);
foreach ($social_auth_users as $user) { foreach ($social_auth_users as $user) {
......
social_auth.integrations: social_auth.integrations:
path: '/admin/config/social-api/social-auth' path: '/admin/config/social-api/social-auth'
defaults: defaults:
_controller: '\Drupal\social_auth\Controller\SocialAuthController::integrations' _controller: '\Drupal\social_api\Controller\SocialApiController::integrations'
_title: 'User authentication' _title: 'User authentication'
type: 'social_auth' type: 'social_auth'
requirements: requirements:
_permission: 'administer social api authentication' _permission: 'administer social api authentication'
social_auth.network.redirect:
path: 'user/login/{network}'
defaults:
_controller: '\Drupal\social_auth\Controller\OAuth2ControllerBase::redirectToProvider'
requirements:
# Anonymous users can log in, but authenticated users can also associate a new provider.
_access: 'TRUE'
options:
no_cache: TRUE
parameters:
network:
type: network
social_auth.network.callback:
path: 'user/login/{network}/callback'
defaults:
_controller: '\Drupal\social_auth\Controller\OAuth2ControllerBase::callback'
requirements:
# Anonymous users can log in, but authenticated users can also associate a new provider.
_access: 'TRUE'
options:
no_cache: TRUE
parameters:
network:
type: network
social_auth.network.settings_form:
path: 'admin/config/social-api/social-auth/{network}'
defaults:
_form: '\Drupal\social_auth\Form\SocialAuthSettingsForm'
_title_callback: '\Drupal\social_auth\Form\SocialAuthSettingsForm::getTitle'
requirements:
_permission: 'administer social api authentication'
options:
parameters:
network:
type: network
social_auth.user.profiles:
path: '/user/{user}/social-auth/profiles'
defaults:
_controller: '\Drupal\social_auth\Controller\UserController::socialAuthProfiles'
_title: 'Social authentication profiles'
requirements:
_entity_access: 'user.update'
user: \d+
...@@ -24,8 +24,16 @@ services: ...@@ -24,8 +24,16 @@ services:
- '@event_dispatcher' - '@event_dispatcher'
- '@token' - '@token'
- '@file_system' - '@file_system'
- '@password_generator'
social_auth.data_handler: social_auth.data_handler:
class: Drupal\social_auth\SocialAuthDataHandler class: Drupal\social_auth\SocialAuthDataHandler
arguments: arguments:
- '@session' - '@session'
paramconverter.network:
class: Drupal\social_auth\ParamConverter\NetworkConverter
arguments:
- '@plugin.network.manager'
tags:
- { name: paramconverter }
...@@ -16,26 +16,26 @@ abstract class OAuth2Manager extends BaseOAuth2Manager implements OAuth2ManagerI ...@@ -16,26 +16,26 @@ abstract class OAuth2Manager extends BaseOAuth2Manager implements OAuth2ManagerI
* *
* @var string|null * @var string|null
*/ */
protected $scopes; protected ?string $scopes = NULL;
/** /**
* The end points to be requested. * The end points to be requested.
* *
* @var string|null * @var string|null
*/ */
protected $endPoints; protected ?string $endPoints = NULL;
/** /**
* The user returned by the provider. * The user returned by the provider.
* *
* @var \League\OAuth2\Client\Provider\GenericResourceOwner|array|mixed * @var mixed
*/ */
protected $user; protected mixed $user = NULL;
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getExtraDetails($method = 'GET', $domain = NULL) { public function getExtraDetails(string $method = 'GET', ?string $domain = NULL): ?array {
$endpoints = $this->getEndPoints(); $endpoints = $this->getEndPoints();
// Stores the data mapped with endpoints define in settings. // Stores the data mapped with endpoints define in settings.
...@@ -59,7 +59,7 @@ public function getExtraDetails($method = 'GET', $domain = NULL) { ...@@ -59,7 +59,7 @@ public function getExtraDetails($method = 'GET', $domain = NULL) {
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getScopes() { public function getScopes(): string {
if ($this->scopes === NULL) { if ($this->scopes === NULL) {
$this->scopes = $this->settings->get('scopes'); $this->scopes = $this->settings->get('scopes');
} }
...@@ -70,7 +70,7 @@ public function getScopes() { ...@@ -70,7 +70,7 @@ public function getScopes() {
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getEndPoints() { public function getEndPoints(): string {
if ($this->endPoints === NULL) { if ($this->endPoints === NULL) {
$this->endPoints = $this->settings->get('endpoints'); $this->endPoints = $this->settings->get('endpoints');
} }
......
...@@ -22,7 +22,7 @@ interface OAuth2ManagerInterface extends BaseOAuth2ManagerInterface { ...@@ -22,7 +22,7 @@ interface OAuth2ManagerInterface extends BaseOAuth2ManagerInterface {
* @return array|null * @return array|null
* The extra details gotten from provider. * The extra details gotten from provider.
*/ */
public function getExtraDetails($method = 'GET', $domain = NULL); public function getExtraDetails(string $method = 'GET', ?string $domain = NULL): ?array;
/** /**
* Request and end point. * Request and end point.
...@@ -39,7 +39,7 @@ public function getExtraDetails($method = 'GET', $domain = NULL); ...@@ -39,7 +39,7 @@ public function getExtraDetails($method = 'GET', $domain = NULL);
* @return array|mixed * @return array|mixed
* Data returned by provider. * Data returned by provider.
*/ */
public function requestEndPoint($method, $path, $domain = NULL, array $options = []); public function requestEndPoint(string $method, string $path, ?string $domain = NULL, array $options = []): mixed;
/** /**
* Gets the scopes defined in the settings form. * Gets the scopes defined in the settings form.
...@@ -47,7 +47,7 @@ public function requestEndPoint($method, $path, $domain = NULL, array $options = ...@@ -47,7 +47,7 @@ public function requestEndPoint($method, $path, $domain = NULL, array $options =
* @return string * @return string
* Data points separated by comma. * Data points separated by comma.
*/ */
public function getScopes(); public function getScopes(): string;
/** /**
* Gets the API endpoints to be requested. * Gets the API endpoints to be requested.
...@@ -55,6 +55,6 @@ public function getScopes(); ...@@ -55,6 +55,6 @@ public function getScopes();
* @return string * @return string
* API endpoints separated in different lines. * API endpoints separated in different lines.
*/ */
public function getEndPoints(); public function getEndPoints(): string;
} }
...@@ -3,16 +3,26 @@ ...@@ -3,16 +3,26 @@
namespace Drupal\social_auth\Controller; namespace Drupal\social_auth\Controller;
use Drupal\Component\Plugin\Exception\PluginException; use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase; use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface; use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Render\RenderContext; use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface; use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\TrustedRedirectResponse; use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\social_api\Plugin\NetworkManager; use Drupal\social_api\Plugin\NetworkManager;
use Drupal\social_auth\AuthManager\OAuth2ManagerInterface; use Drupal\social_auth\AuthManager\OAuth2ManagerInterface;
use Drupal\social_auth\Event\LoginEvent;
use Drupal\social_auth\Event\SocialAuthEvents;
use Drupal\social_auth\Plugin\Network\NetworkInterface;
use Drupal\social_auth\SocialAuthDataHandler; use Drupal\social_auth\SocialAuthDataHandler;
use Drupal\social_auth\User\SocialAuthUserInterface;
use Drupal\social_auth\User\UserAuthenticator; use Drupal\social_auth\User\UserAuthenticator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
/** /**
* Handle responses for Social Auth implementer controllers. * Handle responses for Social Auth implementer controllers.
...@@ -31,122 +41,188 @@ class OAuth2ControllerBase extends ControllerBase { ...@@ -31,122 +41,188 @@ class OAuth2ControllerBase extends ControllerBase {
* *
* @var \Drupal\social_api\Plugin\NetworkManager * @var \Drupal\social_api\Plugin\NetworkManager
*/ */
protected $networkManager; protected NetworkManager $networkManager;
/** /**
* The Social Auth user authenticator.. * The Social Auth user authenticator..
* *
* @var \Drupal\social_auth\User\UserAuthenticator * @var \Drupal\social_auth\User\UserAuthenticator
*/ */
protected $userAuthenticator; protected UserAuthenticator $userAuthenticator;
/** /**
* The provider authentication manager. * The provider authentication manager.
* *
* @var \Drupal\social_auth\AuthManager\OAuth2ManagerInterface * @var \Drupal\social_auth\AuthManager\OAuth2ManagerInterface|null
*/ */
protected $providerManager; protected ?OAuth2ManagerInterface $providerManager = NULL;
/** /**
* Used to access GET parameters. * Used to access GET parameters.
* *
* @var \Symfony\Component\HttpFoundation\RequestStack * @var \Symfony\Component\HttpFoundation\RequestStack
*/ */
protected $request; protected RequestStack $request;
/** /**
* The Social Auth data handler. * The Social Auth data handler.
* *
* @var \Drupal\social_auth\SocialAuthDataHandler * @var \Drupal\social_auth\SocialAuthDataHandler
*/ */
protected $dataHandler; protected SocialAuthDataHandler $dataHandler;
/** /**
* The renderer service. * The renderer service.
* *
* @var \Drupal\Core\Render\Renderer * @var \Drupal\Core\Render\RendererInterface
*/ */
protected $renderer; protected RendererInterface $renderer;
/**
* Event dispatcher.
*
* @var \Symfony\Contracts\EventDispatcher\EventDispatcherInterface
*/
protected EventDispatcherInterface $dispatcher;
/** /**
* The implement plugin id. * The implement plugin id.
* *
* @var string * @var string|null
*/ */
protected $pluginId; protected ?string $pluginId = NULL;
/** /**
* The module name. * The module name.
* *
* @var string * @var string|null
*/ */
protected $module; protected ?string $module = NULL;
/** /**
* SocialAuthControllerBase constructor. * Error code produced in the processCallback method.
* *
* @param string $module * @var string|null
* The module name. */
* @param string $plugin_id private ?string $processCallbackError = NULL;
* The plugin id.
/**
* OAuth2ControllerBase constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* Config factory.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger
* Logger channel.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger * @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger service. * Messenger.
* @param \Drupal\social_api\Plugin\NetworkManager $network_manager * @param \Drupal\social_api\Plugin\NetworkManager $network_manager
* Used to get an instance of the network plugin. * Network manager.
* @param \Drupal\social_auth\User\UserAuthenticator $user_authenticator * @param \Drupal\social_auth\User\UserAuthenticator $user_authenticator
* Used to manage user authentication/registration. * User authenticator.
* @param \Drupal\social_auth\AuthManager\OAuth2ManagerInterface $provider_manager
* Used to manage authentication methods.
* @param \Symfony\Component\HttpFoundation\RequestStack $request * @param \Symfony\Component\HttpFoundation\RequestStack $request
* Used to access GET parameters. * Request stack.
* @param \Drupal\social_auth\SocialAuthDataHandler $data_handler * @param \Drupal\social_auth\SocialAuthDataHandler $data_handler
* The Social Auth data handler. * Social Auth data handler.
* @param \Drupal\Core\Render\RendererInterface $renderer * @param \Drupal\Core\Render\RendererInterface $renderer
* Used to handle metadata for redirection to authentication URL. * Renderer.
* @param \Symfony\Contracts\EventDispatcher\EventDispatcherInterface $dispatcher
* Event dispatcher.
*/ */
public function __construct($module, public function __construct(
$plugin_id, ConfigFactoryInterface $config_factory,
MessengerInterface $messenger, LoggerChannelFactoryInterface $logger,
NetworkManager $network_manager, MessengerInterface $messenger,
UserAuthenticator $user_authenticator, NetworkManager $network_manager,
OAuth2ManagerInterface $provider_manager, UserAuthenticator $user_authenticator,
RequestStack $request, RequestStack $request,
SocialAuthDataHandler $data_handler, SocialAuthDataHandler $data_handler,
RendererInterface $renderer = NULL) { RendererInterface $renderer,
EventDispatcherInterface $dispatcher,
$this->module = $module; ) {
$this->pluginId = $plugin_id; $this->configFactory = $config_factory;
$this->loggerFactory = $logger;
$this->messenger = $messenger; $this->messenger = $messenger;
$this->networkManager = $network_manager; $this->networkManager = $network_manager;
$this->userAuthenticator = $user_authenticator; $this->userAuthenticator = $user_authenticator;
$this->providerManager = $provider_manager;
$this->request = $request; $this->request = $request;
$this->dataHandler = $data_handler; $this->dataHandler = $data_handler;
$this->renderer = $renderer; $this->renderer = $renderer;
$this->dispatcher = $dispatcher;
}
/* /**
* TODO: Added for backward compatibility. * {@inheritdoc}
* */
* Remove after implementers have been updated. public static function create(ContainerInterface $container): static {
* @see https://www.drupal.org/project/social_auth/issues/3033444 return new static(
*/ $container->get('config.factory'),
if (!$this->renderer) { $container->get('logger.factory'),
$this->renderer = \Drupal::service('renderer'); $container->get('messenger'),
} $container->get('plugin.network.manager'),
$container->get('social_auth.user_authenticator'),
$container->get('request_stack'),
$container->get('social_auth.data_handler'),
$container->get('renderer'),
$container->get('event_dispatcher')
);
}
/**
* Sets up the class for the provided network.
*
* @param \Drupal\social_auth\Plugin\Network\NetworkInterface $network
* Network.
*/
private function setUp(NetworkInterface $network): void {
$this->pluginId = $network->getPluginId();
$this->module = $network->getPluginDefinition()['social_network'];
$auth_manager_class = $network->getPluginDefinition()['auth_manager'];
$this->providerManager = new $auth_manager_class(
$this->configFactory,
$this->loggerFactory,
$this->request
);
// Sets the plugin id in user authenticator. // Sets the plugin id in user authenticator.
$this->userAuthenticator->setPluginId($plugin_id); $this->userAuthenticator->setPluginId($network->getPluginId());
// Sets the session prefix. // Sets the session prefix.
$this->dataHandler->setSessionPrefix($plugin_id); $this->dataHandler->setSessionPrefix($network->getPluginId());
// Sets the session keys to nullify if user could not logged in. // Sets the session keys to nullify if user could not be logged in.
$this->userAuthenticator->setSessionKeysToNullify([ $this->userAuthenticator->setSessionKeysToNullify([
'access_token', 'access_token',
'oauth2state', 'oauth2state',
]); ]);
} }
/**
* Callback response router handler for networks.
*/
public function callback(NetworkInterface $network): RedirectResponse {
$this->setUp($network);
$social_auth_user = $this->processCallback();
if ($social_auth_user !== NULL) {
$redirect = $this->userAuthenticator->authenticateUser($social_auth_user);
// Only trigger the event if Drupal fully authenticated the user.
if ($this->currentUser()->isAuthenticated()) {
$event = new LoginEvent($this->currentUser(), $social_auth_user, $this->pluginId);
$this->dispatcher->dispatch($event, SocialAuthEvents::USER_LOGIN);
}
return $redirect;
}
else {
$callbackError = $this->getProcessCallbackError();
if (!is_null($callbackError)) {
$this->messenger->addError($callbackError);
// Redirecting to user.login would cause infinite loop.
return $this->redirect('<front>');
}
}
return $this->redirect('user.login');
}
/** /**
* Response for implementer authentication url. * Response for implementer authentication url.
* *
...@@ -157,7 +233,8 @@ public function __construct($module, ...@@ -157,7 +233,8 @@ public function __construct($module,
* *
* @see https://www.drupal.org/project/social_auth/issues/3033444 * @see https://www.drupal.org/project/social_auth/issues/3033444
*/ */
public function redirectToProvider() { public function redirectToProvider(NetworkInterface $network): Response {
$this->setUp($network);
$context = new RenderContext(); $context = new RenderContext();
/** @var \Drupal\Core\Routing\TrustedRedirectResponse|\Symfony\Component\HttpFoundation\RedirectResponse $response */ /** @var \Drupal\Core\Routing\TrustedRedirectResponse|\Symfony\Component\HttpFoundation\RedirectResponse $response */
...@@ -200,9 +277,8 @@ public function redirectToProvider() { ...@@ -200,9 +277,8 @@ public function redirectToProvider() {
$this->userAuthenticator->dispatchBeforeRedirect($destination); $this->userAuthenticator->dispatchBeforeRedirect($destination);
return new TrustedRedirectResponse($auth_url); return new TrustedRedirectResponse($auth_url);
} }
catch (PluginException $exception) { catch (PluginException) {
$this->messenger->addError($this->t('There has been an error when creating plugin.')); $this->messenger->addError($this->t('There has been an error when creating plugin.'));
return $this->redirect('user.login'); return $this->redirect('user.login');
} }
}); });
...@@ -216,54 +292,91 @@ public function redirectToProvider() { ...@@ -216,54 +292,91 @@ public function redirectToProvider() {
return $response; return $response;
} }
/**
* Gets the error details for the processCallbackError property.
*
* @return string|null
* Error detail or null otherwise.
*/
private function getProcessCallbackError(): ?string {
$errors = [
'config' => $this->t('%module not configured properly. Contact site administrator.', ['%module' => $this->module]),
'oauth' => $this->t('Login failed. Invalid OAuth2 state.'),
'token' => $this->t('Authentication failed. Contact site administrator.'),
'user_info' => $this->t('Login failed, could not load user profile. Contact site administrator.'),
'exception' => $this->t('There has been an error when creating plugin.'),
'unknown' => $this->t('Unknown error.'),
];
return is_null($this->processCallbackError) ?
NULL :
($errors[$this->processCallbackError] ?? $errors['unknown']);
}
/**
* Sets the error code for the processCallbackError property.
*
* @param string $errorCode
* Error code to set.
*/
private function setProcessCallbackError(string $errorCode) {
$this->processCallbackError = $errorCode;
}
/**
* Resets the error code for the processCallbackError property.
*/
private function resetProcessCallbackError() {
$this->processCallbackError = NULL;
}
/** /**
* Process implementer callback path. * Process implementer callback path.
* *
* @return \League\OAuth2\Client\Provider\GenericResourceOwner|null * @return \Drupal\social_auth\User\SocialAuthUserInterface|null
* The user info if successful. * The user info if successful. Null otherwise.
* Null otherwise.
*/ */
public function processCallback() { private function processCallback(): ?SocialAuthUserInterface {
// Clean up any possible previous value first.
$this->resetProcessCallbackError();
try { try {
/** @var \League\OAuth2\Client\Provider\AbstractProvider|false $client */
$client = $this->networkManager->createInstance($this->pluginId)->getSdk(); $client = $this->networkManager->createInstance($this->pluginId)->getSdk();
// If provider client could not be obtained. // If provider client could not be obtained.
if (!$client) { if (!$client) {
$this->messenger->addError($this->t('%module not configured properly. Contact site administrator.', ['%module' => $this->module])); $this->setProcessCallbackError('config');
return NULL; return NULL;
} }
$state = $this->dataHandler->get('oauth2state'); $state = $this->dataHandler->get('oauth2state');
// Retrieves $_GET['state'].
$retrievedState = $this->request->getCurrentRequest()->query->get('state'); $retrievedState = $this->request->getCurrentRequest()->query->get('state');
if (empty($retrievedState) || ($retrievedState !== $state)) { if (empty($retrievedState) || ($retrievedState !== $state)) {
$this->userAuthenticator->nullifySessionKeys(); $this->userAuthenticator->nullifySessionKeys();
$this->messenger->addError($this->t('Login failed. Invalid OAuth2 state.')); $this->setProcessCallbackError('oauth');
return NULL; return NULL;
} }
$this->providerManager->setClient($client)->authenticate(); $this->providerManager->setClient($client)->authenticate();
$access_token = $this->providerManager->getAccessToken();
if (empty($access_token)) {
$this->setProcessCallbackError('token');
return NULL;
}
// Saves access token to session. // Saves access token to session.
$this->dataHandler->set('access_token', $this->providerManager->getAccessToken()); $this->dataHandler->set('access_token', $access_token);
// Gets user's info from provider. // Gets user's info from provider.
if (!$profile = $this->providerManager->getUserInfo()) { if (!$profile = $this->providerManager->getUserInfo()) {
$this->messenger->addError($this->t('Login failed, could not load user profile. Contact site administrator.')); $this->setProcessCallbackError('user_info');
return NULL; return NULL;
} }
return $profile; return $profile;
} }
catch (PluginException $exception) { catch (PluginException) {
$this->messenger->addError($this->t('There has been an error when creating plugin.')); $this->setProcessCallbackError('exception');
return NULL; return NULL;
} }
} }
...@@ -282,7 +395,7 @@ public function processCallback() { ...@@ -282,7 +395,7 @@ public function processCallback() {
* @return \Symfony\Component\HttpFoundation\RedirectResponse|null * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
* Redirect response object that may be returned by the controller or null. * Redirect response object that may be returned by the controller or null.
*/ */
protected function checkAuthError($key = 'error') { protected function checkAuthError(string $key = 'error'): ?RedirectResponse {
$request_query = $this->request->getCurrentRequest()->query; $request_query = $this->request->getCurrentRequest()->query;
// Checks if authentication failed. // Checks if authentication failed.
......
<?php
namespace Drupal\social_auth\Controller;
use Drupal\social_api\Controller\SocialApiController;
/**
* Manages login buttons settings and integration table renderization.
*/
class SocialAuthController extends SocialApiController {
/**
* Sets the settings for the login button for the given social networking.
*
* @param string $module
* The module machine name.
* @param string $route
* The route name of the user authentication controller.
* @param string $img_path
* The path of the image for login.
*/
public static function setLoginButtonSettings($module, $route, $img_path) {
$config = \Drupal::configFactory()->getEditable('social_auth.settings');
$img_path = drupal_get_path('module', $module) . '/' . $img_path;
$config->set('auth.' . $module . '.route', $route)
->set('auth.' . $module . '.img_path', $img_path)
->save();
}
/**
* Delete the settings for the login button for the given social networking.
*
* @param string $module
* The module machine name.
*/
public static function deleteLoginButtonSettings($module) {
$config = \Drupal::configFactory()->getEditable('social_auth.settings');
$config->clear('auth.' . $module)
->save();
}
}
<?php
namespace Drupal\social_auth\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\user\UserInterface;
use Drupal\views\Views;
/**
* Defines a class to show social_auth entities for user.
*/
class UserController extends ControllerBase {
/**
* Social Auth profiles routing callback.
*
* @param \Drupal\user\UserInterface $user
* The user for which the social_auth profiles list is made.
*
* @return array
* The render array of the user social_auth profiles.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function socialAuthProfiles(UserInterface $user) {
$build = [];
/** @var \Drupal\views\ViewEntityInterface $view */
$view = NULL;
try {
$view = $this->entityTypeManager()->getStorage('view')->load('social_auth_profiles');
}
catch (\Exception $ignored) {
}
if ($view && $view->status()) {
$view = Views::getView('social_auth_profiles');
$view
->setArguments([
'user_id' => $user->id(),
]);
$build['list'] = $view->render('default');
}
else {
$build['list'] = $this->entityTypeManager()->getListBuilder('social_auth')->renderForUser($user);
}
return $build;
}
}