Commit 058ab648 authored by difox's avatar difox

Social autorization

parent e9751cea
...@@ -48,6 +48,10 @@ class UrlManager extends \yii\web\UrlManager { ...@@ -48,6 +48,10 @@ class UrlManager extends \yii\web\UrlManager {
{ {
return '/' . $lang->url; return '/' . $lang->url;
} }
// Делаем универсальный URL без языка для Eauth авторизации
elseif (strpos($url, '/eauth') !== false) {
return $url;
}
else else
{ {
return '/' . $lang->url . $url; return '/' . $lang->url . $url;
......
<?php
namespace common\modules\eauth;
/**
* This module use extension https://github.com/Nodge/yii2-eauth
*/
class Module extends \common\components\WebModule
{
public static $active = false;
public static function name()
{
return 'Eauth';
}
public static function description()
{
return 'Авторизация через социальные сети';
}
public static function version()
{
return '1.0';
}
public function init()
{
parent::init();
}
}
<?php
namespace common\modules\eauth\components;
class FacebookOAuth2Service extends \nodge\eauth\services\FacebookOAuth2Service
{
use ServiceTrait;
protected function fetchAttributes()
{
$info = $this->makeSignedRequest('me', [
'query' => [
'fields' => join(',', [
'email',
'id',
'name',
'link',
'last_name',
'first_name',
'locale',
'picture',
'verified',
'gender',
]),
]
]);
$this->attributes['id'] = $info['id'];
$this->attributes['name'] = $info['name'];
$this->attributes['url'] = $info['link'];
$this->attributes['profile'] = [
'id' => $info['id'],
'email' => $info['email'],
// 'firstname' => $info['first_name'],
// 'lastname' => $info['last_name'],
'fullname' => $info['name'],
'locale' => $info['locale'],
];
return true;
}
}
<?php
namespace common\modules\eauth\components;
class GoogleOAuth2Service extends \nodge\eauth\services\GoogleOAuth2Service
{
use ServiceTrait;
protected function fetchAttributes()
{
$info = $this->makeSignedRequest('https://www.googleapis.com/oauth2/v1/userinfo');
echo '<pre>'; die(var_dump($info)); echo '</pre>';
$this->attributes['id'] = $info['id'];
$this->attributes['name'] = $info['name'];
if (!empty($info['link'])) {
$this->attributes['url'] = $info['link'];
}
$this->attributes['profile'] = [
'id' => $info['id'],
'email' => $info['email'],
// 'firstname' => $info['given_name'],
// 'lastname' => $info['family_name'],
'fullname' => $info['name'],
'locale' => $info['locale'],
];
}
}
<?php
namespace common\modules\eauth\components;
/**
* Trait extends functionality of nodge\eauth\BaseService class in extension "yii2-eauth"
*/
trait ServiceTrait
{
/**
* Logout from Oauth
*/
public function logout()
{
$this->getProxy()->getStorage()->clearToken($this->getServiceName());
}
public function checkAttributes()
{
die('1');
}
}
<?php
namespace common\modules\eauth\components;
class TwitterOAuth1Service extends \nodge\eauth\services\TwitterOAuth1Service
{
use ServiceTrait;
protected function fetchAttributes()
{
$info = $this->makeSignedRequest('account/verify_credentials.json', [
'include_email'=>1
]);
$this->attributes['id'] = $info['id'];
$this->attributes['name'] = $info['name'];
$this->attributes['url'] = 'http://twitter.com/account/redirect_by_id?id=' . $info['id_str'];
$this->attributes['profile'] = [
'id' => $info['id'],
'email' => $info['email'],
// 'firstname' => $info['name'],
// 'lastname' => $info['name'],
'fullname' => $info['name'],
'locale' => $info['lang'],
];
return true;
}
}
<?php
namespace common\modules\eauth\components;
class VkOAuth2Service extends \nodge\eauth\services\VKontakteOAuth2Service
{
use ServiceTrait;
/*
* Scopes MUST be declarated for use
*/
const SCOPE_EMAIL = 'email';
protected function fetchAttributes()
{
$tokenData = $this->getAccessTokenData();
$info = $this->makeSignedRequest('users.get.json', [
'query' => [
'uids' => $tokenData['params']['user_id'],
'fields' => 'uid, name, nickname, first_name, last_name, email', // uid, first_name and last_name is always available
],
]);
$info = $info['response'][0];
$this->attributes['id'] = $info['uid'];
$this->attributes['name'] = $info['first_name'] . ' ' . $info['last_name'];
$this->attributes['url'] = 'http://vk.com/id' . $info['uid'];
$this->attributes['profile'] = [
'id' => $tokenData['params']['user_id'],
'email' => $tokenData['params']['email'],
// 'firstname' => $info['first_name'],
// 'lastname' => $info['last_name'],
'fullname' => $info['first_name'].' '.$info['last_name'],
'locale' => 'ru',
];
return true;
}
}
<?php
namespace common\modules\eauth\widgets;
class Widget extends \nodge\eauth\Widget
{
/**
* Executes the widget.
* This method is called by {@link CBaseController::endWidget}.
*/
public function run()
{
echo $this->render('widget', [
'id' => $this->getId(),
'services' => $this->services,
'action' => $this->action,
'popup' => $this->popup,
'assetBundle' => $this->assetBundle,
]);
}
}
\ No newline at end of file
<?php
use yii\helpers\Html;
use yii\web\View;
/** @var $this View */
/** @var $id string */
/** @var $services stdClass[] See EAuth::getServices() */
/** @var $action string */
/** @var $popup bool */
/** @var $assetBundle string Alias to AssetBundle */
Yii::createObject(['class' => $assetBundle])->register($this);
// Open the authorization dilalog in popup window.
if ($popup) {
$options = [];
foreach ($services as $name => $service) {
$options[$service->id] = $service->jsArguments;
}
$this->registerJs('$("#' . $id . '").eauth(' . json_encode($options) . ');');
}
?>
<div class="eauth" id="<?php echo $id; ?>">
<ul class="eauth-list">
<?php
foreach ($services as $name => $service) {
echo '<li class="eauth-service eauth-service-id-' . $service->id . '">';
echo Html::a($service->title, [$action, 'service_eauth' => $name], [
'class' => 'eauth-service-link',
'data-eauth-service' => $service->id,
]);
echo '</li>';
}
?>
</ul>
</div>
...@@ -52,7 +52,7 @@ ...@@ -52,7 +52,7 @@
<?php <?php
echo $form; echo $form;
?> ?>
<?php echo \nodge\eauth\Widget::widget(['action' => '/site/login']); ?> <?php echo \common\modules\eauth\widgets\Widget::widget(['action' => '/site/login']); ?>
<div class="usl">Проходя регистрацию вы подтверждаете<br><a href="#">согласие на обработку персональных данных.</a></div> <div class="usl">Проходя регистрацию вы подтверждаете<br><a href="#">согласие на обработку персональных данных.</a></div>
</div> </div>
<div class="col-md-8 col-xs-6 col-sm-12"> <div class="col-md-8 col-xs-6 col-sm-12">
......
...@@ -155,8 +155,8 @@ return [ ...@@ -155,8 +155,8 @@ return [
'school' => 'school/course/index', 'school' => 'school/course/index',
'school/course/<id>' => 'school/course/view', 'school/course/<id>' => 'school/course/view',
'school/lesson/<id>' => 'school/lesson/view', 'school/lesson/<id>' => 'school/lesson/view',
'login' => 'site/login', 'login/eauth/<service_eauth:google|facebook|vk|twitter>' => 'site/login',
'login/<service:google|facebook|etc>' => 'site/login', 'login' => 'site/login',
'<page:(/)>' => 'content/page/view', '<page:(/)>' => 'content/page/view',
'<_m>/<_c>/<_a>/<id:\d+>' => '<_m>/<_c>/<_a>', '<_m>/<_c>/<_a>/<id:\d+>' => '<_m>/<_c>/<_a>',
...@@ -215,29 +215,29 @@ return [ ...@@ -215,29 +215,29 @@ return [
'services' => [ // You can change the providers and their classes. 'services' => [ // You can change the providers and their classes.
'google' => [ 'google' => [
// register your app here: https://code.google.com/apis/console/ // register your app here: https://code.google.com/apis/console/
'class' => 'nodge\eauth\services\GoogleOAuth2Service', 'class' => 'common\modules\eauth\components\GoogleOAuth2Service',
'clientId' => '978174489634-ploc443rik2ij4d9rbj1b8d889mr6pq7.apps.googleusercontent.com', 'clientId' => '...',
'clientSecret' => '3T4Do6Uu2f2Kx3NSLxrSogma', 'clientSecret' => '...',
'title' => 'Google', 'title' => 'Google',
], ],
/*'twitter' => [
// register your app here: https://dev.twitter.com/apps/new
'class' => 'nodge\eauth\services\TwitterOAuth1Service',
'key' => '...',
'secret' => '...',
],
'facebook' => [ 'facebook' => [
// register your app here: https://developers.facebook.com/apps/ // register your app here: https://developers.facebook.com/apps/
'class' => 'nodge\eauth\services\FacebookOAuth2Service', 'class' => 'common\modules\eauth\components\FacebookOAuth2Service',
'clientId' => '...', 'clientId' => '...',
'clientSecret' => '...', 'clientSecret' => '...',
], ],
'vkontakte' => [ 'vk' => [
// register your app here: https://vk.com/editapp?act=create&site=1 // register your app here: https://vk.com/editapp?act=create&site=1
'class' => 'nodge\eauth\services\VKontakteOAuth2Service', 'class' => 'common\modules\eauth\components\VkOAuth2Service',
'clientId' => '...', 'clientId' => '...',
'clientSecret' => '...', 'clientSecret' => '...',
],*/ ],
'twitter' => [
// register your app here: https://dev.twitter.com/apps/new
'class' => 'common\modules\eauth\components\TwitterOAuth1Service',
'key' => '...',
'secret' => '...',
],
], ],
], ],
], ],
......
...@@ -23,6 +23,7 @@ use \yii\web\Response; ...@@ -23,6 +23,7 @@ use \yii\web\Response;
use \yii\widgets\ActiveForm; use \yii\widgets\ActiveForm;
use common\modules\scoring\models\ScClient; use common\modules\scoring\models\ScClient;
use common\models\LoginForm; use common\models\LoginForm;
use common\modules\eauth\components\GoogleOAuth2Service;
/** /**
* Site controller * Site controller
...@@ -122,16 +123,28 @@ class SiteController extends BaseController ...@@ -122,16 +123,28 @@ class SiteController extends BaseController
public function actionLogin() public function actionLogin()
{ {
$serviceName = Yii::$app->request->getQueryParam('service'); $serviceName = Yii::$app->request->getQueryParam('service_eauth');
if (isset($serviceName)) { if (isset($serviceName)) {
/** @var $eauth \nodge\eauth\ServiceBase */ /** @var $eauth \nodge\eauth\ServiceBase */
$eauth = Yii::$app->get('eauth')->getIdentity($serviceName); $eauth = Yii::$app->get('eauth')->getIdentity($serviceName);
$eauth->setRedirectUrl(Yii::$app->getUser()->getReturnUrl()); $eauth->setRedirectUrl(Yii::$app->getUser()->getReturnUrl());
$eauth->setCancelUrl(Yii::$app->getUrlManager()->createAbsoluteUrl('site/login')); $eauth->setCancelUrl(Yii::$app->getUrlManager()->createAbsoluteUrl('site/login'));
if ($serviceName == 'facebook' || $serviceName == 'vk') {
$eauth->setScope('email');
}
else if ($serviceName == 'google') {
$eauth->setScope(GoogleOAuth2Service::SCOPE_EMAIL);
}
try { try {
if ($eauth->authenticate()) { if ($eauth->authenticate()) {
// var_dump($eauth->getIsAuthenticated(), $eauth->getAttributes()); exit;
// Добавить проверку обязательных полей - если нет какого-то
// обязательного поля, то предлагать другой сервис.
// $eauth->checkAttributes();
echo '<pre>'; die(var_dump($eauth->getAttributes())); echo '</pre>';
$identity = User::findByEAuth($eauth); $identity = User::findByEAuth($eauth);
Yii::$app->getUser()->login($identity); Yii::$app->getUser()->login($identity);
...@@ -145,6 +158,7 @@ class SiteController extends BaseController ...@@ -145,6 +158,7 @@ class SiteController extends BaseController
} }
} }
catch (\nodge\eauth\ErrorException $e) { catch (\nodge\eauth\ErrorException $e) {
echo '<pre>'; die(var_dump($e->getMessage())); echo '</pre>';
// save error to show it later // save error to show it later
Yii::$app->getSession()->setFlash('error', 'EAuthException: '.$e->getMessage()); Yii::$app->getSession()->setFlash('error', 'EAuthException: '.$e->getMessage());
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment