Codeigniter 3 Multi User database - codeigniter

I just finished creating website for my school projects with CI 3. I've also made a session and also all the menu for admin and user. But, when i tried to register a new user account and then login with it, the page showing the exact data like user 1. How can i make a different crud database to every different user (with the same views of page), so every user can do CRUD on their data.
This is my authh controller code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Authh extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->library('form_validation');
}
public function index(){
$this->form_validation->set_rules('email','Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password','Password', 'trim|required');
if($this->form_validation->run() == false){
$data['title']= 'LCA Master Login';
$this->load->view('auth/header2',$data);
$this->load->view('authh');
$this->load->view('auth/footer2');
} else{
$this->_login();
}
}
private function _login()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$user = $this->db->get_where('user',['email' => $email])->row_array();
//jika usernya ada
if($user) {
// jika usernya aktif
if($user['is_active']==1){
//cek password
if(password_verify($password, $user['password'])){
$data= [
'email' => $user['email'],
'role_id' => $user['role_id']
];
$this->session->set_userdata($data);
if($user['role_id']== 1){
redirect('admin');
} else {
redirect('user');}
}else {
$this->session->set_flashdata('message','<div class="alert alert-danger" role="alert">Wrong password!</div>');
redirect('authh');
}
} else{
$this->session->set_flashdata('message','<div class="alert alert-danger" role="alert">Email has not been activated!</div>');
redirect('authh');
}
} else {
$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Email is not registered!</div>');
redirect('authh');
}
}
public function registration(){
$this->form_validation->set_rules('name', 'Name', 'required|trim');
$this->form_validation->set_rules('email', 'Email','required|trim|valid_email|is_unique[user.email]',[
'is_unique'=> 'This Email is already Registered!'
]);
$this->form_validation->set_rules('password1', 'Password', 'required|trim|min_length[3]|matches[password2]', [
'matches' => 'Password dont match!',
'min_length' => 'Password too short!'
]);
$this->form_validation->set_rules('password2', 'Password', 'required|trim|matches[password1]');
if ($this->form_validation->run() == false){
$data['title']= 'LCA Master Registration';
$this->load->view('auth/header2',$data);
$this->load->view('register');
$this->load->view('auth/footer2');
} else{
$data = [
'name' => htmlspecialchars($this->input->post('name', true)),
'email' => htmlspecialchars($this->input->post('email', true)),
'image' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' =>1,
'date_created'=>time()
];
$this->db->insert('user', $data);
$this->session->set_flashdata('message','<div class="alert alert-info" role="alert">
Your Account Has Been Created! Please Login </div>');
redirect ('authh');
}
}
public function logoutt()
{
$this->session->unset_userdata('email');
$this->session->unset_userdata('role_id');
$this->session->set_flashdata('message','<div class="alert alert-success"
role="alert">You have been logged out!</div>');
redirect('authh');
}
}

Related

Codeigniter sessions, display user's firstname

I'm trying to display the user's firstname after login but it doesn't appear on the page. I tried to display it like this
<h2> Welcome <?php echo $this->session->userdata('firstname'); ?> </h2>
but it didn't display the user's firstname, even though there are data in DB. But when I tried to change the 'firstname' into 'username', it displayed the email of the user(test#gmail.com). How can I display the user firstname? Here's my controller:
function login(){
$this->form_validation->set_rules('username', 'Username', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
redirect('/');
} else {
$user_login = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
);
$login = new UI_model;
$result = $login->login_user($user_login);
if($result){
$auth_details = array(
'firstname' => $result->firstname,
'lastname' => $result->lastname,
'username' => $result->username,
);
$this->session->set_userdata($auth_details);
// $this->session->set_userdata('authenticated', '1');
$this->session->set_flashdata('status', 'User Logged in Successfully!');
redirect(base_url('pages/index'));
} else {
$this->session->set_flashdata('status', 'Invalid Credentials. Please try again');
redirect(base_url('pages/about'));
}
}
}
Here's my Model:
public function login_user($data){
$this->db->select('*');
$this->db->where('username', $data['username']);
$this->db->where('password', $data['password']);
$this->db->from('users');
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1){
return $query->row();
} else {
return false;
}
}
Can you attach an image of your database you are using for and echo all data session?

Laravel - How to pass parameter from controller to route and use it in another controller?

I have configured a resource route as below
Route::resource('users', UserController::class);
When a user posts data, it will call the store method in the controller where it will add the data and set a message for success/failure.
public function store(Request $request)
{
// return $request;
$request->validate(
[
"firstName" => 'required',
"lastName" => 'required',
"phoneNo" => 'required',
"email" => 'email:rfc,dns'
]
);
$date = date(now());
$data = [
'firstName' => $request->firstName,
'lastName' => $request->lastName,
'phoneNo' => $request->phoneNo,
'email' => $request->email,
'designation' => $request->designation,
'status' => $request->status,
'createdAt' => $date,
'updatedAt' => $date,
];
$user = Firebase::insertData($data, static::$collection);
if ($user->id() != null) {
$message = "User Created Successfully";
} else {
$message = "Something went wrong. Please contact System Admin with error code USR001";
}
return redirect()->route('users.index', ['message' => $message]);
}
This will redirect to the index method of the same controller. How can I use the $message parameter in the index method and send it to the view? My index method is below
public function index()
{
$userCollection = app('firebase.firestore')->database()->collection('users');
$userData = $userCollection->documents();
$response = [];
$app = app();
foreach ($userData as $data) {
$user = $app->make('stdClass');
$user->firstName = $data["firstName"];
$user->lastName = $data["lastName"];
$user->phoneNo = $data["phoneNo"];
$user->email = $data["email"];
$user->designation = $data["designation"];
$user->status = $data["status"];
$user->createdAt = $data["createdAt"];
$user->updatedAt = $data["updatedAt"];
array_push($response, $user);
}
return view('pages.user.list-user', ['response' => $response]);
}
You can directly pass the message as a flash message using the with() method with the redirect method.
Edit your redirect code as:
return redirect()->route('users.index')->with('message', $message]);
and add the below code in your pages.user.list-user blade file:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
Visit https://laravel.com/docs/8.x/redirects#redirecting-with-flashed-session-data for more info on redirects with a flash message.
Replace your redirect code :
return redirect()->route('users.index', ['message' => $message]);
with
return view('pages.user.list-user', ['message' => $message]);
(1) First of all, pass the message in the parameter of index function:
public function index($message)
{
...
}
(2) This is okay, you wrote correctly:
return redirect()->route('users.index', ['message' => $message]);
(3) Now just access the message in the view (blade) and print it:
{{ $message }}
You can also store message in $response array and simply pass the $response to the desired view:
$response['message'] = $message;
You can have the index method like if the parameter used in the controller.
public function index(Request $request)
{
// Your code
$message = $request['message'];
}
If you want to access the message in view use
return redirect()->route('users.index')->with('message', $message]);
and access from the view using session('message') like in OMi Shah's answer

Get Userdata from database by Login Sessions Codeigniter 3

i'm trying to make a login system. When user already login it will show user personal data like name, email or something. I'm try to modify the login code but doesn't work. Maybe someone can help.
Here is my code.
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Model_user');
$this->load->library('form_validation');
}
public function index()
{
$this->load->view('user/user_login');
}
function aksi_login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$where = array(
'username' => $username,
'password' => $password,
'status' => 1
);
$cek = $this->Model_user->cek_login('tb_user',$where)->num_rows();
if($cek > 0){
$data_session = array(
'username' => $username,
'status' => "userlogin"
);
$this->session->set_userdata($data_session);
redirect('user/user_dash');
}else{
$this->session->set_flashdata('flash_data', '<div class="alert alert-danger" role="alert" style="font-size:12px">
<center><b>Sorry !!</b> Username / Password is not correct.
</center>
</div>');
redirect('user/user_login');
}
}
function logout(){
$this->session->sess_destroy();
redirect('user/user_login');
}
}?>
Model
function cek_login($table,$where){
return $this->db->get_where($table,$where);
}
I'm can make username session appear,
<?php echo $this->session->userdata('username') ?> it's working.
But try to show name it doesnt appear. Appreciate any kind help. Thank you
You can try something like this.
$query = $this->Model_user->cek_login('tb_user',$where);
if($query->num_rows() > 0){
$user = $query->row();
$data_session = array(
'username' => $username,
'status' => "userlogin",
'name' => $user->name,
);
$this->session->set_userdata($data_session);
redirect('user/user_dash');
} {
$this->session->set_flashdata('flash_data', '<div class="alert alert-danger" role="alert" style="font-size:12px">
<center><b>Sorry !!</b> Username / Password is not correct.
</center>
</div>');
redirect('user/user_login');
}
For this to work, there must be a name column in the table tb_user
You need to store the full name in the session too.
Try editing this
$cek = $this->Model_user->cek_login('tb_user',$where)->num_rows();
if($cek > 0){
$data_session = array(
'username' => $username,
'status' => "userlogin"
);
to this
$cek = $this->Model_user->cek_login('tb_user',$where);
if($cek->num_rows() == 1){
$row=$cek->result_array()[0]; //returns an array of results, pick the first
$data_session = array(
'fullname' => $row['fullname'], //assuming column name is 'fullname'
'username' => $username,
'status' => "userlogin",
);

codeigniter login Cannot modify header information

I test on my localhost is working well and now show any error but after upload to the godaddy server. it is codeigniter version 2.2.6.
this error show in the login page.
Error Message 1
Message: Cannot modify header information - headers already sent by (output started at /home/user/public_html/ngapali/test/application/controllers/admin/user.php:1)
Filename: libraries/Session.php
Line Number: 433
Error Message 2
Message: Cannot modify header information - headers already sent by (output started at /home/user/public_html/ngapali/test/application/controllers/admin/user.php:1)
Filename: libraries/Session.php
Line Number: 689
Admin Controller of My Controller
<?php
class Admin_Controller extends MY_Controller{
function __construct(){
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('user_m');
$this->load->model('roomtype_m');
$this->load->model('room_m');
$this->load->model('roomcapacity_m');
//login check
$exception_uris = array(
'admin/user/login',
'admin/user/logout'
);
if(in_array(uri_string(), $exception_uris) == FALSE) {
if($this->user_m->loggedin() == FALSE) {
redirect('admin/user/login');
}
}
}}?>
My login page /user/login
Controller
<?php
class User extends Admin_Controller {
function __construct(){
parent::__construct();
}
public function index() {
$this->data['users'] = $this->user_m->get();
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main',$this->data);
}
public function login() {
$dashboard = 'l0gadmin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == TRUE){
if($this->user_m->login() == TRUE){
redirect($dashboard);
}else{
$this->session->set_flashdata('error','That email/password combination does not exist ');
redirect('admin/user/login','refresh');
}
}
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal',$this->data);
}
public function logout(){
$this->user_m->logout();
redirect('admin/user/login');
}}?>
Model
<?php
class User_m extends MY_Model {
function __construct(){
parent::__construct();
}
public function login(){
$user = $this->get_by(array(
'email'=> $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
),TRUE);
if(count($user)){
$data = array(
'name'=> $user->name,
'email' => $user->email,
'id'=> $user->id,
'loggedin'=>TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout(){
$this->session->sess_destroy();
}
public function loggedin(){
return (bool) $this->session->userdata('loggedin');
}
public function hash($string){
return hash('sha512', $string . config_item('encryption_key'));
}}?>
View Page of login
<div class="row">
<div class="col-md-3">
<h2>Admin Login</h2>
<?php
echo validation_errors();
echo form_open('');
$email = array(
'name' => 'email',
'class' => 'form-control',
'placeholder' => 'Email Address'
);
echo form_input($email) . "<br/>";
$password = array(
'name' => 'password',
'class' => 'form-control',
'placeholder' => 'Password'
);
echo form_password($password) . "<br/>";
$submit = array(
'name' => 'submit',
'class' => 'form-control btn btn-primary',
'value' => 'Login'
);
echo form_submit($submit);
echo form_close();
?>
</div>
</div>
i search this problem can be of open and closed tag. I try to add all the page but it still show error. Why?.
Read the error message:
output started at
/home/user/public_html/ngapali/test/application/controllers/admin/user.php:1
/user.php file has some blank character on line 1
check for any blank space before <?php tag.
Remove it and refresh error will be go away.
One more suggestion,
Omit ending php tags ?> in controller and model files.
Read more here : Why would one omit the close tag?
This is most probably because there occured an error or warning, which is not visible because of your current display_errors setting. I would suggest turning it on in order to fix these errors/warnings.

Check if user is not active, not to log in

I want to add condition for my login form - if a user is not already active, not to log in. I'm using CodeIgniter. That's my controller:
public function login ()
{
$this->load->model('user_model');
$user=$this->user_model->login();
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_login_check');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run()==FALSE)
{
$this->index();
}
else
{
if(count($user) > 0 )
{
$this->load->library('session');
$data = array(
'username' => $user['username'],
'user_id' => $user['user_id'],
'is_logged_in' => TRUE,
'role_id' => $user['role_id']
);
$this->session->set_userdata($data);
redirect('index/home_page');
}
}
}
My model is:
public function login()
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $this->input->post('username'));
$this->db->where('password',sha1($this->input->post('password')));
//$this->db->where('deactivated_at = "0000-00-00 00:00:00" OR deactivated_at IS NULL');
$result=$this->db->get();
return $result->row_array();
}
I have tried with this: $this->db->where('deactivated_at = "0000-00-00 00:00:00" OR deactivated_at IS NULL'); in my login function, but it does not work. How could I make this authentication, if not active user, not to log in at all?
There's a few things I would say is wrong with your code.
First off, you're trying to login the user before the form validation has completed. This should be done afterwards, or I don't see the need for validation?
This would be my version of your login function, within your controller.
function login()
{
$this->load->model('users_model');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if (!$this->form_validation->run())
{
$this->index(); // Show the login form..
}
else
{
// This is where we try to login the user, now the validation has passed
if ($user = $this->users_model->login())
{
// Start the session...
}
else
{
// The model returned false..
}
}
}
So you don't go to the model, until the form validation has passed. Then, in your model;
function login()
{
$where = array(
'username' => $this->input->post('username'),
'password' => sha1($this->input->post('password'))
);
// $this->db->select('*'); No need for this line
$query = $this->db->get_where('users', $where);
if ($query->num_rows() > 0)
{
// Found a match
// Are they activated?
if (!is_null($query->row('deactivated_at'))
{
// The user isn't deactivated
return $query->row_array();
}
else
{
// The user is deactivated
return false;
}
}
else
{
// The username and/or password is wrong...
return false;
}
}
Hope this helps.

Resources