Авторизация по IP

Общие вопросы по использованию фреймворка. Если не знаете как что-то сделать и это про Yii, вам сюда.
Ответить
Странник
Сообщения: 295
Зарегистрирован: 2013.04.08, 10:35
Откуда: Нижний Новгород

Авторизация по IP

Сообщение Странник »

Возникла необходимость переделать авторизацию. Авторизация по IP с присвоением ролей.
Что-то не получается. Есть у кого примеры?
Делаю так:
UserIdentity

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

class UserIdentity extends CUserIdentity
{
    private $_id;
    public function authenticate()
    {
        $record=User::model()->findByAttributes(array('ip'=>$this->ip));
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else
        {
            $this->_id=$record->id;
            $this->setState('username', $record->username);
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }
 
    public function getId()
    {
        return $this->_id;
    }
}
В модели User (стандартая модель)

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

 * @property integer $id
 * @property string $username
 * @property string $ip
 * @property string $role
В контроллере по умолчанию

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

	public function actionLogin()
	{
		if (Yii::app()->user->isGuest) {
		if (!defined('CRYPT_BLOWFISH')||!CRYPT_BLOWFISH)
			throw new CHttpException(500,"This application requires that PHP was compiled with Blowfish support for crypt().");

		$ip = $_SERVER['REMOTE_ADDR'];
		$model=new LoginForm;

		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		$this->render('login',array('model'=>$model));
		}
		else $this->redirect(array('number/index'));
	}
В LoginForm

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

	...
	public function authenticate($attribute)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->ip);
			if(!$this->_identity->authenticate())
				$this->addError('ip','Incorrect IP.');
		}
	}

	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->ip);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*1*1 : 0; // 1 hour
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}
	...
Ответить