Codeigniter session different site - php

Hi all I have two sites developed in codeigniter. These sites are completely different but the mdoel of user is similar like the login method because I thinked to recycle that code.
The problem is: If I log in into a site and open the other I am logged in inside it with the user of the other site that doesn't exist into my database.
Database are different, I don't know what is the problem or if I have to change my login method into my model or some configuration.
This is my method in the model:
function login($username = '', $password = '') {
$user_name = base64_decode($username);
$password = base64_decode($password);
//Make sure login info was sent
if($username == '' || $password == '') {
return FALSE;
}
//Check if already logged in
if( $this->session->userdata('username') == $username && $this->session->userdata('logged_in') ) {
//User is already logged in.
return TRUE;
}
//Check against user table
$this->db->where('username', $user_name);
$this->db->where('password', $this->encrypt->sha1($password) );
$this->db->where('active', 1);
$query = $this->db->get_where($this->user_table);
if ($query->num_rows() > 0) {
$row = $query->row_array();
//Destroy old session
$this->session->sess_destroy();
//Create a fresh, brand new session
$this->session->sess_create();
//Update Last Login
$data = array(
'last_login' => date('Y-m-d H:i:s')
);
$this->db->where('id', $row['id']);
$this->db->update($this->user_table, $data);
//Set session data
$this->session->set_userdata(array('id' => $row['id'], 'username' => $row['username'],'name' => $row['name'], 'surname' => $row['surname'], 'language' => $row['language']));
if ($row['type']==1){
//se è 1 è un administrator
$this->session->set_userdata(array('is_admin' => 1));
}
else{
$this->session->set_userdata(array('is_admin' => 0));
}
//Set logged_in to true
$this->session->set_userdata(array('logged_in' => TRUE));
//image profile
$this->db->where('user_id', $row['id']);
$query2 = $this->db->get_where('user_image_profile');
if ($query2->num_rows() > 0) {
$row_image = $query2->row_array();
$this->session->set_userdata(array('img_profile' => $row_image['filename']));
}
//Login was successful
return TRUE;
} else {
//No database result found
return FALSE;
}
}

I think the problem is in the config file. Here you use the same "encryption_key" for the both site for that reason when you log in one site and open the other one here you also logged. So you have to use different "encryption_key" for the both site.
like that for first web site-
$config['encryption_key'] = 'gHZc2let11sp3YAns00rggHlYNMp7CVX';
and the second one -
$config['encryption_key'] = 'V1M839GlUk65rKzm1GM67H66X1WLD6ay';

for each application you can configure the session to be stored in the database. change config file.
sess_use_database = true;
after that you need to create this table in your database
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id VARCHAR(40) DEFAULT '0' NOT NULL,
ip_address VARCHAR(16) DEFAULT '0' NOT NULL,
user_agent VARCHAR(120) NOT NULL,
last_activity INT(10) UNSIGNED DEFAULT 0 NOT NULL,
user_data TEXT NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);

Related

Make Username and Password Input Case Sensitive

Hi I would like to add here a case sensitive error trap on my login function, by the way i am using MVC FRAMEWORK anyone be of help ? I want to make the username and password case sensitive so that is the input doesn't match an error exception will occur............... I have tried but failed maybe someone can assist me on hot to go about this dilemma
//THIS IS THE CODE OF MY CONTROLLER
public function login() {
if(isLoggedIn()) {
header("Location: " .URLROOT . "/");
}
$data = [
'title' => 'Login page',
'username' => '',
'password' => '',
'usernameError' => '',
'passwordError' => ''
];
//Check for post
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//Sanitize post data
$_POST = filter_input_array(INPUT_POST);
$data = [
'username' => trim($_POST['username']),
'password' => trim($_POST['password']),
'usernameError' => '',
'passwordError' => '',
];
$findUser = $this->userModel->findUser($data);
//Validate username
if(empty($data['username'])){
$data['usernameError'] = 'Please enter a username.';
}else if($findUser === false){
$data['usernameError'] = "Username not registered";
}
//Validate username
if(empty($data['password'])){
$data['passwordError'] = 'Please enter a password.';
}else if($findUser === false){
$data['passwordError'] = "Password not registered";
}
$findUser = $this->userModel->getUserDetails($data);
//Check if all errors are empty
if(empty($data['usernameError']) && empty($data['passwordError'])){
$loggedInUser = $this->userModel->login($data['username'], $data['password']);
if($loggedInUser){
$this->createUserSession($loggedInUser);
}else {
$data['passwordError'] = 'Password is incorrect. Please try again.';
$this->view('users/login',$data);
}
}
}else{
$data = [
'username' => '',
'password' => '',
'usernameError' => '',
'passwordError' => ''
];
}
//THIS IS THE CODE OF MY MODEL
public function login($username, $password) {
$this->db->query('SELECT * FROM user WHERE username = :username');
//Bind value
$this->db->bind(':username', $username);
$row = $this->db->single();
$hashedPassword = !empty($row) ? $row->password:'';
if(password_verify($password, $hashedPassword)){
return $row;
}else {
return false;
}
}
$this->view('users/login', $data);
}
Case sensitive error trap
If you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:
SELECT * FROM `table` WHERE BINARY `column` = 'value'
The password is already case-sensitive, since it's using the native password_hash and password_verify functions, it can be easily tested with:
var_dump(password_verify('AAA', password_hash('AAA', PASSWORD_DEFAULT))); // true
var_dump(password_verify('AAA', password_hash('aaa', PASSWORD_DEFAULT))); // false
If you really want to have the username case-sensitive, you can also use a case-sensitive collation for the username field, such as utf8mb4_0900_as_cs, more info here.
ALTER TABLE `users` CHANGE COLUMN `username` `username` VARCHAR(255) CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_0900_as_cs' NOT NULL;
Test case:
INSERT INTO `users` (`username`) VALUES ('test');
SELECT * FROM `users` WHERE `username`='TEST'; /* returns nothing as expected */

Second tab redirect to login page when i am already logged in, In codeigniter Application

function auth(){
$nic = $this->input->post('nic',TRUE);
$password = md5($this->input->post('password',TRUE));
$this->load->model('Login_model');
$validate = $this->Login_model->validate($nic,$password);
$this->load->helper("cookie");
$autoLogin = $this->input->post("autologin",true);
if($validate->num_rows() > 0){
$data = $validate->row_array();
$nic = $data['user_nic'];
$name = $data['user_name'];
$email = $data['user_email'];
$level = $data['user_level'];
$sesdata = array(
'nic' => $nic,
'username' => $name,
'email' => $email,
'level' => $level,
'logged_in' => TRUE
);
$this->session->set_userdata($sesdata);
if($level === '1'){
redirect('Forget/dashboard');
// access login for staff
}elseif($level === '2'){
redirect('welcome/officer_dashboard');
// access login for author
}elseif($level === '3'){
redirect('User/User_Dashboard');
}
}else{
echo $this->session->set_flashdata('msg','Username or Password is Wrong');
redirect('welcome');
}
}
}
This is my user auth function which redirects to ages upon user levels. I have many views as per the User levels.
But whenever I have loggedin, the second tab base url redirects to Login page again.
TIA
Debug the session data(using print statements) and make sure that you have added proper conditions in each page based on session data
I Welcome controller, Check the session data is_logged in, If data available act according to it
public function index()
{
$session_id = $this->session->userdata('nic');
if (!empty($session_id))
{
$this->load->view('login');
}
else
{
redirect('welcome/auth');
}
}

How can I add a number to value if already exist in CodeIgniter

In my register form I have an input which is unique but if more than two users would like to create an exact username I would like for the second username created to have a number after the typed value.
For example we have two users:
username 1: codelover
username 2: codelover2 and so on.
I currently have this in my controller:
// Create Page Data Array
$data = array(
'first_name' => strip_tags($this->input->post('first_name')),
'last_name' => strip_tags($this->input->post('last_name')),
'email' => strip_tags($this->input->post('email')),
//'username' => strip_tags($this->input->post('username')),
'ip_address' => $this->input->ip_address(),
'genre' => $this->input->post('genre'),
'slug' => $slug,
'status' => 'active',
/* 1-Founder, 2-Administrator, 3-Editor, 4-Author , 5-Contributor , 6-Subscriber , 7-Banned, 8-Suspended */
'role' => 'Subscriber',
'password' => strip_tags(password_hash($this->input->post('password'), PASSWORD_DEFAULT)),
'password2' => strip_tags(password_hash($this->input->post('password2'), PASSWORD_DEFAULT)),
);
// Is this the right approach of doing this?
$i = 0;
while($this->input->post('username') != 0){
$i++;
$data['username'] = strip_tags($this->input->post('username'.'.'.$i));
}
//Check if username and/or email already exist.
$existent_username = $this->User_model->existent_username($this->input->post('username'));
$existent_email = $this->User_model->existent_email($this->input->post('email'));
if (!empty($existent_username) || ($existent_email)) {
// Create Message
$this->session->set_flashdata('error', 'Username and/or Email already exist. Try again.');
// Redirect to pages
redirect('users/register');
} else {
// Add User
$this->User_model->add($data);
and this in my model which checks if username already exists:
public function existent_username($username) {
$query = $this->db->get_where($this->table, array('username' => $username));
return $query->row_array();
}
This is what I'm trying to do but in CodeIgniter:
if(empty($existent_username)){
$query = mysqli_query($con, "SELECT username FROM users WHERE username = '$username'");
$i = 0;
// If username already exists, add number to username
while(mysqli_num_rows($query) != 0){
$i++;
$username = $username ."." . $i;
$query = mysqli_query($con, "SELECT username FROM users WHERE username = '$username'");
}
}
First of all
// Is this the right approach of doing this?
$i = 0;
while($this->input->post('username') != 0) {
$i++;
$data['username'] = strip_tags($this->input->post('username'.'.'.$i));
}
This is wrong, its seems to me you are running an infinite loop here. I did not even understand why you need it. If you users can provide multiple username then get the input fields value first then run the loop.
Now about the main question,
you should the get all the existing usernames thats partially matches with the provided username. then generate the username and check the username already existed or not. If not then that's the username. like this.
$username = $this->input->post('username');
$existent_username = $this->User_model->existent_username($username));
if (!empty($existent_username)) {
$partially_matched_usernames = $this->db->select('username')->like('username', $username, 'after')->from('users')->get()->result_array();
$usernames_array = array_column($partially_matched_usernames, 'username');
// now generate the username
$i = 1;
while(true) {
if( ! in_array($username.$i, $usernames_array)) {
$username = $username.$i;
break;
}
$i++;
}
echo $username;
}
I did not run this code, so there could be any error. I think you will able to fix that by yourself.

How to stop updating password in codeigniter in edit method?

When i edit a user and save it , it saves blank filed in database. It Save all other fields as it is, but for password i have to manually add password every time i edit a user.
This is my edit method::
if ($id)
{
$this->data['user'] = $this->user_m->get_emp($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
$rules = $this->user_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE)
{
$data = $this->user_m->array_from_post(array('emp_id','name','last_name','email','password','phone','gender','designation','user_type','blood_group','date_birth','status','address'));
$data['password'] = $this->user_m->hash($data['password']);
$id = $this->session->userdata('id');
$this->user_m->save($data, $id);
redirect('admin/user/index');
}
}
// Load the view
$this->data['subview'] = 'employee/profile/edit';
$this->load->view('employee/_layout_main', $this->data);
This is my HASH METHOD:
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
Now i want that when i edit a user and i dont change his password i dont want the password updated to be blank instead keep the last inserted passoword.
But My Code generates this query:
UPDATE `users` SET `emp_id` = '21', `name` = 'Rajan', `last_name` = 'Jadav', `email` = 'rajan#bizrtc.com', `password` = '3eee66dbace42d2e671c52013e41de441b176dbaa0f7df33a5811b86c78b60ecb5328184bf1f5057f94817801140d7287f31c1fb06fa65550c356a33a8eec0db', `phone` = '999999999988', `gender` = 'Male', `designation` = 'Web', `user_type` = 'employee', `blood_group` = '+ve', `date_birth` = 'DD-MM-YYYY', `status` = 'Active', `address` = 'DD-MM-YYYY' WHERE `id` = 18
THe Model Code:
public function save($data, $id = NULL){
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
If I remove the hash method from controller then it inserts blank field and if i keep it it inserts false values
I just found a solution.
I will check if i have blank password if so then will unset it and if not then insert the new password using this:
if(!empty($data['password']))
{
$data['password'] = $this->user_m->hash($data['password']);
} else {
// We don't save an empty password
unset($data['password']);
}
1.) Add $this->output->enable_profiler(TRUE); to your code to enable Debug Profiling as described here
2.) In your controller add some var_dumps to check for the values of your vars:
$data = $this->user_m->array_from_post(array('emp_id','name','last_name','email','password','phone','gender','designation','user_type','blood_group','date_birth','status','address'));
// Let's dump the $data array and kill the app:
var_dump($data);die;
You can move the var_dump successively down step after step to see exactly what the value of your vars is.
Tip: I am guessing the problem is in the View (HTML Form) - But with Profiler and var_dump you should see that very easily.
Hope this helps - Good Luck!
A bad approach is to use unset password from your data before updating. In your code it would be like:
unset($data['password']);
Also if you don't want to update password on user edit just don't show the field.

Check MySQL if token is valid, then return. If not, generate token

I have this table:
CREATE TABLE wp_tokens (
ID int(12) NOT NULL AUTO_INCREMENT,
USER varchar(128) NOT NULL COMMENT 'User name',
TS timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
IP varchar(64) NOT NULL,
TOKEN varchar(128) NOT NULL COMMENT 'Hashed tokens',
VALID (12),
PRIMARY KEY (`ID`)
)
And I want to check if a token exists for a user. If it exists, then it should return the token. If not, it should generate one.
Here is my PHP:
<?php
global $wpdb;
global $user_login;
$token = uniqid();
$hashedtoken = md5($token);
$user = $user_login;
$ip = $_SERVER['REMOTE_ADDR'];
$valid = "1";
$chkdb = mysql_query("SELECT valid FROM wp_tokens WHERE user=$user");
if(mysql_num_rows($chkdb) == 1)
{
echo $hashedtoken;
}
else
{
$wpdb->insert('wp_tokens',
array('user' => $user, 'token' => $hashedtoken, 'ip' => $ip, 'valid' => $valid),
array('%s','%s','%s'));
}
?>
It doesn't work and I cannot solve. It's being executed on Wordpress $wpdb should be working. Please help!

Categories