Хочу сделать авторизацию через соц. сети

Общие вопросы по использованию фреймворка. Если не знаете как что-то сделать и это про Yii, вам сюда.
Ответить
asisdes
Сообщения: 202
Зарегистрирован: 2013.10.03, 15:54

Хочу сделать авторизацию через соц. сети

Сообщение asisdes »

Хочу сделать авторизацию через соц. сети

делал по этому http://habrahabr.ru/post/129804/
и этому http://habrahabr.ru/post/129804/
рецепту

там еще на кэш ругался, но я в конфиге убрал эти параметры и все заработало.

но пока такая ошибка:
PHP warning

Missing argument 1 for LightOpenID::__construct(), called in Z:\home\cafe-bar.kz\www\protected\extensions\lightopenid\loid.php on line 34 and defined


Никто не сталкивался с таким?!
Изображение
lucky
Сообщения: 80
Зарегистрирован: 2015.03.06, 20:06

Re: Хочу сделать авторизацию через соц. сети

Сообщение lucky »

Попробуйте сделать так:
В файле protected/extensions/lightopenid/loid.php в строке 34 замените $openid = new LightOpenID(); на $openid = new LightOpenId('www.ваш домен.com');
У меня ошибка исчезла.
asisdes
Сообщения: 202
Зарегистрирован: 2013.10.03, 15:54

Re: Хочу сделать авторизацию через соц. сети

Сообщение asisdes »

подскажите как найти ошибку, оставил 3 сервиса: фейсбук, вконтакте и твиттер.
Ключи и секрет сгенерировал, при авторизации модальное окно всплывает с сообщение типа: "такой то сайт просит личные данные - разрешить?"
нажимаю: разрешить или ок
потом окно закрывает перехожу на форму логина... и ничего.
var_dump - разкомментировал, но так ничего и не выходит!?

Код: Выделить всё

<?php
    class UserIdentity extends CUserIdentity
    {
        protected $_id;

        public function authenticate()
        {
            $user = User::model()->find('LOWER(username)=?', array(strtolower($this->username)));
            if($user === null) {
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            } elseif(User::hashPassword($this->password, $user->salt) !== $user->password) {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            } else {
                $this->_id = $user->id;
                $this->errorCode = self::ERROR_NONE;
            }
            return !$this->errorCode;
        }

        public function getId()
        {
            return $this->_id;
        }

    } 
 
этот класс тоже в компанентах лежит

Код: Выделить всё

class ServiceUserIdentity extends UserIdentity {
    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) {
            $this->username = $this->service->getAttribute('name');
            $this->setState('id', $this->service->id);
            $this->setState('name', $this->username);
            $this->setState('service', $this->service->serviceName);
            $this->errorCode = self::ERROR_NONE; 
            echo "Privet"; 
            
            // You can save all given attributes in session.
            $attributes = $this->service->getAttributes();
            $array[$this->service->serviceName]= $attributes;
            Yii::app()->session->add("eauth_attributes", $array); 
            
        }
        else {
            $this->errorCode = self::ERROR_NOT_AUTHENTICATED;
        }
        return !$this->errorCode;
    }
}
 
и мой логинАктион

Код: Выделить всё

    public function actionLogin()
    {
    $serviceName = Yii::app()->request->getQuery('service');
    
        if (isset($serviceName)) {
            /** @var $eauth EAuthServiceBase */
            $eauth = Yii::app()->eauth->getIdentity($serviceName);
            $eauth->redirectUrl = Yii::app()->user->returnUrl;
            $eauth->cancelUrl = $this->createAbsoluteUrl('site/login');

            try {
                if ($eauth->authenticate()) {
                    var_dump($eauth->getIsAuthenticated(), $eauth->getAttributes());
                    $identity = new EAuthUserIdentity($eauth);

                    // successful authentication
                    if ($identity->authenticate()) {
                        Yii::app()->user->login($identity);
                        var_dump($identity->id, $identity->name, Yii::app()->user->id);exit;

                        // special redirect with closing popup window
                        $eauth->redirect();
                    }
                    else {
                        // close popup window and redirect to cancelUrl
                        $eauth->cancel();
                    }
                }

                // Something went wrong, redirect to login page
                $this->redirect(array('site/login'));
            }
            catch (EAuthException $e) {
                // save authentication error to session
                Yii::app()->user->setFlash('error', 'EAuthException: '.$e->getMessage());

                // close popup window and redirect to cancelUrl
                $eauth->redirect($eauth->getCancelUrl());
            }
        } 
      
       
        $model = new LoginForm;
        
        $this->layout='column2';
        
        // if it is ajax validation request
        if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if(isset($_POST['LoginForm']))
        {
            $model->attributes=$_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if($model->validate() && $model->login())
                
                //$this->lastViset();
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login',array('model'=>$model));
    }

 

кстати, это же окончательный код,
там логика должны быть типа,
при удачной авторизации, проверить пользователя по базе: почта, ID, service.
если нет внести, если есть авторизовать?!
Изображение
Ответить