class UserIdentity extends CUserIdentity
{
const ERROR_USERNAME_INACTIVE=67;
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 if($user->active == 0)
$this->errorCode=self::ERROR_USERNAME_INACTIVE;
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;
}
}
However, on my view it returns Incorrect username or password instead of ERROR_USERNAME_INACTIVE message, what should i do to rectify this error?
in your LoginForm model in auuthenticate function you need to add error based on the error_code..
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new UserIdentity($this->email,$this->password);
if(!$this->_identity->authenticate()) {
if($this->_identity->errorCode === UserIdentity::ERROR_USERNAME_INACTIVE)
$this->addError('username','My custom error');
else
$this->addError('password','Incorrect email or password.');
}
}
}
Related
I keep on getting this error in my codeigniter micro app restful api. When I post an item only the first letter is get saved with status code 400 being displayed.
here is my model file:
class Cities_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function save($city)
{
$this->db->set($this->setCity($city, null))->insert('cities');
if ($this->db->affected_rows() > 0) {
return $this->db->insert_id;
}
return null;
}
public function update($id, $city)
{
$this->db->set($this->setCity($city))->where('id')->update('cities');
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array(
'id' => $city['id'],
'name' => $city['name']
);
}
}
As you can see setCity function treat $city variable as array. So you need to pass array to setCity function.
class Cities_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function save($city)
{
$this->db->insert('cities',$this->setCity(array('name'=>$city,'id'=> null)));
if ($this->db->affected_rows() > 0) {
return $this->db->insert_id();
}
return null;
}
public function update($id, $city)
{
$this->db->where('id',$id)->update('cities',$this->setCity(array('name'=>$city,'id'=> $id)));
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array(
'id' => $city['id'],
'name' => $city['name']
);
}
}
another thing is, Codeignitor having method insert_id() to know last insert id.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
class Cities extends REST_Controller{
public function __construct() {
parent::__construct();
$this->load->model('cities_model');
}
public function index_get(){
$cities=$this->cities_model->get();
if(!is_null($cities))
{
$this->response(array('response'=>$cities),200);
}
else
{
$this->response(array('error'=>'cities cannot be found...'),404);
}
}
public function find_get($id){
if(!$id)
{
$this->respose(null,400);
}
$cit=$this->cities_model->get($id);
if(!is_null($cit))
{
$this->response(array('response'=> $cit),200);
}
else{
$this->response(array('error'=> 'data could not be found...'),404);
}
}
public function index_post(){
// Use validation library, instead of checking just for value.
$this->load->library('form_validation');
$this->form_validation->set_rules('city','City','trim|required');
if($this->form_validation->run() == FALSE)
{
// send back list of validation errors.
$this->response($this->validation_errors(),REST_Controller::HTTP_BAD_REQUEST);
}
$id=$this->cities_model->save($this->post('city'));
if(!is_null($id))
{
$this->response(array('response'=> $id),REST_Controller::HTTP_OK);
}
else
{
$this->response(array('error'=> 'sorry, data could not be saved...'),REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_put(){
// for put you need to pass id as parameter
// Use validation library, instead of checking just for value.
$this->load->library('form_validation');
$this->form_validation->set_rules('id','ID','trim|required|integer');
$this->form_validation->set_rules('city','City','trim|required');
if($this->form_validation->run() == FALSE)
{
// send back list of validation errors.
$this->response($this->validation_errors(),REST_Controller::HTTP_BAD_REQUEST);
}
$update=$this->cities_model->update($this->post('id'),$this->post('city'));
if(!is_null($update))
{
$this->response(array('response' => 'content updated successfully'),REST_Controller::HTTP_OK);
}
else
{
$this->response(array('error'=> 'sorry, technical error occurred, please try again later...'), REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_delete($id){
if(!$id)
{
$this->response(null,400);
}
$del=$this->cities_model->delete($id);
if(!is_null($del))
{
$this->response(array('response'=> 'item successfully deleted'),200);
}
else{
$this->response(array('error'=> 'delete operations could not be done...'),400);
}
}
}
here is the model file:
<?php
class Cities_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function get($id=null)
{
if(!is_null($id))
{
$query=$this->db->select('*')->from('cities')->where('id',$id)->get();
if($query->num_rows()===1)
{
return $query->row_array();
}
return null;
}
$sql=$this->db->select('*')->from('cities')->get();
if($sql->num_rows()>0)
{
return $sql->result_array();
}
return null;
}
public function save($city)
{
$this->db->insert('cities', array('name'=>$city));
if($this->db->affected_rows()>0)
{
return $this->db->insert_id();
}
return null;
}
public function update($id, $city)
{
$this->db->where('id',$id)->update('cities',$this->setCity(array('name'=>$city,'id'=> $id)));
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array('id'=>$city['id'],
'name'=>$city['name']
);
}
public function delete($id)
{
$this->db->where('id',$id)->delete('cities');
if($this->db->affected_rows()===1)
{
return true;
}
return false;
}
}
I'm trying to do:
when user authorized go to home page
when user not authorized go to Login page
but now when I put (correct) user email and password that always refresh login page and doesn't log in into system.
User(ActiveRecord)
class User extends ActiveRecord implements IdentityInterface
{
public function setPassword($user_password)
{
$this->password = sha1($user_password);
}
public function validatePassword($user_password)
{
return $this->user_password === sha1($user_password);
}
public static function findIdentity($id)
{
return self::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null)
{
}
public function getId()
{
return $this->user_id;
}
public function getAuthKey()
{
}
public function validateAuthKey($authKey)
{
}
}
Login Model:
class Login extends Model
{
public $user_email;
public $user_password;
public function rules()
{
return [
[['user_email', 'user_password'],'required'],
['user_email','email'],
['user_password','validatePassword']
];
}
public function validatePassword($attribute,$params)
{
if(!$this->hasErrors())
{
$user = $this->getUser();
if(!$user || !$user->validatePassword($this->user_password))
{
$this->addError($attribute, 'Пароль или пользователь введенны не верно');
}
}
}
public function getUser()
{
return User::findOne(['user_email'=>$this->user_email]);
}
}
?>
SiteController(only login function)
public function actionLogin()
{
if(!Yii::$app->user->isGuest)
{
return $this->goHome();
}
else {
$login_model = new Login();
return $this->render('login',['login_model'=>$login_model]);
}
}
Putting username and password is not enough you should also perform a login
public function actionLogin()
{
if(!Yii::$app->user->isGuest)
{
return $this->goHome();
}
if ($model->load(Yii::$app->getRequest()->post())) {
// you should perform login
\Yii::$app->getUser()->login($model->user, $this->rememberMe ? $model->module->rememberFor : 0);
return $this->goBack();
}
else {
$login_model = new Login();
return $this->render('login',['login_model'=>$login_model]);
}
}
I am new to Codeigniter. I have error when i try to check the email is existed or not. I saw lot of post on Stackoverflow and other website. I can't get any result.
When i try with below coding i got below errors
Unable to access an error message corresponding to your field name
Email.(email_check)
Please check my code.
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public function index()
{
$this->login();
}
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("email","Email","required|trim|callback_email_check");
$this->form_validation->set_rules("password","Password","required|md5|trim|callback_password_check");
if($this->form_validation->run())
{
redirect('main/members');
}
else
{
$this->load->view('login');
}
}
public function members()
{
$this->load->model('model_users');
if($this->model_users->can_log_in())
{
return true;
}
else
{
$this->form_validation->set_message('email_check', 'Incorrect Username/Password');
return false;
}
}
}
MODEL
<?php
class Model_users extends CI_Model
{
public function can_log_in()
{
$this->db->where->('email',$this->input->post('email'));
$this->db->where->('password',md5($this->input->post('password')));
$query = $this->db->get('users');
if($query->num_rows == 1)
{
return true;
}
else
{
return false;
}
}
}
?>
I believe you are missing your callback function email_check, and there the set_message should correspond to the function and not the field itself.
You will have to add the 2 callback functions that you are using :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public function index()
{
$this->login();
}
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("email","Email","required|trim|callback_email_check");
$this->form_validation->set_rules("password","Password","required|md5|trim|callback_password_check");
if($this->form_validation->run())
{
redirect('main/members');
}
else
{
$this->load->view('login');
}
}
public function email_check(){
//perform your validation here
if({your_validation_result}){
return true;
}else{
$this->form_validation->set_message('email_check', 'Incorrect Username/Password');
return false;
}
}
public function password_check(){
//perform your validation here
if({your_validation_result}){
return true;
}else{
$this->form_validation->set_message('password_check', 'Incorrect Username/Password');
return false;
}
}
public function members()
{
$this->load->model('model_users');
if($this->model_users->can_log_in())
{
return true;
}
else
{
$this->form_validation->set_message('email_check', 'Incorrect Username/Password');
return false;
}
}
}
Here is my authentication controller
class AuthController extends Controller
{
public function actionLogin()
{
$model = new LoginForm;
$post = Yii::app()->request->getPost('LoginForm');
// If form is submitted
if($post) {
$identity = new UserIdentity($post['username'], $post['password']);
if($identity->authenticate()) { // loop enters but could not get id
echo Yii::app()->user->id;
echo Yii::app()->user->getId();
} else {
echo 'failed';
}
//exit;
}
$this->render('login', array('model' => $model));
}
}
Here is my UserIdentity.php
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = SchLogins::model()->findByAttributes(array('username' => $this->username));
if(is_null($user)) {
$this->errorCode=self::ERROR_USERNAME_INVALID;
} else if($user->password != $this->password) {
$this->errorCode=self::ERROR_PASSWORD_INVALID;
} else {
$this->_id = $user->id;
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
In the above code I am having problem in getting user id (i.e) Yii::app()->user->getId(); this returns nothing and what wrong I did the above code
You are creating a LoginForm instance $model but you never use it to actually login. If you are using the standard LoginForm model then it is what interacts with the UserIdentity class. It should be this:
if($post) {
$model->attributes = $_POST['LoginForm'];
if ($model->validate() && $model->login()) { // loop enters but could not get id
echo Yii::app()->user->id;
echo Yii::app()->user->getId();
} else {
echo 'failed';
}
//exit;
}
If you look at the login() function of LoginForm you will see it calls Yii::app()->user->login($this->_identity,$duration); which is what actually sets the Yii::app()->user which with your method was being skipped.
I just a newbie in Yii. I have read http://www.yiiframework.com/wiki/328/simple-rbac/ and followed all instructions there, but I had error User.roles is not defined when I tried to login. Here is my UserIdentity.php
<?php
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = User::model()->findByAttributes(array
('username'=>$this->username));
if($user===null){
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else{
if($user->password!==$user->encrypt($this->password)){
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else{
$this->_id = $user->username;
$this->setState('roles', $user->roles);
$this->errorCode=self::ERROR_NONE;
}
}
return !$this->errorCode;
}
public function getId(){
return $this->_id;
}
}
And then EWebUser.php
<?php
class EWebUser extends CWebUser
{
public function checkAccess($operation, $params=array())
{
if (empty($this->id)) {
// Not identified => no rights
return false;
}
$role = $this->getState("roles");
if ($role === 'admin') {
return true; // admin role has access to everything
}
// allow access if the operation request is the current user's role
return ($operation === $role);
}
}
At last accessRules method in UserController.php
public function accessRules()
{
.....
return array(
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
//'users'=>array('admin'),
'roles'=>array('admin'),
.....
);
}
I hope anyone can help me solve this problwm, thank you very much