Commit 59d6a788 authored by Marcello Pivanti's avatar Marcello Pivanti
Browse files

Initial Commit

parents
Amos Social Auth
-----------------------
Social Auth For Amos
Installation
------------
1. The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
Either run
```bash
composer require elitedivision/amos-social-auth
```
or add
```
"elitedivision/amos-social-auth": "~1.0"
```
to the require section of your `composer.json` file.
2. Add module to your main config in common:
```php
<?php
'modules' => [
'socialauth' => [
'class' => 'elitedivision\amos\socialauth\Module'
],
],
```
3. Apply migrations
```bash
php yii migrate/up --migrationPath=@vendor/elitedivision/amos-social-auth/src/migrations
```
Configuration
-------------
* Sample configuration
```php
<?php
'modules' => [
'socialauth' => [
'class' => 'elitedivision\amos\socialauth\Module',
'enableLogin' => true,
'enableLink' => false,
'enableRegister' => false,
'providers' => [
"Facebook" => [
"enabled" => true,
"keys" => [
"id" => "",
"secret" => ""
],
"scope" => "email"
],
"Twitter" => [
"enabled" => true,
"keys" => [
"key" => "",
"secret" => ""
],
"scope" => 'email',
"includeEmail" => true
],
"Google" => [
"enabled" => true,
"keys" => [
"id" => "",
"secret" => ""
],
"scope" => 'email',
"includeEmail" => true
],
]
],
],
```
see configuration doc: https://hybridauth.github.io/hybridauth/userguide/Configuration.html
* Action enable/disable
* `enableLogin` To alow Social Login
* `enableLink` To Enable Social Account Linking (my-profile 'settings' tab)
* `enableRegister` To Enable Registration with Social
* `enableServices` To list enabled services related to social accounts. By default the array contains `calendar` and `contacts`
The provider linking functionality is managed in 'My Profile', amos-admin.
To enable social links check in admin configuraion the visibility for box social-accounts and for the the providers buttons.
```php
$modules['admin'] = [
'class' => 'elitedivision\amos\admin\AmosAdmin',
'enableRegister' => true,
'fieldsConfigurations' => [
'boxes' => [
.
.
.
'box_social_account' => ['form' => true, 'view' => true],
],
'fields' => [
.
.
.
'facebook' => ['form' => true, 'view' => true, 'referToBox' => 'box_social_account'],
'google' => ['form' => true, 'view' => true, 'referToBox' => 'box_social_account'],
'linkedin' => ['form' => true, 'view' => true, 'referToBox' => 'box_social_account'],
'twitter' => ['form' => true, 'view' => true, 'referToBox' => 'box_social_account'],
.
.
.
]
]
];
```
Providers
------------
Providers configuration doc: https://hybridauth.github.io/hybridauth/userguide.html section 'Popular Providers'
* Google
(guide from https://hybridauth.github.io/hybridauth/userguide/IDProvider_info_Google.html)
1. Go to the Google Developers Console
https://console.developers.google.com/projectselector/apis/library?supportedpurview=project.
2. From the project drop-down, select a project, or create a new one.
3. Enable the Google API services:
In the list of Google APIs, search for the Google+ API service.
Select Google+ API from the results list.
Press the Enable API button.
The same for People API and Calendar API
* Enable API in Google console
**for account and contacts:** People API, Google+ API
**for calendar events:** Google Calendar API
4. When the process completes, enabled APIs appears in the list of enabled APIs. To access, select API Manager on the left sidebar menu, then select the Enabled APIs tab.
5. In the sidebar under "API Manager", select Credentials.
In the Credentials tab, select the New credentials drop-down list, and choose **OAuth client ID**.
6. From the Application type list, choose the Web application.
7. Enter a name and provide this URLs as Authorized redirect URIs:
http://YourPlatformUrl/socialauth/social-auth/endpoint?action=done&provider=google
http://YourPlatformUrl/admin/user-profile/enable-google-service
https://YourPlatformUrl/socialauth/social-auth/endpoint?action=done&provider=google
https://YourPlatformUrl/admin/user-profile/enable-google-service
8. Once you have registered, copy and past the created application credentials (Client ID and Secret) into the HybridAuth config file.
\ No newline at end of file
{
"name": "arter/amos-social-auth",
"description": "Social Auth",
"keywords": [
"amos",
"auth",
"social",
"yii2"
],
"homepage": "https://bitbucket.org/elite_division/amos-social-auth",
"type": "component",
"require": {
"php": ">=5.4.0",
"arter/amos-admin": "^2.0.18",
"arter/amos-core": "^1.9.52",
"arter/amos-attachments": "^1.0",
"hybridauth/hybridauth": "~2.9",
"google/apiclient": "^2.0"
},
"autoload": {
"psr-4": {
"elitedivision\\amos\\socialauth\\": "src"
}
}
}
\ No newline at end of file
<?php
/**
* Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
* OPEN 2.0
*
*
* @package elitedivision\amos\socialauth
* @category CategoryName
* @author Elite Division S.r.l.
*/
namespace elitedivision\amos\socialauth;
use elitedivision\amos\admin\AmosAdmin;
use elitedivision\amos\core\module\AmosModule;
use elitedivision\amos\socialauth\controllers\ShibbolethController;
use elitedivision\amos\socialauth\models\SocialAuthServices;
use Yii;
use yii\base\BootstrapInterface;
use yii\helpers\ArrayHelper;
/**
* Class Module
* @package elitedivision\amos\socialauth
*/
class Module extends AmosModule implements BootstrapInterface
{
public static $CONFIG_FOLDER = 'config';
/**
* @var array providers configuration
*/
public $providers = [];
/**
* @var $enableLogin bool Is Login With Social Enabled?
*/
public $enableLogin;
/**
* @var $enableSpid bool Is Login With Spid Enabled?
*/
public $enableSpid = false;
/**
* @var $enableLogin bool Is Social Account Link Enabled?
*/
public $enableLink;
/**
* @var $enableLogin bool Is Social registration Enabled?
*/
public $enableRegister;
/**
* @var bool Decide if the overload security is enabled (false) or user can be oberloaded by social (true)
*/
public $userOverload = false;
/**
* @var bool $enableServices - array with enabled service names
*/
public $enableServices = ['calendar', 'contacts'];
/**
* @inheritdoc
*/
public $name = 'socialauth';
/**
* @var string $moduleName
*/
private static $moduleName = 'socialauth';
/**
* @var string|boolean the layout that should be applied for views within this module. This refers to a view name
* relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
* will be taken. If this is false, layout will be disabled within this module.
*/
public $layout = 'main';
/**
* @inheritdoc
*/
public $controllerNamespace = 'elitedivision\amos\socialauth\controllers';
public $timeout = 180;
/**
* @var bool $enableSpidMultiUsersSameCF If true the model validation doesn't check the unique of che fiscal code.
*/
public $enableSpidMultiUsersSameCF = false;
/**
* @inheritdoc
*/
public function init()
{
parent::init(); // TODO: Change the autogenerated stub
\Yii::setAlias('@elitedivision/amos/' . static::getModuleName() . '/controllers', __DIR__ . '/controllers');
//Configuration
$config = require(__DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php');
\Yii::configure($this, ArrayHelper::merge($config, $this));
}
/**
* @return array
*/
public function getProviders()
{
return $this->providers;
}
/**
* @inheritdoc
*/
public static function getModuleName()
{
return static::$moduleName;
}
/**
* @inheritdoc
*/
public function getWidgetIcons()
{
return [
];
}
/**
* @inheritdoc
*/
public function getWidgetGraphics()
{
return [
];
}
/**
* @inheritdoc
*/
protected function getDefaultModels()
{
return [
];
}
/**
* @param string $provider
* @param null|SocialAuthServices $service
* @return \Google_Client|null
*/
public function getClient($provider = 'google', $service = null)
{
$providers = $this->providers;
$client = null;
if ($provider == 'google') {
if (!empty($providers) && array_key_exists('Google', $providers)) {
$key = $providers['Google']['keys']['secret'];
$clientId = $providers['Google']['keys']['id'];
$client = new \Google_Client();
$client->setClientId($clientId);
$client->setClientSecret($key);
if (!is_null($service)) {
$accessToken['access_token'] = $service->access_token;
$accessToken['token_type'] = $service->token_type;
$accessToken['expires_in'] = $service->expires_in;
$accessToken['created'] = $service->token_created;
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$accessToken = $client->fetchAccessTokenWithRefreshToken($service->refresh_token);
$service->access_token = $accessToken['access_token'];
$service->token_type = $accessToken['token_type'];
$service->expires_in = $accessToken['expires_in'];
$service->token_created = $accessToken['created'];
if (!$service->save()) {
\Yii::$app->session->addFlash('danger', Module::t('amossocialauth',
'An error occurred while synchronizing {provider} {serviceName}',
['provider' => $provider, 'serviceName' => $service->service]));
}
}
}
}
}
return $client;
}
/**
* @param SocialAuthServices $service
* @return string $message
*/
public function synchronizeGoogleService($service)
{
$message = '';
$client = $this->getClient('google', $service);
if ($service->service == 'calendar') {
$serviceGoogle = new \Google_Service_Calendar($client);
$calendarId = $service->service_id;
if (empty($calendarId)) {
$calendar = new \Google_Service_Calendar_Calendar();
$calendar->setSummary(\Yii::$app->name);
$calendar = $serviceGoogle->calendars->insert($calendar);
$calendarId = $calendar->getId();
$service->service_id = $calendarId;
$service->save(false);
$message = Module::t('amossocialauth', 'Calendar \'{appName}\' has been added successfully to your Google Account.', ['appName' => \Yii::$app->name]);
} else {
$message .= Module::t('amossocialauth', 'Calendar \'{appName}\' synchronization', ['appName' => \Yii::$app->name]);
}
$eventsModule = Yii::$app->getModule('events');
if (!is_null($eventsModule)) {
return $eventsModule->synchronizeEvents($serviceGoogle, $calendarId, $message);
}
} elseif ($service->service == 'contacts') {
$serviceGoogle = new \Google_Service_PeopleService($client);
$message = AmosAdmin::synchronizeGoogleContacts($serviceGoogle);
}
return $message;
}
/**
* @param SocialAuthServices $service
* @return string
*/
public function removeGoogleService($service)
{
$message = '';
$client = $this->getClient();
$accessToken['access_token'] = $service->access_token;
$accessToken['token_type'] = $service->token_type;
$accessToken['expires_in'] = $service->expires_in;
$accessToken['created'] = $service->token_created;
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$accessToken = $client->fetchAccessTokenWithRefreshToken($service->refresh_token);
$service->access_token = $accessToken['access_token'];
$service->token_type = $accessToken['token_type'];
$service->expires_in = $accessToken['expires_in'];
$service->token_created = $accessToken['created'];
if (!$service->save()) {
$message = Module::t('amosadmin', 'Errore durante l\'aggiornamento delle impostazioni');
}
}
if ($service->service == 'calendar') {
$message .= ' calendar : ';
$serviceGoogle = new \Google_Service_Calendar($client);
$calendarId = $service->service_id;
if (!empty($calendarId)) {
$calendar = $serviceGoogle->calendars->get($calendarId);
if ($calendar) {
$message .= $calendarId . ' ';
}
}
$serviceGoogle->calendars->delete($calendarId);
} elseif ($service->service == 'contacts') {
AmosAdmin::removeGoogleContacts();
}
return $message;
}
/**
* @inheritdoc
*/
public function bootstrap($app)
{
//Init a new shibboleth controller to link user
$shibbolethController = new ShibbolethController('shibboleth', $this);
//Get Session IDM datas (copy of headers)
$sessionIDM = \Yii::$app->session->get('IDM');
//Link to current user with IDM
if ($sessionIDM && $sessionIDM['matricola']) {
return $shibbolethController->tryIdmLink('idm', $sessionIDM, false, false);
} else if ($sessionIDM && $sessionIDM['saml_attribute_codicefiscale']) {
return $shibbolethController->tryIdmLink('spid', $sessionIDM, false, false);
}
}
}
<?php
/**
* Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
* OPEN 2.0
*
*
* @package elitedivision\amos\socialauth
* @category CategoryName
* @author Elite Division S.r.l.
*/
namespace elitedivision\amos\socialauth\components;
use elitedivision\amos\core\icons\AmosIcons;
use elitedivision\amos\socialauth\Module;
use Yii;
use yii\base\Component;
use yii\base\Widget;
use yii\db\ActiveRecord;
use yii\helpers\Html;
/**
* Class FileImport
* @package elitedivision\amos\socialauth\components
*/
class SocialAuthBar extends Widget
{
public function run()
{
parent::run();
/**
* Return string
*/
$result = '';
/**
* @var $module Module
*/
$module = Yii::$app->getModule('socialauth');
/**
* List of providers configured
*/
$providers = $module->providers;
return $this->render('social-auth-bar', [
'providers' => $providers
]);
}
}
<?php
/**
* Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
* OPEN 2.0
*
*
* @package elitedivision\amos\socialauth
* @category CategoryName
* @author Elite Division S.r.l.
*/
namespace elitedivision\amos\socialauth\components;
use elitedivision\amos\core\icons\AmosIcons;
use elitedivision\amos\socialauth\models\SocialAuthUsers;
use elitedivision\amos\socialauth\Module;
use Yii;
use yii\base\Component;
use yii\base\Widget;
use yii\db\ActiveRecord;
use yii\helpers\Html;
/**
* Class FileImport
* @package elitedivision\amos\socialauth\components
*/
class SocialLinkBar extends Widget
{
public function run()
{
parent::run();
/**
* Return string
*/
$result = '';
/**
* @var $module Module
*/
$module = Yii::$app->getModule('socialauth');
/**
* List of providers configured
*/
$providers = $module->providers;
/**
* @var $enabledProviders array List of providers not yet linked
*/
$enabledProviders = [];
/**
* Iterate all provider and find existing links
*/
foreach ($providers as $providerName=>$config) {
$lowCaseName = strtolower($providerName);
/**
* @var $socialAccount SocialAuthUsers
*/
$socialAccount = SocialAuthUsers::findOne([
'provider' => $lowCaseName,
'user_id' => Yii::$app->user->id
]);
/**
* If the user profile is not linked to this user append the provider
*/
if(!$socialAccount || !$socialAccount->id) {
$enabledProviders[$providerName] = $config;
}
}
return $this->render('social-link-bar', [
'providers' => $enabledProviders
]);
}
}
<?php
/**
* Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
* OPEN 2.0
*
*
* @package elitedivision\amos\socialauth\components
* @category CategoryName
* @author Elite Division S.r.l.
*/
namespace elitedivision\amos\socialauth\components;
use elitedivision\amos\socialauth\Module;
use Yii;
use yii\base\Widget;
/**
* Class SocialLinkTable
* @package elitedivision\amos\socialauth\components
*/
class SocialLinkTable extends Widget
{
/**
* @inheritdoc
*/
public function run()
{
parent::run();
/**
* @var $module Module
*/
$module = Yii::$app->getModule('socialauth');
/**