My Google+ Profile

Thursday 6 September 2012

User Authentication using crypt (salt) encryption method in Yii

First of all you need to create user table model,view and controller for user authetication and authorization. And then you need to encrypt password using crypt() method at the time of creation of new user. You can convert password like this.

UserController.php

    public function actionCreate()
    {
        $model=new User;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
          
            $model->password = crypt($model->password);

            if($model->save())
                $this->redirect(array('view','id'=>$model->user_id));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

Note: crypt() function return different crypted string everytime. so you need to make following change to compare your password with crypted password in Yii.


UserIdentity.php


public $_id;
public function authenticate()
{
              $record=User::model()->findByAttributes(array('username'=>$this->username));
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($record->password!==crypt($this->password,$record->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->_id=$record->user_id;
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
        }
  
        public function getId()
        {
        return $this->_id;
        }
}

2 comments:

  1. thank you for this tutorial. it really helps me to start in yii.

    ReplyDelete