Commit 79ef690f authored by difox's avatar difox

Social plugin

parent 058ab648
......@@ -24,19 +24,20 @@ class FacebookOAuth2Service extends \nodge\eauth\services\FacebookOAuth2Service
]
]);
$this->attributes['id'] = $info['id'];
$this->attributes['name'] = $info['name'];
$this->attributes['url'] = $info['link'];
$this->attributes['profile'] = [
$profile = [
'id' => $info['id'],
'email' => $info['email'],
// 'firstname' => $info['first_name'],
// 'lastname' => $info['last_name'],
'fullname' => $info['name'],
'name' => $info['name'],
'locale' => $info['locale'],
];
$this->attributes['id'] = $info['id'];
$this->attributes['name'] = $info['name'];
$this->attributes['url'] = $info['link'];
$this->attributes['profile'] = $profile;
$this->setSocialProfile($profile);
return true;
}
}
......@@ -5,24 +5,26 @@ class GoogleOAuth2Service extends \nodge\eauth\services\GoogleOAuth2Service
{
use ServiceTrait;
protected $name = 'google';
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'] = [
$profile = [
'id' => $info['id'],
'email' => $info['email'],
// 'firstname' => $info['given_name'],
// 'lastname' => $info['family_name'],
'fullname' => $info['name'],
'name' => $info['name'],
'locale' => $info['locale'],
];
$this->attributes['id'] = $info['id'];
$this->attributes['name'] = $info['name'];
$this->attributes['url'] = $info['link'];
$this->attributes['profile'] = $profile;
$this->setSocialProfile($profile);
return true;
}
}
......@@ -6,6 +6,8 @@ namespace common\modules\eauth\components;
*/
trait ServiceTrait
{
protected $socialProfile;
/**
* Logout from Oauth
*/
......@@ -14,8 +16,20 @@ trait ServiceTrait
$this->getProxy()->getStorage()->clearToken($this->getServiceName());
}
public function getSocialProfile()
{
return $this->socialProfile;
}
public function setSocialProfile($profile)
{
$this->socialProfile = $profile;
}
public function checkAttributes()
{
die('1');
if (!$this->socialProfile['email']) {
die('Невозможно получить email');
}
}
}
......@@ -11,19 +11,20 @@ class TwitterOAuth1Service extends \nodge\eauth\services\TwitterOAuth1Service
'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'] = [
$profile = [
'id' => $info['id'],
'email' => $info['email'],
// 'firstname' => $info['name'],
// 'lastname' => $info['name'],
'fullname' => $info['name'],
'name' => $info['name'],
'locale' => $info['lang'],
];
$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'] = $profile;
$this->setSocialProfile($profile);
return true;
}
}
......@@ -5,6 +5,8 @@ class VkOAuth2Service extends \nodge\eauth\services\VKontakteOAuth2Service
{
use ServiceTrait;
protected $name = 'vk';
/*
* Scopes MUST be declarated for use
*/
......@@ -20,22 +22,22 @@ class VkOAuth2Service extends \nodge\eauth\services\VKontakteOAuth2Service
'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'] = [
$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'],
'name' => $info['first_name'].' '.$info['last_name'],
'locale' => 'ru',
];
$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'] = $profile;
$this->setSocialProfile($profile);
return true;
}
}
<?php
namespace common\modules\eauth\models;
use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
use common\modules\users\models\User;
use common\modules\rbac\models\AuthAssignment;
class UserEAuth extends \common\components\ActiveRecordModel
{
public $created_at;
public $updated_at;
public function attributeLabels()
{
$attrs = array_merge(parent::attributeLabels(), array(
"id" => "ID",
));
return $attrs;
}
public function rules()
{
return [
[['user_id'], 'required'],
[['google_id', 'twitter_id', 'vk_id', 'facebook_id'], 'integer','integerOnly' => true],
];
}
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public static function tableName()
{
return 'users_eauth';
}
public function name()
{
return "Социальные аккаунты пользователя";
}
public static function findById($id)
{
return static::findOne(['id' => $id]);
}
/**
* Finds user by user id
*
* @param string $user_id
* @return static|null
*/
public static function findByUserId($user_id)
{
return static::findOne(['user_id' => $user_id]);
}
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'User', 'user_id')
);
}
/**
* @param \nodge\eauth\ServiceBase $service
* @return User
* @throws ErrorException
*/
public function getByEAuth($service) {
/*if (!$service->getIsAuthenticated()) {
throw new ErrorException('EAuth user should be authenticated before creating identity.');
}*/
$userModel = new User();
$socialProfile = $service->getSocialProfile();
$eauthField = $service->getServiceName().'_id';
// Check is User EAuth service token exists
if ($this->isEAuthExists($service)) {
// Get existing user model
return $userModel->getByEAuth($service);
}
// Check is User with such email exists - assign Eauth token to him
elseif ($userModel->isUserEmailExists($socialProfile['email'])) {
$model = User::findByUsername($socialProfile['email']);
// Assign service token
$modelEAuth = $model->eauth;
$modelEAuth->{$eauthField} = $socialProfile['id'];
$modelEAuth->update(false, [$eauthField]);
return $model;
}
else {
// Create and save new user
$model = new User();
$model->scenario = User::SCENARIO_SOCIAL_REGISTRATION;
$model->email = $socialProfile['email'];
$model->name = $socialProfile['name'];
$model->status = User::STATUS_ACTIVE;
$model->activate_date = date('Y-m-d H:i:s');
if ($model->save()) {
// Assign role
$assignment = new AuthAssignment();
$assignment->item_name = 'user';
$assignment->user_id = $model->id;
$assignment->save();
// Assign EAuth data
$eauth = new UserEAuth();
$eauth->user_id = $model->id;
$eauth->{$eauthField} = $socialProfile['id'];
$eauth->save();
return $model;
}
else {
echo '<pre>'; die(var_dump($model->getErrors())); echo '</pre>';
}
return false;
}
/*$id = $service->getServiceName().'-'.$service->getId();
$attributes = [
'id' => $id,
'username' => $service->getAttribute('name'),
'authKey' => md5($id),
'profile' => $service->getAttributes(),
];
$attributes['profile']['service'] = $service->getServiceName();
Yii::$app->getSession()->set('user-'.$id, $attributes);*/
}
public function isEAuthExists($service)
{
$socialProfile = $service->getSocialProfile();
$eauthField = $service->getServiceName().'_id';
return (bool)static::find()->where($eauthField.' = :eauth', [':eauth'=>$socialProfile['id']])->count();
}
}
<?php
namespace common\modules\eauth\widgets;
class Widget extends \nodge\eauth\Widget
class SocialWidget extends \nodge\eauth\Widget
{
/**
* Executes the widget.
......
......@@ -23,6 +23,7 @@ if ($popup) {
?>
<div class="eauth" id="<?php echo $id; ?>">
<p>Войти, используя соцсети:</p>
<ul class="eauth-list">
<?php
foreach ($services as $name => $service) {
......
<?php
use common\modules\eauth\widgets;
?>
<section class="sh_kurs">
<div class="container">
<div class="row">
......@@ -45,6 +48,8 @@
</div>
</div>
</section>
<?php if (Yii::$app->user->isGuest): ?>
<section class="sh_ft">
<div class="container">
<div class="row">
......@@ -52,7 +57,7 @@
<?php
echo $form;
?>
<?php echo \common\modules\eauth\widgets\Widget::widget(['action' => '/site/login']); ?>
<?php echo common\modules\eauth\widgets\SocialWidget::widget(['action' => '/site/login']); ?>
<div class="usl">Проходя регистрацию вы подтверждаете<br><a href="#">согласие на обработку персональных данных.</a></div>
</div>
<div class="col-md-8 col-xs-6 col-sm-12">
......@@ -63,6 +68,8 @@
</div>
</div>
</section>
<?php endif ?>
<div class="tr_foot"></div>
<footer>
<div class="container">
......
<?php
use yii\helpers\Url;
use common\modules\users\widgets;
?>
<section class="ks_header">
<div class="container">
......@@ -11,10 +12,8 @@
<div class="ball_hover">Текст как увеличить,<br> текст как увеличить,</div>
</div>
</div>
<div class="col-md-3 col-md-offset-4 col-xs-5 col-sm-12">
<div class="prof_block">
<span class="prof_name">Дмитрий</span><a href="#">Выход</a>
</div>
<div class="col-md-5 col-md-offset-2 col-xs-5 col-sm-12">
<?php echo \common\modules\users\widgets\UserBoxWidget::widget() ?>
</div>
</div>
</div>
......
<?php
use common\modules\users\widgets;
?>
<section class="ks_header">
<div class="container">
<div class="row">
......@@ -8,10 +11,8 @@
<div class="ball_hover">Текст как увеличить,<br> текст как увеличить,</div>
</div>
</div>
<div class="col-md-3 col-md-offset-4 col-xs-5 col-sm-12">
<div class="prof_block">
<span class="prof_name">Дмитрий</span><a href="#">Выход</a>
</div>
<div class="col-md-5 col-md-offset-2 col-xs-5 col-sm-12">
<?php echo UserBoxWidget::widget() ?>
</div>
</div>
</div>
......
......@@ -102,9 +102,11 @@ class UserController extends \common\components\BaseController {
}
public function actionLogout() {
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
......
......@@ -12,9 +12,13 @@ use \common\components\validators\RuEmailValidator;
use \common\modules\rbac\models\AuthItem;
use \common\modules\rbac\models\AuthAssignment;
use \common\modules\eauth\models\UserEAuth;
class User extends \common\components\ActiveRecordModel implements IdentityInterface
{
public $created_at;
public $updated_at;
const PAGE_SIZE = 10;
const OCCUPATION_CHIEF_IT = 1;
......@@ -49,6 +53,7 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
const SCENARIO_SEARCH = 'Search';
const SCENARIO_CSV_IMPORT = 'CSV_IMPORT';
const SCENARIO_RECOVER_PASSWORD = 'RecoverPassword';
const SCENARIO_SOCIAL_REGISTRATION = 'SocialRegistration';
// public $email;
public $role;
......@@ -121,6 +126,7 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
self::SCENARIO_CREATE,
self::SCENARIO_LOGIN,
self::SCENARIO_REGISTRATION,
self::SCENARIO_SOCIAL_REGISTRATION,
self::SCENARIO_UPDATE,
self::SCENARIO_SEND_NEW_PASSWORD,
self::SCENARIO_RECOVER_PASSWORD
......@@ -131,6 +137,7 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
], 'message' => 'Пожалуйста, укажите Ваше имя'],
[['name'], 'required', 'on' => [
self::SCENARIO_REGISTRATION,
self::SCENARIO_SOCIAL_REGISTRATION,
], 'message' => 'Пожалуйста, укажите Ваше имя'],
[['phone'], 'required', 'on' => [
self::SCENARIO_CREATE,
......@@ -373,10 +380,16 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
{
return array(
'assignment' => array(self::HAS_ONE, 'AuthAssignment', 'user_id'),
'city' => array(self::BELONGS_TO, 'City', 'city_id')
'city' => array(self::BELONGS_TO, 'City', 'city_id'),
//'eauth' => array(self::HAS_ONE, 'UserEAuth', 'user_id'),
);
}
public function getEauth()
{
return $this->hasOne(UserEAuth::className(), ['user_id'=>'id']);
}
public function search($params)
{
......@@ -520,26 +533,20 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
return $granted;
}
/**
* @param \nodge\eauth\ServiceBase $service
* @return User
* @throws ErrorException
*/
public static function findByEAuth($service) {
if (!$service->getIsAuthenticated()) {
throw new ErrorException('EAuth user should be authenticated before creating identity.');
public function getByEAuth($service)
{
$socialProfile = $service->getSocialProfile();
$eauthField = $service->getServiceName().'_id';
return static::find()
->joinWith('eauth')
->where('users_eauth.'.$eauthField.' = :eauthId', [':eauthId' => $socialProfile['id']])
->one();
}
$id = $service->getServiceName().'-'.$service->getId();
$attributes = [
'id' => $id,
'username' => $service->getAttribute('name'),
'authKey' => md5($id),
'profile' => $service->getAttributes(),
];
$attributes['profile']['service'] = $service->getServiceName();
Yii::$app->getSession()->set('user-'.$id, $attributes);
return new self($attributes);
public function isUserEmailExists($email)
{
return (bool)static::find(['email' => $email])->count();
}
}
<?php
namespace common\modules\users\widgets;
use yii\base\Widget;
use Yii;
class UserBoxWidget extends Widget
{
public $user;
/**
* Executes the widget.
* This method is called by {@link CBaseController::endWidget}.
*/
public function run()
{
$this->setUser();
echo $this->render('UserBoxWidget', ['user'=>$this->user]);
}
public function setUser()
{
$this->user = Yii::$app->user->getIdentity();
}
}
\ No newline at end of file
<?php
use yii\helpers\Html;
use yii\web\View;
?>
<div class="prof_block"> <span class="prof_name"><?php echo $user->name ?></span>
<?php echo Html::a('Выход', ['/site/logout']) ?></div>
\ No newline at end of file
<?php
use yii\db\Migration;
use yii\db\Schema;
class m160207_204809_create_eauth_table extends Migration
{
public function up()
{
$this->createTable('users_eauth', [
'id' => Schema::TYPE_PK,
'user_id' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'google_id' => Schema::TYPE_STRING . '(100) NOT NULL',
'vk_id' => Schema::TYPE_STRING . '(100) NOT NULL',
'twitter_id' => Schema::TYPE_STRING . '(100) NOT NULL',
'facebook_id' => Schema::TYPE_STRING . '(100) NOT NULL',
]);
}
public function down()
{
$this->dropTable('eauth_table');
}
}
......@@ -157,6 +157,7 @@ return [
'school/lesson/<id>' => 'school/lesson/view',
'login/eauth/<service_eauth:google|facebook|vk|twitter>' => 'site/login',
'login' => 'site/login',
'logout' => 'site/logout',
'<page:(/)>' => 'content/page/view',
'<_m>/<_c>/<_a>/<id:\d+>' => '<_m>/<_c>/<_a>',
......
......@@ -24,6 +24,7 @@ use \yii\widgets\ActiveForm;
use common\modules\scoring\models\ScClient;
use common\models\LoginForm;
use common\modules\eauth\components\GoogleOAuth2Service;
use common\modules\eauth\models\UserEAuth;
/**
* Site controller
......@@ -140,21 +141,21 @@ class SiteController extends BaseController
try {
if ($eauth->authenticate()) {
$eauth->getAttributes(); // get EAuth info
// Добавить проверку обязательных полей - если нет какого-то
// обязательного поля, то предлагать другой сервис.
// $eauth->checkAttributes();
echo '<pre>'; die(var_dump($eauth->getAttributes())); echo '</pre>';
// обязательного поля, то выводить форму для заполнения
$eauth->checkAttributes();
$identity = User::findByEAuth($eauth);
$userEAuthModel = new UserEAuth();
$identity = $userEAuthModel->getByEAuth($eauth);
Yii::$app->getUser()->login($identity);
// special redirect with closing popup window
$eauth->redirect();
$eauth->redirect('/school');
}
else {
// close popup window and redirect to cancelUrl
$eauth->cancel();
$eauth->cancel('/school');
}
}
catch (\nodge\eauth\ErrorException $e) {
......@@ -163,8 +164,7 @@ class SiteController extends BaseController
Yii::$app->getSession()->setFlash('error', 'EAuthException: '.$e->getMessage());
// close popup window and redirect to cancelUrl
// $eauth->cancel();
$eauth->redirect($eauth->getCancelUrl());
$eauth->cancel('/school');
}
}
......
......@@ -9,3 +9,18 @@
background: #fff url(../images/icon-fail.png) no-repeat 96% center;
border: 1px solid #E9A2A2;
}
/* EAuth widget */
.eauth-service-id-vk .eauth-service-link:before {
background-position: 0 -136px;
}
.eauth-service-id-google .eauth-service-link:before {
background-position: 0 -34px;
}
.eauth-service {
text-indent: -9999px;
margin: 0 !important;
}
.eauth-list {
margin: 0 !important;
margin-top: 10px !important;
}
\ No newline at end of file
......@@ -3967,7 +3967,7 @@ footer {
-webkit-border-radius: 50px;
-o-border-radius: 50px;
-ms-border-radius: 50px;
margin-bottom: 34px;
margin-bottom: 10px;
color: #698387;
font-size: 16px;
padding: 0px 18px;
......@@ -11461,7 +11461,7 @@ h6 {
list-style: none;
}
.teltext-block{
margin-top: -40px;
/*margin-top: -40px;*/
margin-bottom: 15px;
color: #698387;
font-size: 14px;
......
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