Codeigniter access session in view - php

function login(){
$data = array('username' => $_POST['username'], 'password' => $_POST['password']);
$this->form_validation->set_rules('username', 'Username', 'required|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('Login');
} else {
$result = $this->LoginModel->account_check($data);
if($result){
if($result['status'] = 'admin'){
$isLoggedin = array('user_type' => 'administrator' ,'admin_name' => $result['username'] , 'is_loggedin' => TRUE);
$this->session->set_userdata($isLoggedin);
$this->load->view('admin/homepage');
} else if($result['status'] = 'user'){
$isLoggedin = array( 'user_name' => $row['username'] , 'user_type' => 'user' , 'is_loggedin' => TRUE);
$this->session->set_user($isLoggedin);
$this->load->view('user/homepage');
}
}
}
}
function username_check($username){
$result = $this->LoginModel->username_check($username);
if($result != TRUE){
$this->form_validation->set_message('username_check' , 'Username does not exist');
return FALSE;
} else return TRUE;
}
MODEL:
function username_check($username){
$query = $this->db->get_where( 'admin' , array('username' => $username))->result_array();
if(!empty($query)){
return TRUE;
}else{
$query = $this->db->get_where( 'user_mst', array('username' => $username))->result_array();
if(!empty($query)){
return TRUE;
}else return FALSE;
}
}
function account_check($data){
$query = $this->db->get_where( 'admin' , array( 'username' => $data['username'] , 'password' => $data['password'] ))->result_array();
if(!empty($query)){
foreach($query as $row){
$result['status'] = 'admin';
$result['username'] = $row['username'];
$result['password'] = $row['password'];
return $result;
}
} else{
$query = $this->db->get_where( 'user_mst' , array( 'username' => $data['username'] , 'password' => $data['password'] ))->result_array();
if(!empty($query)){
foreach($query as $row){
$result['status'] = 'user';
$result['username'] = $row['username'];
$result['password'] = $row['password'];
return $result;
}
}
}
}
How do i access the user data, im going to use this to run an if per view if an account is logged in and if it is an admin acc.
I would like to read some opinion regarding how im using the session if i am 100% correct.
Also, i have a question,
This code <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
blocks direct access to the view, prevents view access but not specifically checks if a user is logged in.
How can i utilize this with the session. If its redundant please tell me,

Codeigniter passes data to the view with a second parameter:
$this->load->view('user/homepage');
doesn't pass any data.
$this->load->view('user/homepage', $data);
Would pass in a $data variable that you could use. (https://ellislab.com/codeigniter/user-guide/general/views.html)
Another point - I'd consider using the redirect() function after a successful login rather than loading the view you want in the login method. Use the URL Helper to do this (https://ellislab.com/codeigniter/user-guide/helpers/url_helper.html).
Hope that helps.

Related

Password verify function in codeigniter for login

Hi all I have this issue when I validate log in in codeigniter that seems it does not check the required password in my database.The required password in my database is hash using this
$password_hash = password_hash($password, PASSWORD_BCRYPT);
How can i used password_verify function in my model code?
Here is my model code:
public function login($data) {
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return true;
} else
{
return false;
}
}
Here is my controller:
public function login_user()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean','required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean','required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_view');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
// Add user data in session
$this->session->set_userdata('username', $data['username']);
$this->session->set_userdata('firstname', $data['firstname']);
$this->session->set_userdata('lastname', $data['lastname']);
//redirect to dashboard
$this->load->view('include/sidenavbar');
$this->load->view('include/topnavbar');
$this->load->view('dashboard');
} else {
$this->session->set_flashdata('message', 'Login is invalid. Please try again!');
$this->load->view('login_view', $data);
}
}
}
can anyone help me how to do this..
Thanks in advance.
You should use password_verify() to know if you're password is valid.
Try this model function:
public function login($data) {
$this->db->select('password');
$this->db->from('users');
$this->db->where('username', $data['username']);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
$record = $query->row_array();
return password_verify($data['password'], $record['password']);
} else {
return false;
}
}
Hope this will help you :
after returning data from model you can check for correct password using password_verify()
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname')
);
$result = $this->login_database->login($data);
/*$result should return a single user data (in array form here)*/
if (! empty($result))
{
if (password_verify($data['password'], $result['password']))
{
$this->session->set_userdata('username', $data['username']);
$this->session->set_userdata('firstname', $data['firstname']);
$this->session->set_userdata('lastname', $data['lastname']);
//redirect to dashboard
redirect('dashboard'); /*use redirect()*/
//$this->load->view('include/sidenavbar');
//$this->load->view('include/topnavbar');
//$this->load->view('dashboard');
}
else
{
$this->session->set_flashdata('message', 'Password is invalid. Please try again!');
$this->load->view('login_view', $data);
}
}
else
{
$this->session->set_flashdata('message', 'Login is invalid. Please try again!');
$this->load->view('login_view', $data);
}
Your model should be like this :
public function login($data)
{
$this->db->where('username', $data['username']);
$query = $this->db->get('users');
if ($query->num_rows() == 1) {
$user = $query->row_array();
return $user;
} else {
return false;
}
}
Update : dashboard method
public function dashboard()
{
/*$data['title'] = 'my title';
you can pass data to the view like this
$this->load->view('dashboard',$data);
*/
$this->load->view('templates/header');
$this->load->view('dashboard');
$this->load->view('templates/footer');
}

session checking is not working after uploading to server

this is my controller for login
public function user_login_process()
{
$this->form_validation->set_rules('username', 'username', 'trim|required');
$this->form_validation->set_rules('password', 'password', 'trim|required');
if ($this->form_validation->run() == false)
{
if(isset($this->session->userdata['logged_in']))
{
$this->load->view('admin/intropage');
}
else
{
$this->load->view('admin/login/login_dashboard');
}
}
else
{
$data = array('username' => $this->input->post('username'),'password' => md5($this->input->post('password')));
$result = $this->gt_login_model->login($data);
if ($result == true)
{
$username = $this->input->post('username');
$result = $this->gt_login_model->read_user_information($username);
if ($result != false)
{
$session_data = array('username' => $result[0]->user_name);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view('admin/intropage');
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('admin/login/login_dashboard', $data);
}
}
}
this is the code that i used to check whether the session is set or not in other pages
if(!$this->session->userdata['logged_in'])
{
redirect("gt_login");
}
else
{
}
but this checking doesnot works ie, in other pages
$session_data = array('username' => $result[0]->user_name);
the value inside this array is not available.This problem is only when i uploaded my project to the server . But when i woked in local host this whole project works fine .
now the main problem is i cant check wheather the session is set or not in other pages .

How to get session array data CodeIgniter

I'm not quite sure why the username didn't appear on view page if i change the session data into array (i'm new in CodeIgniter). I have auth controller to make login process:
function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('Login');
# code...
}
else {
$username = $this->input->post('username');
$password = $this->input->post('password');
$check = $this->M_login->check($username, $password);
// session data
if ($check->num_rows() == TRUE) {
foreach ($check->result() as $value) {
$sess_data['id'] = $value->id;
$sess_data['name'] = $value->name;
$sess_data['username'] = $value->username;
$sess_data['password'] = $value->password;
$sess_data['description'] = $value->description;
$this->session->set_userdata($sess_data);
}
redirect('Dashboard');
}
else {
$this->session->set_flashdata('result_login', '<br>Invalid username or password, try again.');
redirect('Login');
}
And here is my dashboard controller:
public function __construct() {
parent::__construct();
if(!$this->session->userdata('id')){
redirect('login');
}
}
public function index() {
// Dashboard view
$username = $this->session->userdata('username');
$data['username']=$username;
$this->load->view('Dashboard', $data);
}
function logout() {
$this->session->sess_destroy('id');
redirect('login');
}
With above code, i can get the username on my dashboard view by echo $username. But when i change the session data like this:
if ($check->num_rows() == TRUE) {
foreach ($check->result() as $value) {
// session data
$sess_data = array(
'id' => $value->id,
'username' => $value->username,
'password' => $value->password,
'name' => $value->name,
'description' => $value->description
);
$this->session->set_userdata('log',$sess_data);
}
}
And Dashboard controller changed like this:
if(!$this->session->userdata('id')) {
$getdata= $this->session->userdata('log');
$data['username'] = $getdata['username'];
}
$this->load->view('Dashboard', $data);
Then the username disappeared from view page. How can i store username in session array and call it in view page. Please share your better suggestions or your experience guys.
Thanks.
Adding data in session :-
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Retrieving Data from session :-
$this->session->all_userdata()
Retrieving single data :-
$session_id = $this->session->userdata('username');
Youcan refer this code
public function loginaction()
{
$this->load->library('session');
$a = $this->input->post('email');
$b = trim($this->input->post('password'));
$b1 = md5($b);
$c = 1;
$data = $this->userdata->userlogin($a,$b1,$c);
if($data)
{
echo true;
foreach ($data as $login)
{
$uid=$this->session->set_userdata('logId',$login->usr_id);
}
}
else
{
echo "Invalid username or password..!!!!";
$a=$this->input->post('email');
}
}
You can do it like
$username = $this->input->post('username');
$password = $this->input->post('password');
$check = $this->M_login->check($username, $password);
if ($check->num_rows() > 0)
{
$value = $check->row();
$sess_data['id'] = $value->id;
$sess_data['name'] = $value->name;
$sess_data['username'] = $value->username;
$sess_data['password'] = $value->password;
$sess_data['description'] = $value->description;
$this->session->set_userdata($sess_data);
redirect('Dashboard');
}
else
{
$this->session->set_flashdata('result_login', '<br>Invalid username or password, try again.');
redirect('Login');
}
And in your view
$username = $this->session->userdata('username');

best way to implement Codeigniter login

Here's my login controller index function:
public function index() {
$data['title'] = 'Login';
$this->load->view('login_form', $data);
}
then here's my validate_credentials function:
public function validate_credentials() {
$this->load->library('form_validation');
$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 {
$this->load->model('user_model');
if ($this->user_model->checkUserAccess($this->input->post('username'))) { // checks if user has access to the site
if ($this->ldapAuth()) { // checks if successful authentication with LDAP server
$email = $this->user_model->getEmail($this->input->post('username'));
$gpcid = $this->user_model->getUserGPC($this->input->post('username'));
$this->user_model->updateTimestamp('users', 'DateLastLogin', 'UserID', $this->input->post('username'));
$data = array (
'username' => $this->input->post('username'),
'gpcid' => $gpcid,
'email' => $email,
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile');
} else { // unsuccessful login
$error = "Username and/or Password is incorrect";
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
}
} else {
$error = "You do not have access to the site";
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
}
}
}
Is there a way to just call the index function and pass the error message rather than loading the view multiple times?
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
Instead of loading view file you have to redirect it to index function. And use Session flash data to achieve this.
Like,
Controller
$this->session->set_flashdata( 'error', 'Username and/or Password is incorrect' );
redirect('index');
To print the message on login_form.php view file,
View (login_form.php)
<?php if($this->session->flashdata('error')){
echo $this->session->flashdata('message');
}?>
Your Controller
public function validate_credentials() {
$this->load->library('form_validation');
$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 {
$this->load->model('user_model');
if ($this->user_model->checkUserAccess($this->input->post('username'))) { // checks if user has access to the site
if ($this->ldapAuth()) { // checks if successful authentication with LDAP server
$email = $this->user_model->getEmail($this->input->post('username'));
$gpcid = $this->user_model->getUserGPC($this->input->post('username'));
$this->user_model->updateTimestamp('users', 'DateLastLogin', 'UserID', $this->input->post('username'));
$data = array (
'username' => $this->input->post('username'),
'gpcid' => $gpcid,
'email' => $email,
'is_logged_in' => true
);
$this->session->set_flashdata($data);
redirect('profile');
} else {
$userdata = array (
'error' =>'Username and/or Password is incorrect',
);
$this->session->set_flashdata($userdata);
redirect('redirect url here'); // here is your url for index
}
} else {
$userdata = array (
'error' =>'You do not have access to the site',
);
$this->session->set_flashdata($userdata);
redirect('redirect url here'); // here is your url for index
}
}
}
Controller
public function loginaction() {
$this->load->library('session');
$a = $this->input->post('email');
$b = trim($this->input->post('password'));
$b1 = md5($b);
$c = 1;
$data = $this->userdata->userlogin($a, $b1, $c);
if($data) {
echo true;
foreach ($data as $login) {
$uid = $this->session->set_userdata('logId', $login->usr_id);
}
} else {
echo "Invalid username or password..!!!!";
$a = $this->input->post('email');
}
}

Password is not matching while logging in

I have this code while registering the form:
function register()
{
$this->form_validation->set_rules('txt_username', 'Username', 'trim|required');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required|matches[txt_password]|md5');
$this->form_validation->set_rules('txt_password', 'Password', 'trim|required|md5');
//other codes
$data = array('username' => $this->input->post('txt_username'),
'password' => $this->input->post('txt_password')
);
// insert form data into database
if ($this->account_model->insertUser($data));
{
$this->session->set_flashdata('msg','successfully registered!');
redirect('account/register');
}
}
the password matches here.
but when i use same data to username and password to login: it displays invalid username or password:
the login function is as follows:
function login()
{
//set validations
$this->form_validation->set_rules("txt_username", "Username", "trim|required");
$this->form_validation->set_rules("txt_password", "Password", "trim|required");
$username = $this->input->post("txt_username");
$password = $this->input->post("txt_password");
$usr_result = $this->account_model->get_user($username, $password);
if ($usr_result > 0) //active user record is present
{
$this->account_model->login();
$data['message'] ="You are logged in!";
}
else
{
$this->session->set_flashdata('msg', 'Invalid username and password!');
}
}
}
I have this model for inserting registration form data to database:
function insertUser($data)
{
return $this->db->insert('user', $data);
}
and i have this model to retreive data to login:
function get_user($usr, $pwd)
{
$sql = "select * from user where username = '" . $usr . "' and password = '".md5($pwd). "'";
$query = $this->db->query($sql);
return $query->num_rows();
}
The best method instead of MD5 is use base64 in Codeigniter. That means decode() and encode().
Encoding
$password = 'mYp#ssw0rd'; // or $password
$encriptKey = 'super-secret-key';
$encrypted_string = $this->encrypt->encode($password, $encriptKey);
Decoding
$password = 'mYp#ssw0rd'; // or $password
$encriptKey = 'super-secret-key';
$decrypted_string = $this->encrypt->decode($password, $encriptKey);
In Addition
Load library as well $this->load->library('encrypt');
You could do this in your model:
public function login()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user))
{
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'user_type'=>$user->user_type,
'emp_id'=>$user->emp_id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
return TRUE;
}
return FALSE;
}
public function logout ()
{
$this->session->sess_destroy();
$this->session->unset_userdata('logged_in','id','name','email');
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
And can let a user login. Use CI Session for login which would be a better option.
Read More here
For Controller Do this:
public function login()
{
$dashboard ='admin/dashboard';
$rules = $this->secure_m->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == TRUE)
{
if ($this->secure_m->login() == TRUE)
{
$this->secure_m->loggedin() == FALSE || redirect($dashboard);
redirect($dashboard);
}
else
{
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('secure/login', 'refresh');
}
}
$this->load->view("Your View");
}
Please store encrypted password at insert time.
for example:
$data['password'] = md5($data['password']);
I think it will resolve your problem.
Other code is working fine for me.

Categories