yii Call to undefined method in authenticate access rules section - php

We have integrated the yii authenticate acceess rules. In the login page, after submit the
form, it displays the following error message shows
Fatal error: Call to undefined method LoginForm::model() in D:\wamp\www\onlinetest\protected\components\UserIdentity.php on line 13
Here is the controller code
public function actionLogin()
{
$model=new LoginForm;
// 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->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
Here is the login form model
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe;
private $_identity;
public function tableName()
{
return 'tbl_login';
}
public function authenticate($attribute,$params)
{
if(!$this->hasErrors()) // we only want to authenticate when no input errors
{
$identity=new UserIdentity($this->username,$this->password);
$identity->authenticate();
switch($identity->errorCode)
{
case UserIdentity::ERROR_NONE:
Yii::app()->user->login($identity);
break;
case UserIdentity::ERROR_USERNAME_INVALID:
$this->addError('username','Username is incorrect.');
break;
default: // UserIdentity::ERROR_PASSWORD_INVALID
$this->addError('password','Password is incorrect.');
break;
}
}
}
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;
}
}
Here is the useridentity.php in components
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record=LoginForm::model()->findByAttributes(array('VarUser_type'=>$this->username)); // here I use Email as user name which comes from database
if($record===null)
{
$this->_id='user Null';
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if($record->E_PASSWORD!==$this->password) // here I compare db password with passwod field
{ $this->_id=$this->username;
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else
{
$this->_id=$record['VarUser_type'];
$this->setState('title', $record['VarUser_type']);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId() // override Id
{
return $this->_id;
}
}
How can I fix this issue? If you know help me

you can njot use
$record=LoginForm::model()->findByAttributes(array('VarUser_type'=>$this->username));
because LoginForm extends CFormModel
for database retrival it should extends CActiveRecord
see this
see this
your model should be like this
class Users extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #return Users the static model class
*/
private $_identity;
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(' password, user_name,' , 'required', 'on'=>'login' ),
array('user_id, last_name, first_name, address1, address2, city, pincode, state_id, country_id, phone, fax, email, created_date, updated_date, last_login, company_name, tour_id, password, user_name, last_login_from, gender, is_session_on, status, memo, cell, role_type_id, group_contract_template_id, group_policy_id, billing_contact, billing_phone, billing_address, billing_email, after_hours_phone', '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(
);
}
public function login( $id, $password = "" )
{
$this->_identity = new UserIdentity($username = $id ,$password);
$this->_identity->authenticate();
//Yii::app()->user->login($this->_identity,3600*24*30);
if(Yii::app()->user->login($this->_identity,0*0*0))
{
//echo $this->_identity->errorMessage;
return true;
}
else
{
Yii::app()->user->setState('error', $this->_identity->errorMessage);
return false;
}
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'user_id' => 'User',
'last_name' => 'Last Name',
'first_name' => 'First Name',
'address1' => 'Address1',
'email' => 'Email',
);
}
/**
* 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('user_id',$this->user_id,true);
$criteria->compare('last_name',$this->last_name,true);
$criteria->compare('first_name',$this->first_name,true);
$criteria->compare('email',$this->billing_address,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}

you don't have included the code for model method
public static function model($className=__CLASS__)
{
return parent::model($className);
}
in your model class

Your UserIdentity class method authenticate is incorrect.. Refer to the code below to see how.
public function authenticate()
{
$record=YourUserModel::model()->find(array(
'condition'=>'VarUser_type =:username',
'params'=>array(':username'=>$this->username)
));
if($record===null)
{
$this->_id='user Null';
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if($record->E_PASSWORD!==$this->password) // here I compare db password with passwod field
{ $this->_id=$this->username;
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else
{
$this->_id=$record['VarUser_type'];
$this->setState('title', $record['VarUser_type']);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}

Related

Laravel 7 - Redirecting different user roles to different view

The LoginController had this code before:
class LoginController extends Controller
{
public function showLoginForm(){
$roles = Role::all();
return view('auth.login', compact('roles'));
}
public function logout(Request $request){
Auth::logout();
$request->session()->flush();
return redirect('/');
}
public function login()
{
$credentials = $this->validate(request(),[
'email' => 'email|required|string',
'password' => 'required|string',
]);
if (Auth::attempt ($credentials)){//auth attemptdevuelve verdadero o falso en caso de que las credenciales correspondan o no
//Inician cambios RDAN
$user = Auth::user();
if($user->userRole() == 'admin') {
return redirect('main');
} else if($user->userRole() == 'externo') {
return redirect('es/user_form');
} else if($user->userRole() == 'profesor') {
return redirect('profesor_site');
} else if($user->userRole() == 'registrador') {
return redirect('select_lang');
} else {
return back()->withErrors(['email' => 'Incorrect user permissions'])
->withInput(request(['email']));
}
//Terminan cambios RDAN
}else{
return back()->withErrors(['email' => 'Incorrect user permissions'])
->withInput(request(['email'])); }
}
}
Then I changed it for:
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/main';//RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
In the model User I have this for the roles:
public function roles()
{
return $this->belongsToMany(Role::class,'assigned_roles');
}
public function isAdmin(){
return $this->hasRoles(['admin']);
}
public function hasRoles(array $roles)
{
return $this->roles->contains(fn($role, $key) => in_array($role->name, $roles));
}
public function userRole(){
return $this->role->nombre_rol;
}
With the new changes on the LoginController I have no problem with the login, but obviously only redirect to the main view. So, I want to add the redirect view depend on the role, but when I add the public function login() that it had before it returns an error with the function userRole() on the model User. The error is
ErrorException
Trying to get property 'nombre_rol' of non-object
http://localhost/Servescol2.0.2/public/login
You don't need to override the login method. The login method currently will make a call to the authenticated method to see if it returns true truthy value and then return that as the response. You can override the authenticated method and have it return your redirect based on your conditions.
protected function authenticated(Request $request, $user)
{
if ($user->hasRoles(['admin'])) {
return redirect('main');
}
...
}
The error is caused by trying to access an attribute/relationship which doesn't exist, which returns null:
$this->role
The User belongs to many Role so there are multiple roles not a single one.
You could have a method to check for a single role:
public function hasRole($role)
{
return $this->roles->contains('name', $role);
}
Then you could adjust your conditionals:
if ($user->hasRole('admin')) {
Or use the hasRoles method instead:
if ($user->hasRoles(['admin']) {

$model->validate() not shows error with out filling the form in yii

I have created login form in yii using authenticate functionality.
After submit the login form with out enter username and password, it directly goes to the redirect url.
It doesn't show the error message. I am not familiar in yii. So I couldn't find the solution for this.
Here is my controller code for login form
public function actionIndex()
{
$this->layout = 'layout10';
$model = new LoginForm;
//exit;
// 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($_POST['LoginForm']))
$url = Yii::app()->getBaseUrl()."/admin/product_name";
Yii::app()->getRequest()->redirect($url);
//$this->redirect(Yii::app()->user->returnUrl);
}
$this->render('index',array('model'=>$model));
}
Here is the model page for login
class LoginForm extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #return Users the static model class
*/
private $_identity;
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'tbl_user';
}
/**
* #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(' password, username,' , 'required', 'on'=>'login' ),
);
}
/**
* #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(
);
}
public function login( $id, $password = "" )
{
$this->_identity = new UserIdentity($username = $id ,$password);
$this->_identity->authenticate();
//Yii::app()->user->login($this->_identity,3600*24*30);
if(Yii::app()->user->login($this->_identity,0*0*0))
{
//echo $this->_identity->errorMessage;
return true;
}
else
{
Yii::app()->user->setState('error', $this->_identity->errorMessage);
return false;
}
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'username' => 'User',
'password' => 'Last Name',
);
}
/**
* 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,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('username',$this->username,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
Here is the useridentity in components
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record=LoginForm::model()->find(array(
'condition'=>'username =:username',
'params'=>array(':username'=>$this->username)
));
if($record===null)
{
$this->_id='user Null';
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if($record->E_PASSWORD!==$this->password) // here I compare db password with passwod field
{
$this->_id=$this->username;
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else
{
$this->_id=$record['username'];
$this->setState('title', $record['username']);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId() // override Id
{
return $this->_id;
}
}
Here is the view page for login
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>false,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<fieldset>
<div class="input-group input-group-lg">
<span class="input-group-addon"><i class="glyphicon glyphicon-user red"></i></span>
<?php echo $form->textField($model,'username',array('id'=>'example-username2','class'=>'form-control','placeholder'=>'Username')); ?>
</div><?php echo $form->error($model,'username'); ?>
<div class="clearfix"></div><br>
<div class="input-group input-group-lg">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock red"></i></span>
<?php echo $form->passwordField($model,'password',array('id'=>'example-username2','class'=>'form-control','placeholder'=>'Password')); ?>
</div><?php echo $form->error($model,'password'); ?>
<div class="clearfix"></div>
<div class="clearfix"></div>
<p class="center col-md-5">
<button type="submit" class="btn btn-primary">Login</button>
</p>
</fieldset>
<?php $this->endWidget(); ?>
Please tell How to validate the form in model. Now no error message displayed.
for watching errors also you can use:
var_dump($model->getErrors());
and next
$model->login($_POST['LoginForm']);
I think you don't need the pass POST variable because model already have this params
maybe you just change the login method like this:
public function login()
{
$this->_identity = new UserIdentity($this->id ,$this->password);
$this->_identity->authenticate();
//Yii::app()->user->login($this->_identity,3600*24*30);
if(Yii::app()->user->login($this->_identity,0*0*0))
{
//echo $this->_identity->errorMessage;
return true;
}
else
{
Yii::app()->user->setState('error', $this->_identity->errorMessage);
return false;
}
}

yii:how to remove error validate for update form

in my site if email is registered in my database I would add a error
$this->addError('email' ,'This Email already registered');
but in Update form I do not want see this error
What is a simple way to solve my problem?
this is my users model:
<?php
/**
* This is the model class for table "users".
class Users extends CActiveRecord
{
// public $captcha;
/**
* #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, email,password', 'required'),
array('roles_id', 'numerical', 'integerOnly'=>true),
array('username, password',
'length',
'max'=>255,
'min'=>4
),
array('email', 'comp_email'),
array('username', 'comp_username'),
array('DataCreated, LastUpdated', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, username, password, DataCreated, LastUpdated, roles_id', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'email'=>'Email',
'username' => 'Username',
'password' => 'Password',
'DataCreated' => 'Data Created',
'LastUpdated' => 'Last Updated',
'roles_id' => 'Roles',
);
}
public function search()
{
// #todo 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('DataCreated',$this->DataCreated,true);
$criteria->compare('LastUpdated',$this->LastUpdated,true);
$criteria->compare('roles_id',$this->roles_id);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return Users the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function comp_username($attributes , $params)
{
$username = Yii::app()->db->createCommand()
->select('username')
->from('users')
->queryAll();
$y = (count($username));
for ($x=0;$x<$y;$x++)
{
$usernameE[$x] = $username[$x]['username'];
}
foreach ($usernameE as $u)
{
if($this->username == $u)
{
$this->addError('username' ,'This Username already registered');
break;
}
}
}
public function comp_email($attributes , $params)
{
$email = Yii::app()->db->createCommand()
->select('email')
->from('users')
->queryAll();
$y = (count($email));
for ($x=0;$x<$y;$x++)
{
$emailE[$x] = $email[$x]['email'];
}
foreach ($emailE as $u)
{
if($this->email == $u)
{
$this->addError('email' ,'This Email already registered');
break;
}
}
}
public function getUsernameEmail($id)
{
$emailUsername = Yii::app()->db->createCommand()
->select('*')
->from('users')
->where('id=:id', array(':id'=>$id))
->queryAll();
return $emailUsername;
}
}
and this is my action Update in my controller:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Users']))
{
$model->attributes=$_POST['Users'];
$id=$model->id;
$useremail = Users::model()->getUsernameEmail($id);
$useremailX= $useremail[0]['username'];
$model->username=$useremailX;
$useremailX= $useremail[0]['email'];
$model->email=$useremailX;
$model->password= crypt($model->password,'salt');
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
You can achieve this by applying specific scenarios to your rules.
The Yii WIKI topic on the subject is a good reference.
In your rules, you can specify which scenarios to apply the rule to.
array('email', 'unique','message'=>'Email already exists!', 'on'=>'insert')
Please note that Yii automatically injects specific scenarios, depending on how the object is created.
insert
update
search
You can specify your own custom scenario.
$model = Customer::model()->findByPK($customerID);
$model->scenario = 'purchase';
this is how to validate, you can set error message to be empty.
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
//First parameter is your field name of table which has email value
array('email', 'email','message'=>"The email isn't correct"),
array('email', 'unique','message'=>'Email already exists!'),
);
}
https://stackoverflow.com/a/12778419/1727357
or you can make your own validator:
public function uniqueEmail($attribute, $params)
{
// Set $emailExist variable true or false by using your custom query on checking in database table if email exist or not.
// You can user $this->{$attribute} to get attribute value.
$emailExist = true;
if($emailExist)
{
//do what your want
$this->addError('email','Email already exists');
}
}
User this validation method in rules:
array('email', 'uniqueEmail','message'=>'Email already exists!'),

Complete Newbie at Laravel, wondering if I'm using models correctly

So I've got three models, "Incomplete", "User", and "Collaboration". They are related with foreign keys as such:
Collaboration->incomplete_id
incomplete_id->Incomplete
Incomplete->user_id
user_id->User
If I want to get the email of a user for a Collaboration model I have the following code
User::find(Incomplete::find($collab->incomplete_id)->user_id)->email);
I feel like this is wrong as I'm not joining any tables but I don't want to break out of mvc and call straight up SQL from the controller. Basically I'm curious how I could do this correctly.
Collaboration Model
class Collaboration extends Eloquent{
//Set the database to connect to as form d
protected $connection = 'formd';
//Set the table for the model to incomplets
protected $table = 'collaborations';
//Set the fillable columns
protected $fillable = array('incompid', 'link', 'shareFlag');
private $rules = array(
'link'=>'required|unique:collaborations|size:56',
'incompid'=>'required|integer'
);
private $errors;
public function validate($data)
{
// make a new validator object
$v = Validator::make($data, $this->rules);
// check for failure
if ($v->fails())
{
// set errors and return false
$this->errors = $v->errors();
return false;
}
// validation pass
return true;
}
public function errors()
{
return $this->errors;
}
public function getId(){
return $this->getKey();
}
public function incomplete(){
return $this->hasOne('Incomplete');
}
}
Incomplete Model
class Incomplete extends Eloquent{
//Set the database to connect to as form d
protected $connection = 'formd';
//Set the table for the model to incomplets
protected $table = 'incompletes';
//Set the fillable columns
protected $fillable = array('name', 'data', 'userid');
private $rules = array(
'name' => 'required|min:3',
'data' => 'required'
);
private $errors;
public function validate($data)
{
// make a new validator object
$v = Validator::make($data, $this->rules);
// check for failure
if ($v->fails())
{
// set errors and return false
$this->errors = $v->errors();
return false;
}
// validation pass
return true;
}
public function errors()
{
return $this->errors;
}
public function getId(){
return $this->getKey();
}
public function getData(){
return $this->data;
}
public function getName(){
return $this->name;
}
public function user(){
return $this->hasOne('User');
}
}
You can use Eloquents relations:
http://laravel.com/docs/eloquent#relationships
class Collaboration extends Eloquent {
public function incomplete()
{
return $this->hasOne('Incomplete', 'incomplete_id', 'id');
}
}
You can then get the data from the incomplete record by doing:
$collab->incomplete->user_id
In this case, use a relation on your models:
class Collaboration extends Eloquent {
public function incomplete()
{
return $this->belongsTo('Incomplete', 'incomplete_id');
}}
And
class Incomplete extends Eloquent {
public function user()
{
return $this->belongsTo('User', 'user_id');
}}
Then, do this:
Collaboration::find($id)->incomplete()->user()->email;
first of all you'll have to update parts of your model class
Class Collaboration extends Eloquent{
protected function incomplete(){
return $this->belongsTo('Incomplete');
}
}
Class Incomplete extends Eloquent{
protected function collaboration(){
return $this->hasOne('Collaboration');
}
protected function user(){
return $this->belongsTo('User');
}
}
Class User extends Eloquent(){
protected function incomplete(){
return $this->hasOne('Incomplete');
}
}
Then inorder to get what your want, here is the query
Collaboration::find($id)->incomplete()->user()->email;

simple user login form - yii framwork

I am trying to open a login form on my site. I have written code but some how it's not working.
The problem is that the login form does not return any error or mesage, it only redirects me to the login page.
Also, for some reason the checklogin function is not working.
controller/main:
public function actionLogin()
{
$model = new LoginForm;
$this->render('login',array('model'=>$model));
}
model/LoginForm:
class LoginForm extends CFormModel
{
public $email;
public $password;
private $_identity;
public function rules()
{
return array(
array('email, password', 'required', 'message' => 'error'),
array('email', 'email', 'allowEmpty' => false, 'checkMX' => true, 'message' => 'error'),
array('password', 'authenticate')
);
}
public function authenticate($attribute,$params)
{
$this->_identity = Account::model()->checkLogin($this->email, $this->password);
if(!$this->_identity)
$this->addError('password', 'error');
}
}
model/account:
public static function model()
{
return parent::model(__CLASS__);
}
public function tableName()
{
return 'table';
}
public function primaryKey()
{
return 'id';
}
public function checkLogin($email, md5($password))
{
$user = $this->findByAttributes(array('email' => $email, 'password' => $password));
if($user===null)
{
return false;
}
return false;
views/main/login:
<?php $form=$this->beginWidget('CActiveForm', array('action' => Yii::app()->createUrl('login'))); ?>
<table>
<tr><?php echo $form->errorSummary($model); ?></tr>
<tr> <?php echo $form->emailField($model,'email'); ?></tr>
<tr><?php echo $form->passwordField($model,'password'); ?></tr>
<tr><?php echo CHtml::submitButton('Login'); ?></tr>
</table>
<?php $this->endWidget(); ?>
To implement your authentication you must follow the steps below:
First in your action:
public function actionLogin() {
$model = new LoginForm();
if (isset($_POST['LoginForm'])) {
if (CActiveForm::validate($model) && $model->validate() && $model->login()) {
// Authentication DONE
} else {
//TRY TO GET ERRORS
}
}
}
In your model add the login function:
public function login() {
/*
* if identity property had no value, here we initialize
* identity property
*/
if ($this->identity === null) {
$this->identity = new UserIdentity($this->username, $this->password);
//authenticating
$this->identity->authenticate();
} else {
/*
* if error code was NONE, it means user has been successfully
* authenticated.
*/
if ($this->identity->errorCode === UserIdentity::ERROR_NONE) {
Yii::app()->user->login($this->identity);
return true;
}
}
}
and in your model's authentication method:
public function authenticate() {
//if validation was done and we had no error while validating
if (!$this->hasErrors()) {
//new instance of identity class
$this->identity = new UserIdentity($this->username, $this->password);
if (!$this->identity->authenticate()) {
$this->addError('password', Yii::t('app', 'Invalid Username or Password'));
}
}
}
Then you need to add UserIdentity Class (Put this class in your components directory)
class UserIdentity extends CUserIdentity {
private $_id;
private $_username;
public function authenticate() {
$record = Account::model()->findByAttributes(array(
'username' => $this->username
));
if ($record === null) {
//adds error to user
$this->errorCode = self::ERROR_USERNAME_INVALID;
//authentication failed
return false;
} else if (!CPasswordHelper::verifyPassword($this->password, $record->password)) {
$this->errorCode = self::ERROR_PASSWORD_INVALID;
return false;
} else {
/*
* no error
* user information[username and password are valid]
*/
$this->errorCode = self::ERROR_NONE;
//user's id whitch will be accessible through Yii::app()->user->id
$this->_id = $record->id;
//user's username whitch will be accessible through Yii::app()->user->name
$this->_username = $record->username;
//success
return true;
}
}
/**
* Overriding CUserIdentity's getId() method
* #access public
* #return integer user id
*/
public function getId() {
return $this->_id;
}
/**
* Overriding CUserIdentity's getName() method
* #access public
* #return string username
*/
public function getName() {
return $this->_username;
}
Change checklogin function as given below and try again to fix this.
public function checkLogin($email, md5($password))
{
$user = $this->model()->findByAttributes(array('email' => $email, 'password' => $password));
if($user===null)
{
return false;
}
return false;
}
If you are trying to implement the login functionality separately, then you are missing the whole logic to register the user's auth details using the Yii::app()->login()dependent on the CUserIdentity class.
Master this link -> http://www.yiiframework.com/doc/guide/1.1/en/topics.auth and proceed for post authentication.

Categories