I'm new to CodeIgniter and have only started learning ajax. I'm trying to make a web-based management system using codeigniter, a distant relative gave me a sample of his system using codeigniter for reference before he left to work abroad. but I'm having problem with the login page of his system it keeps on refreshing the login page.
here is the login page.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CM_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->generate_login_page('backbone/login', [
'title'=>'CCC case management system - Login',
'js'=>['modules/home/login.js']
]);
}
public function authenticate_login() {
//$this->output->set_content_type('json');
//$this->form_validation->set_rules('username', '<strong>Username</strong>', 'required');
//$this->form_validation->set_rules('password', '<strong>Password</strong>', 'required');
//if($this->form_validation->run()){
$input = elements(['username','password'], $this->input->post());
$input['username'] = ucwords($input['username']);
$input['password'] = sha1($input['password']);
$result = $this->login_model->check_user_exist($input['username']);
//echo $input['username'];
//echo $result;
if($input['username'] !== ''){
if($result)
{
$result_match = $this->login_model->check_user_password_match($input['username'],$input['password'] );
//echo ''.;
if($result_match)
{
$result_user = $this->login_model->retrieve_user_information($input['username']);
$user_type_id = 0;
$user_id = 0;
if($result_user->num_rows() > 0){
foreach ($result_user->result() as $row) {
$user_type_id = $row->user_type_id;
$user_id = $row->user_id;
$username = $row->username;
}
}
//echo json_encode($result_user);
$session_data = array(
'username' => $username,
'session_id' => $this->session->userdata('session_id'),
'user_id' => $user_id,
'user_type_id' =>$user_type_id,
'is_logged_in' => 1
);
$this->session->set_userdata($session_data);
$this->session->set_userdata('login_state', TRUE);
redirect('/');
}
else
{
$this->session->set_flashdata('msg', 'Incorrect Password or Username!');
redirect('login/');
//
//echo 'Username or Password is incorrect';
//$this->output->set_output($this->set_json_output(FALSE, 'Username or Password is incorrect'));
}
}
else
{
$this->session->set_flashdata('msg', 'Invalid Username or doesnt exist !');
redirect('login/');
//
//$this->output->set_output($this->set_json_output(FALSE, 'User not Exist'));
//echo 'User not registered';
}
}else{
$this->session->set_flashdata('msg', 'Please input username !');
redirect('login/');
}
/*}else{
$error_messages = array_values($this->form_validation->error_array());
$this->output->set_output($this->set_json_output(FALSE, $error_messages));
}*/
}
}
if username and password match from database is should redirect to another page. if not a message should pop out for incorrect user / pass.
im not getting any errors but the problem is it does not redirect to another page it only keeps on refreshing the page and also if i leave user and pass empty / give an incorrect user & pass input the same thing happens. it seems like the function authenticate_login is not being executed? can anyone tell me what exactly is wrong here. Tnx.
Related
I have an Admin controller which handles the user login and other admin functionality like managing a basic cms. In the constructor I check if the users session present which is set once they login. If not and they try to access a restricted page, they should be redirected. If I redirect to another page then when going to the login page I get redirected right away as obviously that check is done in the constructor, but as soon as I try to redirect to the login page I get an error:
This page isn’t working localhost redirected you too many times. Try
clearing your cookies. ERR_TOO_MANY_REDIRECTS
class Admin extends Controller {
public function __construct()
{
if(!isLoggedIn()) {
redirect('admin/login');
}
$this->AuthModel = $this->model('Auth');
}
isLoggedIn is a function:
function isLoggedIn() {
if(isset($_SESSION['user_id']) && isset($_SESSION['browser']) && $_SESSION['browser'] == $_SERVER['HTTP_USER_AGENT']) {
return true;
} else {
return false;
}
}
Login method:
public function login()
{
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$password = trim($_POST['password']);
$data = [
'email' => $email,
'password' => $password,
'email_error' => '',
'pass_error' => '',
'no_user' => '',
'pass_wrong' => ''
];
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$data['email_error'] = 'Invalid email address <br />';
}
if(empty(trim($_POST['password']))) {
$data['pass_error'] = 'Password required';
}
if(!empty(trim($_POST['email'])) && !$this->AuthModel->getUserByEmail($email)) {
$data['no_user'] = 'Email does not exist';
}
if(!empty($data['email_error']) || !empty($data['pass_error']) || !empty($data['no_user'])) {
$this->view('admin/login', $data);
} else {
$loggedInUser = $this->AuthModel->login($email, $password);
if($loggedInUser) {
$this->CreateUserSession($loggedInUser);
} else {
$data['pass_wrong'] = 'Incorrect login details';
$this->view('admin/login', $data);
}
}
} else {
$data = [
'email' => '',
'password' => '',
'email_error' => '',
'pass_error' => '',
'no_user' =>'',
'pass_wrong' => ''
];
$this->view('admin/login', $data);
}
}
You are using same controller for login and other functionalities. Every time it checks for authentication and it gets no. And it loops over again. try to implement your login functionalities in a separate Controller.
CakePHP version: 3.3.5
I'm building a simple system using which users can login (using a email and password) and after login they can change their password.
For this, I'm using DefaultPasswordHasher
I had a few users already in my db. Their record were already present. So when I did the login function, it worked. I compared the password the user enters with the hased password already present in the db. The check was successful and user was able to login.
Now after login, I wrote change password function, which updated the user password. New hash string replaced the old password string but when I try to login again, login fails.
I will share my controller here. It's pretty basic.
namespace Api\Controller;
use Cake\Utility\Security;
use Cake\Utility\Hash;
use Cake\Auth\DefaultPasswordHasher;
use Api\Controller\AppController;
class LoginController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
//Function to reset the password
public function resetPassword()
{
$pass = $this->request->data['pass'];
$hasher = new DefaultPasswordHasher();
$hashedPass = $hasher->hash($pass);
$this->loadModel('Login');
//save it to db
$responseArray = $this->Login->resetPassword($hashedPass);
$this->set(compact('responseArray'));
$this->set('_serialize', ['responseArray']);
}
//Function to login
public function login()
{
if ($this->request->is('post'))
{
//Password submitted via form
$pass = $this->request->data['pass'];
//Hashed password fetched from db via a function call
$actualPassword = 'hashedPasswordString'
//Compare password submitted and hash from db
if($this->checkPassword($pass,$actualPassword))
{
$result = 'password matched';
}
else
{
$result = 'password doesnot match';
}
}
$this->set(compact('result'));
$this->set('_serialize', ['result']);
}
//Function to compare password and hash
public function checkPassword($passedPassword , $actualPassword)
{
if ((new DefaultPasswordHasher)->check($passedPassword, $actualPassword)) {
return true;
} else {
return false;
}
}
}
Can anyone tell me why the passwords don't match. I'm new to CakePHP framework. Thanks in advance!
This is what my reset password workflow looks like. I cannot tell from your post what your entity and table look like.
Anytime posted data is converted into a user entity it will now be hashed
Admin/UsersController.php
public function password($id = null)
{
$user = $this->Users->get($id, [
'fields' => ['id', 'first_name', 'last_name', 'username']
]);
if ($this->request->is('put')) {
if ($this->request->data['password'] == $this->request->data['password2']) {
$this->Users->patchEntity($user, ['password' => $this->request->data['password']]);
$this->Users->save($user);
$this->Flash->success('Password has been updated');
return $this->redirect('/admin/users/password/' . $id);
} else {
$this->Flash->error('Passwords do not match');
}
}
$this->set(compact('user'));
}
Model/Entity/User.php
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
public function changePassword(){
if ($this->request->is('post')) {
$data = $this->request->data();
$res['success'] = FALSE;
$user = $this->Users->get($this->Auth->user('id'))->toArray();
if ((new DefaultPasswordHasher)->check($data['oldPassword'], $user['password'])) {
if($data['newPassword'] == $data['confPassword']){
$userEntity = $this->Users->get($this->Auth->user('id'));
$userEntity->password = $data['newPassword'];
if($this->Users->save($userEntity)){
$res['success'] = TRUE;
$res['message'] = 'Password Changed Successfully.';
}
}else{
$res['success'] = FALSE;
$res['message'] = 'Confirm password is not same as new password. please enter both password again!!';
}
}else{
$res['success'] = FALSE;
$res['message'] = 'Your old password is wrong!';
}
echo json_encode($res);
exit();
}
}
I'm getting error when login to my project and then goto the base url. The below is the error which i get
My Login page [ see the url ]
After logging in , if i remove the highlighted segments[pls see below image] after which i get the above error
I know these error are due to headers so can somebody help me in saying what error am i making in header. An also say how to make good use of session so that the form is to resubmitted when i refresh after logging in. Below are the header codes.
login header
<?php if(isset($this->session->userdata['logged'])){
header("location: http://localhost/capacity_planner/login/login_check");
}
?>
admin dashboard[after logging in header]
<?php if(isset($this->session->userdata['logged'])){
$email = ($this->session->userdata['logged']['email']);
}else{
header("location: http://localhost/capacity_planner/login");
}
?>
controller side
public function login_check(){
$data['base_url'] = base_url();
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run($this) == false) {
$this->index();
} else {
if(isset($this->session->userdata['logged'])) {
$data['login_bg'] = $this->input->post('login_bg');
$this->load->view("admin_db", $data);
}
}
function check_database($password){
$email= $this->input->post('email');
$user = $this->user->loginCheck($email, $password);
if($user[1] == 1){
$result = $this->user->user_details($email);
if($result != false) {
$session_data = array(
'id' => $result[0]->id,
'email' => $result[0]->cp_email,
);
$this->session->set_userdata('logged', $session_data);
return true;
}
} else{
$this->form_validation->set_message('check_database', $user[0]);
return false;
}
}
ERR_TOO_MANY_REDIRECTS is caused when strucked up in a conditional loop
I assume you want to redirect to admin dashboard if you go to index after logged in..
Try adding these lines in your public function index()
public function index(){
if(isset($this->session->userdata['logged'])) {
//admin_db display function eg.redirect('admindashboard');
}
else{
//load your index view
this->load->view('your_index_view');
}
}
or you can check reverse way in admin dashboard function like this
public function dashboard(){
if($this->session->userdata('logged') == ''){
redirect('index');
}
else{
$this->load->view('dashboard view');
}
}
This is my assumption.Kindly check it.
I am trying to implement resetting a users password in codeigniter.
I've created a form that the users sends their email and it creates a row in a 'reset' table that stores their token that is created as well as attaches the token the link sent to the email.
The final step is actually resetting the password. I am not understanding how to make the correct comparison when checking the token attached to the email against the one stored in the db associated with that email, or if that is even the right way to go about it.
In the current code I have, I am unable to get it to pass validation and actually reset the password. Here is my code:
This is the model for creating the token and sending the email:
public function validate_retrieve($data) {
$query = $this->db->where($data)->get('users', '1');
foreach ($query->result() as $user)
{
$user->email;
$user->salt;
$user->id;
}
$token = sha1($user->email.$user->salt).dechex($user->id);
$reset_token = array(
'token' => $token,
'email' => $user->email
);
$insert = $this->db->insert('reset', $reset_token, '1');
return $reset_token;
}
and the controller:
public function retrieve()
// REQUEST PASSWORD RESET
// LOADED WHEN THE FORM IS SUBMITTED OFF THE PASSWORD PAGE AND SENDS THE EMAIL WITH TOKEN AND INSTRUCTIONS
{
$this->load->library('form_validation');
$this->load->library('session');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->load->model('user_model', 'um');
$this->load->library('encrypt');
$this->load->helper('url');
$submit = $this->input->post('submit');
$salt = $this->_salt();
if($submit)
// IF THE SUBMIT BUTTON IS SET
{
// START PROCESS TO CREATE $USER VARIABLE THAT HOLDS WHAT THE USER ENTERED IN THE FORM AND THAT CAN GET CHECKED AGAINST THE DB IN THE MODEL
$user = $this->um->validate_retrieve(array('email' => $this->input->post('email')));
// IF THE USER IS CREATED AND CHECKS OUT AND ALL OF THE ERRORS ARE CLEARED ON THE FORM
if( $user && $this->form_validation->run() == TRUE ) {
$domain = "clci.dev/index.php";
// CREATE A TOKEN LINK TO SEND TO THE USERS EMAIL THAT EXIST IN THE DB AND WAS ENTERED
$token = $user['token'];
$link = "http://www.".$domain."/auth/reset/?token=$token";
$this->load->library('email');
$this->email->from('noreply#cysticlife.org', 'CysticLife');
$this->email->to($this->input->post('email'));
$this->email->subject('Reset Password');
$this->email->message("Please go to the following web address to reset your password:\n\n$link\n\n-Your friends at CysticLife\n\nPlease remember to add the cysticlife.org domain to your address book to ensure that you receive your CysticLife e-Notifications as requested.");
$this->email->send();
redirect('auth/success');
exit;
}
$this->form_validation->run() == FALSE;
$data['main_content'] = 'auth/password';
$this->load->view('includes/templates/main_page_template', $data);
$data['email_error'] = 'This email is invalid';
}
}
now here is what I'm having trouble with, the model for resetting:
public function verify_token($token)
{
$this->db->where('token', $token);
$query = $this->db->get('reset');
if ($query->num_rows() == 1) {
return TRUE;
} else {
return FALSE;
}
}
public function reset_password()
{
$salt = $this->_salt();
$query = $this->db->get('reset', 1);
$row = $query->row();
$data = array(
'password' => $this->encrypt->sha1($salt . $this->encrypt->sha1($this->input->post('password'))),
'salt' => $salt
);
$this->db->where('email', $row->email);
$this->db->update('users', $data);
}
and the controller:
public function reset_password()
{
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('user_model', 'um');
$this->load->library('encrypt');
$this->load->helper('url');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
$this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|matches[password]');
$salt = $this->_salt();
$submit = $this->input->post('submit');
if($submit)
{
$validToken = $this->um->verify_token($token);
if($this->form_validation->run() == TRUE && $validToken == TRUE)
{
$this->um->reset_password(array('password' => $this->input->post('password', $salt)));
$data['main_content'] = 'auth/success';
$this->load->view('includes/templates/home_page_template', $data);
}
$this->form_validation->run() == FALSE;
$data['main_content'] = 'auth/reset';
$this->load->view('includes/templates/main_page_template', $data);
}
}
I seem to be very close but I am definitely stuck. Any help is greatly appreciated.
http://yoursitename.com/reset/[hashcode]
send the link to the member email, went password have reset by user.
on web site you will retrieve the hashcode to compare with your database
public function reset($hashcode)
{
if($hashcode!=null)
{
// compare with db
// if success
// redirect to create new password page
// or show create new password form
}
}
What I want to implement is a simple login page, if user login successfully, then redirect to main page, else remain login page.
I have 1 controller named login, and 1 model named main.
When user click the login button, the login/login_send will be called.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('model_login');
}
function index()
{
if ($this->model_login->is_logged_in())
{
redirect('main');
}
else
{
// load login page
$data['main'] = 'view_login';
$data['style'] = 'style_login';
$this->load->view('template', $data);
}
}
function login_send()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
if ( $this->model_login->validate_user() )
{
$user_session_data = array(
'username' => $this->input->post('username'),
'is_logged_in' => 1
);
$this->session->set_userdata($user_session_data);
redirect('main');
}
else
{
redirect('login');
}
}
}// end function login_send
function logout()
{
if ($this->model_login->is_logged_in())
{
$this->session->sess_destroy();
$this->session->set_userdata(array('username' => '', 'is_logged_in' => 0));
log_message('debug', 'Some variable was correctly set');
}
redirect('login','refresh');
}
}// end class Login
?>
Model_login here is just to help to verify if user is logged in, by check the session data.
<?php
class Model_login extends CI_MOdel{
function _isUserExist($username, $password)
{
$options = array(
'UserName' => $username,
'Password' => $password
);
$query = $this->db->get_where('userinfo', $options);
return $query->num_rows() > 0;
}
function validate_user()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
return ($this->_isUserExist($username, $password));
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if ( !isset($is_logged_in) || $is_logged_in != 1 ) return FALSE;
else return TRUE;
}
}// end class model_login
?>
When first time login, and then logout, there is no problem. However, if I login second time, I can not log out. Even the login/logout was called correctly, I also refreshed the page, but the session['is_logged_in'] == 1. Something wrong with my code?
In your application/config/config.php try changing
$config['sess_time_to_update'] = 300; //This is the default setting in ver 2.1.1
to
$config['sess_time_to_update'] = 0;
This gave me some problems a few years back