Hi i am new in yii and below is my UserIdentiy function Please let me know how can i add the remember me functionality
public function authenticate()
{
$users = array();
if ($this->usertype == "registration")
{
$users = Login::model()->findByAttributes(array('email' => $this->username));
$users = $users->attributes;
}
if (empty($users)) $this->errorCode = self::ERROR_USERNAME_INVALID;
elseif (!empty($users['password']) && $users['password'] !== md5($this->password))
$this->errorCode = self::ERROR_PASSWORD_INVALID;
elseif (!empty($users['status']) && $users['status'] !== 1)
$this->errorCode = self::STATUS_NOT_ACTIVE;
else
{
$this->_id = $users->id;
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
In protected\config\main.php configuration array is present in that array go to component index. Inside of that user array has associative indexed value 'allowAutoLogin' must have the boolean value true
So it should look like this
'components' => array(
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => true,
),
...
And You have to use the following property along with login method given below you can achieve remember me easily.
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe;
private $_identity;
login method should be like this in Login model class
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;
}
And this the core code to remember function
Yii::app()->user->login($this->_identity,$duration);
Here
/**
* LoginForm class.
* LoginForm is the data structure for keeping
* user login form data. It is used by the 'login' action of 'SiteController'.
*/
class LoginFormUser extends CFormModel {
public $Username;
public $password;
public $rememberMe;
private $_identity;
// public $verifyCode;
public $verifyCode;
/**
* 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', 'skipOnError' => true),
// array('verifyCode', 'CaptchaExtendedValidator', 'allowEmpty'=>!CCaptcha::checkRequirements()),
// array('verifyCode', 'required'),
// array('verifyCode', 'application.extensions.yiiReCaptcha.ReCaptchaValidator'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels() {
return array(
'rememberMe' => 'Remember me next time',
'Username' => 'User name',
'password' => 'Password',
// 'verifyCode'=> 'verify Code',
);
}
/**
* 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);
$dataAuthenticate = $this->_identity->authenticate();
if($dataAuthenticate == 1)
$this->addError('Username','username is invalid');
elseif($dataAuthenticate == 2)
$this->addError('password','password is invalid');
elseif($dataAuthenticate === 'lock')
$this->addError('Username', 'Your account has been locked for violating the policy');
elseif($dataAuthenticate == 3)
$this->addError('Username', 'Your account have been locked login in 15 minutes!');
}
}
/**
* 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
// if($this->rememberMe == true){
// $duration=3600*24*30; // 30 days
// }else {
// $duration = 0;
// }
Yii::app()->user->login($this->_identity,$duration);
// $get_cookie_first = Yii::app()->request->cookies['loginCookie']->value;
// $cookie = new CHttpCookie('loginCookie', $get_cookie_first);
// $cookie->expire = time() + $duration;
// Yii::app()->request->cookies['loginCookie'] = $cookie;
return true;
}
else
return false;
}
}
Related
I have developed a website which have single login access. I want to give different login access to different members. I tried a sample project as Mutiuser in which there are multiple login, but in this I'm unable to integrate my project. Its showing 404 error after login, in url
http://localhost/Multi_user/login/validate
i have added My_Controller.php in application/core folder
After this im gettin 404 page not found
My_Controller.php
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
$this->load->library('session');
if($this->session->userdata('logged_in') === true) {
redirect('../dashboard');
}
}
public function isNotLoggedIn()
{
$this->load->library('session');
if($this->session->userdata('logged_in') !== true) {
redirect('../../');
}
}
}
this is login.php present application/controllers folder
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('login/login_model');
}
/*
*Showing Login page here
*/
function index()
{
$this->load->view('login/login');
}
/**
* check the username and the password with the database
* #return void
*/
function validate()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$is_valid = $this->login_model->validate($username, $password);
if($is_valid)/*If valid username and password set */
{
$get_id = $this->login_model->get_id($username, $password);
foreach($get_id as $val)
{
$id=$val->id;
$name = $val->username;
$password = $val->password;
$type=$val->type;
if($type=='admin')
{
$data = array(
'admin_name' =>$name,
'admin_password' => $password,
'admin_type'=>$type,
'admin_id'=>$id,
'is_logged_in' => true
);
$this->session->set_userdata($data); /*Here setting the Admin datas in session */
redirect('admin/dashboard');
}
if($type=='staff')
{
$data = array(
'staff_name' =>$name,
'staff_password' =>$password,
'staff_type'=>$type,
'staff_id'=>$id,
'staff_is_logged_in' => true
);
$this->session->set_userdata($data); /*Here setting the staff datas values in session */
redirect('staff/dashboard');
}
if($type=='student')
{
$data = array(
'admin_name' =>$name,
'admin_password' => $password,
'admin_type'=>$type,
'admin_id'=>$id,
'is_logged_in' => true
);
$this->session->set_userdata($data); /*Here setting the Admin datas in session */
redirect('student/dashboard');
}
}
}
else // incorrect username or password
{
$this->session->set_flashdata('msg1', 'Username or Password Incorrect!');
redirect('login');
}
}
/**
* Unset the session, and logout the user.
* #return void
*/
public function admin_logout()
{
$array_items = array(
'admin_name',
'admin_password',
'admin_type',
'admin_id',
'is_logged_in',
);
$this->session->unset_userdata($array_items);
$this->session->set_flashdata('msg', 'Admin Signed Out Now!');
redirect('login');
}
public function staff_logout()
{
$array_items = array(
'staff_name',
'staff_password' ,
'staff_type',
'staff_id',
'staff_is_logged_in'
);
$this->session->unset_userdata($array_items);
$this->session->set_flashdata('msg', 'Staff Signed Out Now!');
redirect('login');
}
Public function next_demo()
{
$this->load->view('next_demo');
}
}
Always there is two way to get the solution forward and backward process.
In Forward Process: Create a replica of your sample project step by step, it will help you to debug your issue.
Backward Process: Just remove all unwanted code to get attention on your desired code.
Previously, I was not using $model->save() function for inserting or updating any data. I was simply using createCommand() to execute query and it was working successfully. But, my team members asked me to avoid createCommand() and use $model->save();
Now, I started cleaning my code and problem is $model->save(); not working for me. I don't know where i did mistake.
UsersController.php (Controller)
<?php
namespace app\modules\users\controllers;
use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use app\modules\users\models\Users;
use app\controllers\CommonController;
class UsersController extends CommonController
{
.
.
public function actionRegister() {
$model = new Users();
// For Ajax Email Exist Validation
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post())) {
$post = Yii::$app->request->post('Users');
$CheckExistingUser = $model->findOne(['email' => $post['email']]);
// Ok. Email Doesn't Exist
if(!$CheckExistingUser) {
$auth_key = $model->getConfirmationLink();
$password = md5($post['password']);
$registration_ip = Yii::$app->getRequest()->getUserIP();
$created_at = date('Y-m-d h:i:s');
$model->auth_key = $auth_key;
$model->password = $password;
$model->registration_ip = $registration_ip;
$model->created_at = $created_at;
if($model->save()) {
print_r("asd");
}
}
}
}
.
.
}
Everything OK in this except $model->save(); Not printing 'asd' as i echoed it.
And, if i write
else if ($model->load(Yii::$app->request->post() && $model->validate()) {
}
It's not entering to this if condition.
And, if i write
if($model->save(false)) {
print_r("asd");
}
It insert NULL to all columns and print 'asd'
Users.php (model)
<?php
namespace app\modules\users\models;
use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use app\modules\users\models\UserType;
class Users extends ActiveRecord implements IdentityInterface
{
public $id;
public $first_name;
public $last_name;
public $email;
public $password;
public $rememberMe;
public $confirm_password;
public $user_type;
public $company_name;
public $status;
public $auth_key;
public $confirmed_at;
public $registration_ip;
public $verify_code;
public $created_at;
public $updated_at;
public $_user = false;
public static function tableName() {
return 'users';
}
public function rules() {
return [
//First Name
'FirstNameLength' => ['first_name', 'string', 'min' => 3, 'max' => 255],
'FirstNameTrim' => ['first_name', 'filter', 'filter' => 'trim'],
'FirstNameRequired' => ['first_name', 'required'],
//Last Name
'LastNameLength' => ['last_name', 'string', 'min' => 3, 'max' => 255],
'LastNameTrim' => ['last_name', 'filter', 'filter' => 'trim'],
'LastNameRequired' => ['last_name', 'required'],
//Email ID
'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
'emailRequired' => ['email', 'required'],
'emailPattern' => ['email', 'email'],
'emailUnique' => ['email', 'unique', 'message' => 'Email already exists!'],
//Password
'passwordRequired' => ['password', 'required'],
'passwordLength' => ['password', 'string', 'min' => 6],
//Confirm Password
'ConfirmPasswordRequired' => ['confirm_password', 'required'],
'ConfirmPasswordLength' => ['confirm_password', 'string', 'min' => 6],
['confirm_password', 'compare', 'compareAttribute' => 'password'],
//Admin Type
['user_type', 'required'],
//company_name
['company_name', 'required', 'when' => function($model) {
return ($model->user_type == 2 ? true : false);
}, 'whenClient' => "function (attribute, value) {
return $('input[type=\"radio\"][name=\"Users[user_type]\"]:checked').val() == 2;
}"], #'enableClientValidation' => false
//Captcha
['verify_code', 'captcha'],
[['auth_key','registration_ip','created_at'],'safe']
];
}
public function attributeLabels() {
return [
'id' => 'ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email',
'password' => 'Password',
'user_type' => 'User Type',
'company_name' => 'Company Name',
'status' => 'Status',
'auth_key' => 'Auth Key',
'confirmed_at' => 'Confirmed At',
'registration_ip' => 'Registration Ip',
'confirm_id' => 'Confirm ID',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'verify_code' => 'Verification Code',
];
}
//custom methods
public static function findIdentity($id) {
return static::findOne($id);
}
public static function instantiate($row) {
return new static($row);
}
public static function findIdentityByAccessToken($token, $type = null) {
throw new NotSupportedException('Method "' . __CLASS__ . '::' . __METHOD__ . '" is not implemented.');
}
public function getId() {
return $this->id;
}
public function getAuthKey() {
return $this->auth_key;
}
public function validateAuthKey($authKey) {
return $this->auth_key === $auth_key;
}
public function validatePassword($password) {
return $this->password === $password;
}
public function getFirstName() {
return $this->first_name;
}
public function getLastName() {
return $this->last_name;
}
public function getEmail() {
return $this->email;
}
public function getCompanyName() {
return $this->company_name;
}
public function getUserType() {
return $this->user_type;
}
public function getStatus() {
return $this->status;
}
public function getUserTypeValue() {
$UserType = $this->user_type;
$UserTypeValue = UserType::find()->select(['type'])->where(['id' => $UserType])->one();
return $UserTypeValue['type'];
}
public function getCreatedAtDate() {
$CreatedAtDate = $this->created_at;
$CreatedAtDate = date('d-m-Y h:i:s A', strtotime($CreatedAtDate));
return $CreatedAtDate;
}
public function getLastUpdatedDate() {
$UpdatedDate = $this->updated_at;
if ($UpdatedDate != 0) {
$UpdatedDate = date('d-m-Y h:i:s A', strtotime($UpdatedDate));
return $UpdatedDate;
} else {
return '';
}
}
public function register() {
if ($this->validate()) {
return true;
}
return false;
}
public static function findByEmailAndPassword($email, $password) {
$password = md5($password);
$model = Yii::$app->db->createCommand("SELECT * FROM users WHERE email ='{$email}' AND password='{$password}' AND status=1");
$users = $model->queryOne();
if (!empty($users)) {
return new Users($users);
} else {
return false;
}
}
public static function getConfirmationLink() {
$characters = 'abcedefghijklmnopqrstuvwxyzzyxwvutsrqponmlk';
$confirmLinkID = '';
for ($i = 0; $i < 10; $i++) {
$confirmLinkID .= $characters[rand(0, strlen($characters) - 1)];
}
return $confirmLinkID = md5($confirmLinkID);
}
}
Any help is appreciable. Please Help me.
It could be a problem related with your validation rules.
Try, as a test, to save the model without any validation in this way:
$model->save(false);
If the model is saved you have conflict with your validation rules. Try selectively removing your validation rule(s) to find the validation conflict.
If you have redefined the value present in active record you don't assign the value to the var for db but for this new var and then are not save.
Try removing the duplicated var.. (only the vars non mapped to db should be declared here.)
I guess $model->load() returns false, call $model->errors to see model's error.
$model->load();
$model->validate();
var_dump($model->errors);
Check model saving error like this :
if ($model->save()) {
} else {
echo "MODEL NOT SAVED";
print_r($model->getAttributes());
print_r($model->getErrors());
exit;
}
As #scaisEdge suggest, try removing all table related field in your Users class
class Users extends ActiveRecord implements IdentityInterface
{
/* removed because this properties is related in a table's field
public $first_name;
public $last_name;
public $email;
public $password;
public $user_type;
public $company_name;
public $status;
public $auth_key;
public $confirmed_at;
public $registration_ip;
public $verify_code;
public $created_at;
public $updated_at;
public $user_type;
public $company_name;
public $status;
public $auth_key;
public $confirmed_at;
public $registration_ip;
public $verify_code;
public $created_at;
public $updated_at;
*/
// this is properties that not related to users table
public $rememberMe;
public $confirm_password;
public $_user = false;
public static function tableName() {
return 'users';
}
/* ........... */
}
The other solution mentioned $model->save(false);. That is just a temporary workaround, and you should still find the actual reason why the save functionality is not working.
Here are additional steps to help diagnose the actual issue:
check that _form input field has the proper name, and
check that if you have added any dropdown functionality, then check whether it's working properly or not
And there maybe another reason of not saving model - you have property of your Users class and before saving from form its reset to NULL.
So, if you set $model->saveAttributes('favorite_book'=>$model->favorite_book), but at that time you declared in class Users public $favorite_book - you will get this field empty in DB.
You are doing all stuff correctly. I think you must add one line for confirm password validation
if(!$CheckExistingUser) {
$auth_key = $model->getConfirmationLink();
$password = md5($post['password']);
$registration_ip = Yii::$app->getRequest()->getUserIP();
$created_at = date('Y-m-d h:i:s');
$model->auth_key = $auth_key;
$model->password = $password;
$model->confirm_password= md5($post["confirm_password"]); /// add this line
$model->registration_ip = $registration_ip;
$model->created_at = $created_at;
And Also after this condition check model attributes and error like this :
if($model->save()) {
print_r("asd");
}else{
var_dump($model);exit;}
Try this:
$model->save(false);
and if thats working, check your model rules() and your form rules() if its
having the same rules. usually the cause is the required fields in your table.
if your column type in your table is "integer" and your data is "string" you may see tis error.You should check your data type and try again.
I suppose that your column type is integer, you should write the following code:
$model->created_at=time();//1499722038
$model->save();
but your column type is string, you should write the following code:
$model->created_at=date('d/m/Y');//11/07/2017
$model->save();
in your model i found First name , last name , email , password is required fields and in your controller you are updating or saving only
$model->auth_key = $auth_key;
$model->password = $password;
$model->confirm_password= md5($post["confirm_password"]); /// add this line
$model->registration_ip = $registration_ip;
$model->created_at = $created_at;
but first name and last name and email id are required so it will throw validation error , to check this error use
$model->load();
$model->validate();
var_dump($model->errors);
it will show you the error . correct that errors then model will get save.
you can solve that error using Scenario or
$model->saveAttributes('favorite_book'=>$model->favorite_book,'favorite_movie'=>$model->favorite_movie);
I hope it will help you.
Hi i'm quite new to yii framework, currently trying to establish a login through database authentication. but while im trying to log in i get this error saying
Please fix the following input errors:
Password is incorrect.
but when i check the database table im typing the correct password.
can anybody help me out if this
Heres the Controller
<?php
class SiteController extends Controller
{
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
'page'=>array(
'class'=>'CViewAction',
),
);
}
public function actionIndex()
{
$this->render('index');
}
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
$headers="From: $name <{$model->email}>\r\n".
"Reply-To: {$model->email}\r\n".
"MIME-Version: 1.0\r\n".
"Content-Type: text/plain; charset=UTF-8";
mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
public function actionLogin()
{
$form=new LoginForm;
if(isset($_POST['LoginForm']))
{
$form->attributes=$_POST['LoginForm'];
if($form->validate() && $form->login()) $this->redirect(Yii::app()->user->returnUrl);
}
$this->render('login',array('form'=>$form));
}
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
herers the model
<?php
class LoginForm extends CFormModel
{
public $email;
public $password;
private $_identity;
public function rules()
{
return array(
array('email, password', 'required'),
array('email', 'email'),
array('password', 'authenticate'),
);
}
public function attributeLabels()
{
return array('email'=>'Email Address');
}
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:
Yii::app()->user->login($identity);
break;
case UserIdentity::ERROR_USERNAME_INVALID:
$this->addError('email','Email address 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 the view
<?php
/* #var $this SiteController */
/* #var $model LoginForm */
/* #var $form CActiveForm */
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<h1>Login</h1>
<p>Please fill out the following form with your login credentials:</p>
<div class="form">
<?php $myWidget=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div>
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($form); ?>
<div>
<?php echo CHtml::activeLabel($form,'email'); ?>
<?php echo CHtml::activeTextField($form,'email') ?>
</div>
<div>
<?php echo CHtml::activeLabel($form,'password'); ?>
<?php echo CHtml::activePasswordField($form,'password') ?>
</div>
<div>
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php echo CHtml::endForm(); ?>
endWidget(); ?>
You have to write your authentication logic inside UserIdentity class not in LoginForm model.
LoginForm model ex:-
public function authenticate($attribute, $params) {
if (!$this->hasErrors()) {
$this->_identity = new UserIdentity($this->email, $this->password);
if (!$this->_identity->authenticate())
$this->addError('password', 'Incorrect username or password.');
}
}
public function login() {
if ($this->_identity === null) {
$this->_identity = new UserIdentity($this->email, $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;
}
For database authentication you must have to add your authetication logic inside authenticate function using components\UserIdentity.php
public function authenticate() {
Yii::app()->getModule('auth')->getModule('user'); #import your module.
$record = User::model()
->findByAttributes(array('email' => CHtml::encode($this->email))); #database call
if ($record === null)
$this->errorCode = self::ERROR_USERNAME_INVALID;
#else if ($record->password !== crypt($this->password, $record->password))
else if ($record->password !== $this->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else {
$this->_uid = $record->user_id;
$this->setState('title', $record->user_name);
$this->setState('uid', $this->_uid);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
If you have role based login then you have to add WebUser class in config/main.php.
components' => array(
'user' => array(
// enable cookie-based authentication
'class' => 'WebUser',
'allowAutoLogin' => true,
'loginUrl'=>array('/site/login'),
'returnUrl'=>array('/site/index'),
),
}
For role based assess check you have to write components\WebUser.php Class -
class WebUser extends CWebUser {
public function checkAccess($operation, $params = array()) {
if (empty($this->id)) {
// Not identified => no rights
return false;
}
$role = $this->getState("roles");
if ($role === '3') {
return true; // super admin role has access to everything
}else if ($role === '1') {
return true; // admin(manager) role has access to everything
}
// allow access if the operation request is the current user's role
return ($operation === $role);
}
}
For more information check Authentication and Authorization
In common/models/User.php
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE,
self::STATUS_INACTIVE, self::STATUS_DELETED]],
];
}
In this method, set the default 'value'=>self::STATUS_ACTIVE
your problem will be solved. I also had the same issue. After changing the value to Active, it worked, because the default value it is setting is 9 and the database considers it an inactive entry that's why it is shoeing incorrect id or password. I hope this helps.
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;
}
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.