Всем привет!
Так как на предыдущий вопрос про модуль Lily ответа так и не получил, решил подойти с другого конца и попробовать самому синтегрировать Eauth и Yii-User.
Но пока что меня хватило только на добавление 2-х полей в {{users}} - service и identity, как это рекомендует автор Eauth.
А что делать дальше абсолютно не понимаю, честно говоря
Т.е. есть понимание, что логин с помощью соц. сетей должен триггерить проверку существования такого пользователя в {{users}} и регистрацию нового юзера, если такового не найдено, но как чисто технически это правильно реализуется - ума не приложу.
Ни о каком объединении аккаунтов одного человека в разных соц. сетях пока и речи не идёт, для начала хотелось бы просто получить соотношение: 1 новый юзер, залогиненный через соц. сеть == 1 новый Yii user.
Натолкните пожалуйста, каким именно образом связывать данные расширение и модуль, хотя бы просто на уровне идеи.
Заранее большое спасибо за любую помощь!
Интеграция Eauth с Yii-User
Re: Интеграция Eauth с Yii-User
Anyone?
Re: Интеграция Eauth с Yii-User
Здравствуйте, делал подключение по статье на хабре http://habrahabr.ru/post/129804/
Вот мой основной код:
и собственно ServiceUserIdentity, где регистрируются новые пользователи через сервисы:
Вот мой основной код:
Код: Выделить всё
class AuthController extends Controller
{
public function actionLogin()
{
$service = Yii::app()->request->getQuery('service');
if (isset($service)) {
$authIdentity = Yii::app()->eauth->getIdentity($service);
$authIdentity->redirectUrl = Yii::app()->user->getReturnUrl();
$authIdentity->cancelUrl = $this->createAbsoluteUrl('auth/login');
if ($authIdentity->authenticate()) {
$identity = new ServiceUserIdentity($authIdentity);
if ($identity->authenticate()) {
Yii::app()->user->login($identity, Yii::app()->params['auth']['cookieTime']);
$authIdentity->redirect();
}
else {
$authIdentity->cancel();
}
}
$this->redirect(array('auth/login'));
}
else {
$login = Yii::app()->request->getParam('login');
$password = Yii::app()->request->getParam('password');
$identity = new UserIdentity($login, $password);
if ($identity->authenticate()) {
Yii::app()->user->login($identity, Yii::app()->params['auth']['cookieTime']);
if (Yii::app()->getRequest()->getIsAjaxRequest()) {
echo CJSON::encode(array('success' => true));
Yii::app()->end();
}
}
else {
if (Yii::app()->getRequest()->getIsAjaxRequest()) {
echo CJSON::encode(array('error' => $identity->errorMessage));
Yii::app()->end();
}
else {
Yii::app()->user->setFlash('loginErr', $identity->errorMessage);
}
}
}
}
}
Код: Выделить всё
<?php
class ServiceUserIdentity extends CUserIdentity
{
private $_id;
const ERROR_NOT_AUTHENTICATED = 3;
/**
* @var EAuthServiceBase the authorization service instance.
*/
protected $service;
/**
* Constructor.
* @param EAuthServiceBase $service the authorization service instance.
*/
public function __construct($service)
{
$this->service = $service;
}
/**
* Authenticates a user based on {@link username}.
* This method is required by {@link IUserIdentity}.
* @return boolean whether authentication succeeds.
*/
public function authenticate()
{
if ($this->service->isAuthenticated) {
$userKey = md5($this->service->serviceName . $this->service->id);
$user = FactoryService::get('user')->getBy('login = :login', array(':login' => $userKey));
$data = new stdClass();
if (!$user) {
$data->login = $userKey;
$data->password = md5(Yii::app()->params['pwdSalt'] . uniqid());
$data->profile_name = $this->service->getAttribute('name');
$data->register_date = date('Y-m-d H:i:s');
$user = new UserModel($data);
}
$data->visit_date = date('Y-m-d H:i:s');
$data->last_ip = Yii::app()->getRequest()->getUserHostAddress();
$user->setDbData($data);
if (FactoryService::get('user')->save($user)) {
$this->_id = $user->getId();
$this->username = $this->service->getAttribute('name');
$this->setState('id', $this->_id);
$this->setState('serviceId', $this->service->id);
$this->setState('name', $this->username);
$this->setState('service', $this->service->serviceName);
$this->errorCode = self::ERROR_NONE;
}
else {
$this->errorCode = self::ERROR_NOT_AUTHENTICATED;
}
}
else {
$this->errorCode = self::ERROR_NOT_AUTHENTICATED;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
Re: Интеграция Eauth с Yii-User
Спасибо большое за код, кажется у меня начинает формироваться понимание
А подскажите плиз, FactoryService что из себя представляет?
А подскажите плиз, FactoryService что из себя представляет?
Re: Интеграция Eauth с Yii-User
Это мой класс для получения сервисов.
Это не часть фреймворка. У меня сервисы служат для работы с мапперами.
Код: Выделить всё
class FactoryService
{
private static $_cache;
public static function get($serviceName)
{
if (!$serviceName) {
throw new Exception("Service name is not define");
}
if (isset(self::$_cache[$serviceName])) {
return self::$_cache[$serviceName];
}
$className = ucfirst($serviceName) . 'Service';
if (!class_exists($className)) {
throw new Exception("Service not exists");
}
$service = new $className();
self::$_cache[$serviceName] = $service;
return $service;
}
}
Re: Интеграция Eauth с Yii-User
Получилось у кого-то реализавать интеграцию yii-user и yii-eauth? Если есть такие, не могли бы описать что вы делали и желательно с примерами кода.
Re: Интеграция Eauth с Yii-User
Знаю, что тема старая, но может кому пригодится пример использования yii-user+rights+eauth.octavi4 писал(а):Получилось у кого-то реализавать интеграцию yii-user и yii-eauth? Если есть такие, не могли бы описать что вы делали и желательно с примерами кода.
-
- Сообщения: 87
- Зарегистрирован: 2014.04.18, 14:21
Re: Интеграция Eauth с Yii-User
у кого то есть реализация всей этой штуки?