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]);
}
}
Related
I am trying to create the login system. My login system works 100% perfectly but the problem is that it's not redirecting properly with sessions. When I try the function in index it's working fine but if I move the function to parent construct then it's not fine. I think there is an issue with the parent construct because it's also not loading the library and models in parents. So I have to call everything in each function. Check the code that I tried:
This code works fine:
<?php
/**
*
*/
class Adminpanel04736 extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function index()
{
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
$this->load->view('admin/dashboard');
}
public function list_of_post()
{
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
$this->load->model('admin_blog_post');
$result['post_list']=$this->admin_blog_post->post_list();
$this->load->view('admin/post_list',$result);
}
// post delete id is comming from post_list php to delete the post
public function post_bin($post_delete_id)
{
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
$this->load->model('admin_blog_post');
$result=$this->admin_blog_post->trash_post($post_delete_id);
if ($result) {
redirect('adminpanel04736/list_of_post'); # code...
}
}
public function my_bin_post()
{
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
$this->load->model('admin_blog_post');
$result['re']=$this->admin_blog_post->trash_bin_post();
$this->load->view('admin/trashed_post',$result);
}
// recycleing the post to repost
public function recycle_post($re)
{
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
$this->load->model('admin_blog_post');
$result=$this->admin_blog_post->repost($re);
if ($result) {
redirect('adminpanel/my_bin_post');
}
}
public function add_new_post()
{
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
$this->load->view('admin/add_new_post');
}
// id is comming from delete post page to delete the post permenently
public function destroy_post($id)
{
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
$this->load->model('admin_blog_post');
$result=$this->admin_blog_post->destroy_post_permenently($id);
if ($result) {
redirect('adminpanel04736/my_bin_post');
}
}
public function post_content()
{
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
$this->load->model('admin_blog_post');
$result=$this->admin_blog_post->adding_the_posts($_POST);
if ($result) {
redirect('adminpanel04736/list_of_post');
}
}
public function admin_login()
{
$this->load->view('admin/lock1');
}
public function loginauthticate()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('admin_password','Password','required');
if ($this->form_validation->run()) {
$this->load->model('admin_blog_post');
$verification=$this->admin_blog_post->login_validation($_POST);
if ($verification) {
$username=$_POST['admin_user'];
$password=$_POST['admin_password'];
$session_data= array(
'admin_user' => $username
);
$this->session->set_userdata($session_data);
redirect(base_url().'adminpanel04736/');
}
else
{
$this->session->set_flashdata('error','Invalid Password');
redirect(base_url().'adminpanel04736/admin_login');
}
}
else
{
$this->admin_login();
}
}
}
?>
But this gives me error redirect too many times. And also doesn't load the library in all functions:
<?php
/**
*
*/
class Adminpanel04736 extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('session');
if ($this->session->userdata('admin_user')=='')
{
redirect(base_url().'adminpanel04736/admin_login');
}
}
public function index()
{
$this->load->view('admin/dashboard');
}
public function list_of_post()
{
$this->load->model('admin_blog_post');
$result['post_list']=$this->admin_blog_post->post_list();
$this->load->view('admin/post_list',$result);
}
// post delete id is comming from post_list php to delete the post
public function post_bin($post_delete_id)
{
$this->load->model('admin_blog_post');
$result=$this->admin_blog_post->trash_post($post_delete_id);
if ($result) {
redirect('adminpanel04736/list_of_post'); # code...
}
}
public function my_bin_post()
{
$this->load->model('admin_blog_post');
$result['re']=$this->admin_blog_post->trash_bin_post();
$this->load->view('admin/trashed_post',$result);
}
// recycleing the post to repost
public function recycle_post($re)
{
$this->load->model('admin_blog_post');
$result=$this->admin_blog_post->repost($re);
if ($result) {
redirect('adminpanel/my_bin_post');
}
}
public function add_new_post()
{
$this->load->view('admin/add_new_post');
}
// id is comming from delete post page to delete the post permenently
public function destroy_post($id)
{
$this->load->model('admin_blog_post');
$result=$this->admin_blog_post->destroy_post_permenently($id);
if ($result) {
redirect('adminpanel04736/my_bin_post');
}
}
public function post_content()
{
$this->load->model('admin_blog_post');
$result=$this->admin_blog_post->adding_the_posts($_POST);
if ($result) {
redirect('adminpanel04736/list_of_post');
}
}
public function admin_login()
{
$this->load->view('admin/lock1');
}
public function loginauthticate()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('admin_password','Password','required');
if ($this->form_validation->run()) {
$this->load->model('admin_blog_post');
$verification=$this->admin_blog_post->login_validation($_POST);
if ($verification) {
$username=$_POST['admin_user'];
$password=$_POST['admin_password'];
$session_data= array(
'admin_user' => $username
);
$this->session->set_userdata($session_data);
redirect(base_url().'adminpanel04736/');
}
else
{
$this->session->set_flashdata('error','Invalid Password');
redirect(base_url().'adminpanel04736/admin_login');
}
}
else
{
$this->admin_login();
}
}
}
?>
Your admin_login is method of Adminpanel04736 class.
But when any method is called (including admin_login) and a user is not already logged, you redirect again to admin_login. So, you get infinite redirects instead of login procedure.
Move admin_login out of the class or check a method name before redirect, something as
function __construct()
{
parent::__construct();
$this->load->library('session');
if ($this->session->userdata('admin_user')=='' and
$this->uri->segment(2) !== 'admin_login'))
{
redirect(base_url().'adminpanel04736/admin_login');
}
}
Before use redirect(), you should load this: $this->load->helper('url');
function __construct()
{
parent::__construct();
$this->load->library('session');
if ($this->session->userdata('admin_user')=='' and
$this->uri->segment(2) !== 'admin_login'))
{
redirect(base_url().'adminpanel04736/admin_login');
}
}
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 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.
Hi iam newbie to yii framework. And iam getting this error after submitting the login details.
error
C:\wamp\www\yii\framework\web\auth\CWebUser.php(154)
152| $this->setState($name,$value);
153| else
154| parent::__set($name,$value);
155| }
and in STACKTRACE
C:\wamp\www\yiiapp1\protected\models\LoginForm.php(71): CModule->__get("user")
70| $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
71| Yii::app()->user->login($this->_identity,$duration);
72| return true;
THIS IS MY USER.PHP FILE
class user extends CActiveRecord
{
public function validatePassword($password)
{
return CPasswordHelper::verifyPassword($password,$this->password);
}
public function hashPassword($password)
{
return CPasswordHelper::hashPassword($password);
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'user';
}
public function rules()
{
return array(
array('', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
);
}
public function attributeLabels()
{
return array(
);
}
public function search()
{
$criteria=new CDbCriteria;
return new CActiveDataProvider('user', array(
'criteria'=>$criteria,
));
}
}
LOGINFORM
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe;
private $_identity;
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'),
);
}
public function attributeLabels()
{
return array(
'rememberMe'=>'Remember me next time',
);
}
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');
}
}
public function login($identity,$duration)
{
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);// --> HERE THE STACKTRACE SHOWING THE ERROR
return true;
}
else
return false;
}
}
It seem you use Yii::app()->user->clientScript;, just replace it by Yii::app()->clientScript
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.');
}
}
}