Авторизация И Регистарция

Подскажите пожалуйста нет не у кого исходников к примеру создание регистрации и авторизации

Аутентификация и авторизация который на этом сайте разбирается

Я все перерыл не могу найти что не так в базу пользователь записывается а авторизоваться не могу и не знаю что делать

Объясняют люди которые считают все это простыми вещами а для меня темный лес.

Зацепиться не могу не за что.

Пожалуйста

Так в примере приложения есть же всё это.

Расскажите что уже сделано, какая БД, как называется таблица в которой пользователи хранятся.

И еще присморитесь к расширению http://www.yiiframework.com/extension/yii-user/

Я попробовал уже сто раз и к приложению присматривался но приложение не записывает в базу данные о пользователе.

Я знаю что я что то не то делаю а что конкретно не знаю знаний не хватает.

для этого то и нужны исходники именно как сделано на сайте именно регистрация

Я не пойму что не так делаю с классом UserIdentity

А все остальное нормально идет модели создаются в базу записывается

А авторизацию не проходит

И все.

Если надо я сейчас по шагам создам новый сайт и выложу.

Спасибо

Вот код не понимаю что не правильно

model user


<?php


/**

 * This is the model class for table "{{users}}".

 *

 * The followings are the available columns in table '{{users}}':

 * @property integer $id

 * @property string $username

 * @property string $password

 * @property string $email

 * @property string $activkey

 * @property string $create_at

 * @property string $lastvisit_at

 * @property integer $superuser

 * @property integer $status

 *

 * The followings are the available model relations:

 * @property Profiles $profiles

 */

class User extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return User the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return '{{users}}';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('username, password, email, create_at', 'required'),

			array('superuser, status', 'numerical', 'integerOnly'=>true),

			array('username', 'length', 'max'=>20),

			array('password, email, activkey', 'length', 'max'=>128),

			array('lastvisit_at', 'safe'),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, username, password, email, activkey, create_at, lastvisit_at, superuser, status', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'profiles' => array(self::HAS_ONE, 'Profiles', 'user_id'),

		);

	}

  public function validatePassword($password)

    {

        return crypt($password,$this->password)===$this->password;

    }

 

    public function hashPassword($password)

    {

        return crypt($password, $this->generateSalt());

    }

	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'username' => 'Username',

			'password' => 'Password',

			'email' => 'Email',

			'activkey' => 'Activkey',

			'create_at' => 'Create At',

			'lastvisit_at' => 'Lastvisit At',

			'superuser' => 'Superuser',

			'status' => 'Status',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id',$this->id);

		$criteria->compare('username',$this->username,true);

		$criteria->compare('password',$this->password,true);

		$criteria->compare('email',$this->email,true);

		$criteria->compare('activkey',$this->activkey,true);

		$criteria->compare('create_at',$this->create_at,true);

		$criteria->compare('lastvisit_at',$this->lastvisit_at,true);

		$criteria->compare('superuser',$this->superuser);

		$criteria->compare('status',$this->status);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

}

UserIdentity


<?php

class UserIdentity extends CUserIdentity

{

    private $_id;

 

    public function authenticate()

    {

        $username=strtolower($this->username);

        $user=User::model()->find('LOWER(username)=?',array($username));

        if($user===null)

            $this->errorCode=self::ERROR_USERNAME_INVALID;

        else if(!$user->validatePassword($this->password))

            $this->errorCode=self::ERROR_PASSWORD_INVALID;

        else

        {

            $this->_id=$user->id;

            $this->username=$user->username;

            $this->errorCode=self::ERROR_NONE;

        }

        return $this->errorCode==self::ERROR_NONE;

    }

 

    public function getId()

    {

        return $this->_id;

    }

}

Login Form


<?php


/**

 * LoginForm class.

 * LoginForm is the data structure for keeping

 * user login form data. It is used by the 'login' action of 'SiteController'.

 */

class LoginForm extends CFormModel

{

	public $username;

	public $password;

	public $rememberMe;


	private $_identity;


	/**

	 * Declares the validation rules.

	 * The rules state that username and password are required,

	 * and password needs to be authenticated.

	 */

	public function rules()

	{

		return array(

			// username and password are required

			array('username, password', 'required'),

			// rememberMe needs to be a boolean

			array('rememberMe', 'boolean'),

			// password needs to be authenticated

			array('password', 'authenticate'),

		);

	}


	/**

	 * Declares attribute labels.

	 */

	public function attributeLabels()

	{

		return array(

			'rememberMe'=>'Remember me next time',

		);

	}


	/**

	 * Authenticates the password.

	 * This is the 'authenticate' validator as declared in rules().

	 */

	public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			if(!$this->_identity->authenticate())

                            switch($this->_identity->errorCode)

{

                            case UserIdentity::ERROR_NONE:

                            Yii::app()->user->login($this->_identity);

                                    break;

				$this->addError('password','Incorrect username or password.');

		}

                }

	}


	/**

	 * Logs in the user using the given username and password in the model.

	 * @return boolean whether login is successful

	 */

	public function login()

	{

		if($this->_identity===null)

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			$this->_identity->authenticate();

		}

		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)

		{

			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

			Yii::app()->user->login($this->_identity,$duration);

			return true;

		}

		else

			return false;

	}

}



Скажите что не так а то сверлит в мозгах покоя не дает

На первый взгляд должно быть нормально.

Попробуйте как-то так:




LoginController

class LoginController extends Controller

{

	public $defaultAction = 'login';


	/**

	 * Displays the login page

	 */

	public function actionLogin()

	{

		if (Yii::app()->user->isGuest) {

			$model=new UserLogin;

			// collect user input data

		

			if(isset($_POST['UserLogin']))

			{

				$model->attributes=$_POST['UserLogin'];

				// validate user input and redirect to previous page if valid

				if($model->validate()) {

					$this->lastViset();

					if (strpos(Yii::app()->user->returnUrl,'/index.php')!==false)

						$this->redirect(Yii::app()->controller->module->returnUrl);

					else

						$this->redirect('/user/general/index');//Yii::app()->user->returnUrl

				}

			}

			// display the login form

			$this->render('/user/login',array('model'=>$model));

		} else

			$this->redirect(Yii::app()->controller->module->returnUrl);

	}

    private function lastViset() {

		$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);

		$lastVisit->lastvisit = time();

		$lastVisit->save();

	}


}






<?php


/**

 * LoginForm class.

 * LoginForm is the data structure for keeping

 * user login form data. It is used by the 'login' action of 'SiteController'.

 */

class UserLogin extends CFormModel

{

	public $email;

	public $password;

	public $rememberMe;

	/**

	 * Declares the validation rules.

	 * The rules state that username and password are required,

	 * and password needs to be authenticated.

	 */

	public function rules()

	{

		return array(

			array('email, password', 'required'),

			array('email', 'email'),

			array('password', 'authenticate'),

		);

	}

	/**

	 * Declares attribute labels.

	 */

	public function attributeLabels()

	{

		return array(

			'rememberMe'=>UserModule::t("Remember me next time"),

			'email'=>UserModule::t("Email"),

			'password'=>UserModule::t("Password"),

		);

	}

	/**

	 * Authenticates the password.

	 * This is the 'authenticate' validator as declared in rules().

	 */

	public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())  // we only want to authenticate when no input errors

		{

			$identity=new UserIdentity($this->email,$this->password);

			$identity->authenticate();

			switch($identity->errorCode)

			{

				case UserIdentity::ERROR_NONE:

					$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

					Yii::app()->user->login($identity,$duration);

					break;

				case UserIdentity::ERROR_EMAIL_INVALID:

					$this->addError("email",UserModule::t("Email is incorrect."));

					break;

				case UserIdentity::ERROR_USERNAME_INVALID:

					$this->addError("email",UserModule::t("Email is incorrect."));

					break;

				case UserIdentity::ERROR_STATUS_NOTACTIV:

					$this->addError("status",UserModule::t("Your account is not active."));

					break;

				case UserIdentity::ERROR_STATUS_BAN:

					$this->addError("status",UserModule::t("You account is blocked."));

					break;

				case UserIdentity::ERROR_PASSWORD_INVALID:

					$this->addError("password",UserModule::t("Password is incorrect."));

					break;

			}

		}

	}

}




Ну и наконец


/**

 * UserIdentity represents the data needed to identity a user.

 * It contains the authentication method that checks if the provided

 * data can identity the user.

 */

class UserIdentity extends CUserIdentity

{

	private $_id;

	const ERROR_EMAIL_INVALID=3;

	const ERROR_STATUS_NOTACTIV=4;

	const ERROR_STATUS_BAN=5;

	/**

	 * Authenticates a user.

	

	 * @return boolean whether authentication succeeds.

	 */

	public function authenticate()

	{

		if (strpos($this->username,"@")) {

			$user=User::model()->notsafe()->findByAttributes(array('email'=>$this->username));

		}

		if($user===null)

			if (strpos($this->username,"@")) {

				$this->errorCode=self::ERROR_EMAIL_INVALID;

			}

		else if(Yii::app()->getModule('user')->encrypting($this->password)!==$user->password)

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		else if($user->status==0&&Yii::app()->getModule('user')->loginNotActiv==false)

			$this->errorCode=self::ERROR_STATUS_NOTACTIV;

		else if($user->status==-1)

			$this->errorCode=self::ERROR_STATUS_BAN;

		else {

			$this->_id=$user->id;

			$this->username=$user->email;

			$this->errorCode=self::ERROR_NONE;

		}

		return !$this->errorCode;

	}

    /**

    * @return integer the ID of the user record

    */

	public function getId()

	{

		return $this->_id;

	}

}

Спасибо буду разбираться