Session create by ajax but destroyed when page refresh in codeigniter - ajax

I have create session using ajax in a page but it destroyed when i refresh that page in codeigniter. When i print this session data it will return null.
controler code for create session(through ajax)
public function check_database() {
$username =$this->input->post('username');
$password =$this->input->post('password');
$result = $this->Api_model->login($username, $password);
if ($result) {
$sess_array = array();
foreach ($result as $data) {
$sess_array = array( 'id' => $data->id, 'username' => $data->user_name,
'type' =>$data->type, 'email' => $data->email, 'phone' => $data->mobile
);
$this->session->set_userdata('admin_logged_in', $sess_array);
}
$session_data = $this->session->userdata('admin_logged_in');
print_r(Json_encode($session_data));
} else {
echo 0;
} }
session check method
function ourservice() {
$session_data = $this->session->userdata('admin_logged_in');
$ids = $session_data['id'];
$this->load->view('our_service');
}
After create session by ajax call, i will check session by ajax call also and it retun session value,but when i refresh my codeigniter page and check session on page load event it will return null also if i check session in another function in controller it also return null.

Related

Store the login details in session in laravel

I have a function in controller checklogin() which checks the user details. I want to store into session. So I can get the name of the user and display in blade view
Controller
public function checklogin(Request $request)
{
$req=$request->validate([
'name'=>'required',
'email'=>'required|email',
'password'=>'required|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[#_!]){8,}/'
]);
$userdata = array(
'name' => $request->input('name') ,
'email'=>$request->input('email'),
'password' => $request->input('password')
);
if (Auth::attempt($userdata))
{
$data = $request->session()->put('user',$userdata['name']);
dd($data) ; //returning null
return redirect('/home');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
No need to store logged in user detail in session.You can call auth helper function which will return auth instance.
{{auth()->user()->name}}
if you have both logged in or guest page same then you can do null check
{{ auth()->user()!=null?auth()->user()->name:null }}

Authorise a user with Laravel Passport when testing RESTful controllers update method

Every time I run the test, I'm getting a 403 response status, what am I doing wrong in here?
I have tried to remove Passport authorization from the test, but then I'm getting a redirect to a login page, 302 status response.
//PostTest:
public function test_can_update_post()
{
//creating a user
$user = factory(User::class)->create();
//creating an author for post
$author = factory(Author::class)->create([
'user_id' => $user->id,
]);
//creating a post
$post = factory(Post::class)->create([
'author_id' => $author->id,
]);
$data = [
'title' => $this->faker->title,
'content' => $this->faker->paragraph,
];
//authorizing user
//I have tried to remove this line, then I'm gettig a redirect to login page 302
$user = Passport::actingAs($user);
$this->actingAs($user)
->patch(route('posts.update', $post->id), $data)
->assertStatus(200);// why I'm getting 403???
}
//API route:
Route::patch('posts/{post}')
->uses('PostController#update')
->middleware('auth:api')
->name('posts.update');
//PostController update method:
public function update(PostUpdateRequest $request, Post $post)
{
$this->authorize('update', $post);
$post->title = $request->input('title');
$post->content = $request->input('content');
$post->save();
return new PostResource($post);
}
//PostPolocy
public function update(User $user, Post $post)
{
return Author::where('user_id', $user->id)->first()->id === $post->author_id;
}
I expect response status 200
I have changed the line in PostPolicy update method to:
if(!$user->author) {
return false;
}
return $user->author->id == $post->author_id;
This worked for me.

Codeigniter 3 login check function not showing correct flashdata messages

I am creating a login check function. But my two flash data messages are not setting correct.
If user has logged on and then if the session expires it should set this
flash data message Your session token has expired!
And if the user has not logged on and tries to access a controller with out logging on
then it should set this flashdata message You need to login to
access this site!
For some reason it is always showing the second flashdata message.
Question: How am I able to use the two flashdata messages properly.
Controller: Login.php
Function: check
public function check() {
$uri_route = basename($this->router->directory) .'/'. $this->router->fetch_class();
$route = isset($uri_route) ? $uri_route : '';
$ignore = array(
'common/login',
'common/forgotten',
'common/reset'
);
if (!in_array($route, $ignore)) {
// $this->user->is_logged() returns the user id
if ($this->user->is_logged()) {
// $this->session->userdata('is_logged') returns true or false
if (!$this->session->userdata('is_logged')) {
// Redirects if the user is logged on and session has expired!
$this->session->set_flashdata('warning', 'Your session token has expired!');
redirect('admin/common/login');
}
} else {
$this->session->set_flashdata('warning', 'You need to login to access this site!');
redirect('admin/common/login');
}
}
I run function via codeigniter hook that way I do not have to add it on every controller.
$hook['pre_controller'] = array(
'class' => 'Login',
'function' => 'check',
'filename' => 'Login.php',
'filepath' => 'modules/admin/controllers/common'
);
What are you trying to check via the uri() is actually a very bad way of checking, also you should include login checks as a construct function not single.. here is what your function should look like:
function __construct()
{
parent::__construct();
if (!$this->session->userdata('logged_in')) {
// Allow some methods?
$allowed = array(
'some_method_in_this_controller',
'other_method_in_this_controller',
);
if (!in_array($this->router->fetch_method(), $allowed)
{
redirect('login');
}
}
}

$this->session->unset_userdata not working?

So I have this login method:
public function login(){
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('password','Username','trim|required|min_length[4]|xss_clean');
if($this->form_validation->run()== FALSE) {
//Loading View
$this->load->view('admin/layouts/login');
$username = $this->input->post('username');
$password = $this->input->post('password');
//Validate Username & Password
$user_id = $this->Authenticate_model->login($username, $password);
if($user_id){
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
//Set session userdata
$this->session->set_userdata($user_data);
} else {
//Set message
$this->session->set_flashdata('pass_login', 'You are now logged in');
redirect('admin/dashboard');
}
}
}
And then i use this simple method to logout:
public function logout(){
//Unset User Data
$this->session->unset_userdata('user_id');
$this->session->unset_userdata('username');
$this->session->unset_userdata('logged_in');
$this->session->sess_destroy();
redirect('admin/authenticate/login');
}
So basically I'm unsetting all my sessions userdata and then redirecting back to login controller. And what happens is, when i redirect back to login page, I automatically login again, like if my session data was still valid and present. Why it's happening?
You could try
unset($this->session->userdata('user_id'));
unset($this->session->userdata('logged_in'));
unset($this->session->userdata('username'));
Or Just Have
$this->session->sess_destroy();
Make sure your session library auto loaded and have configured your settings depending on version of codeigniter
maybe you place "redirect if session == true" code at __construct, there is my problem :v

Show error message after a page refresh

I have a login form that I'm doing 2 part validations: The client-side and the server side.
Client-side: check if valid email, check if password is minimal 6 characters, etc. If something goes wrong on the client-side I can show the user the error messages on the same page with the login form, because it page never got reloaded because it will not send a post to the server if the client-side validation isn't true.
But when it is true, then I'm doing a server side validation -> check if email and password matches to effectively log in into the website. But if the login credentials aren't matching, I need to show a error message. This is the part where I'm stuck. Where and how do I get a message on the same page (login form) because page gets posted and refreshed so I'm losing data. Now when credentials aren't correct I'm redirecting the user back to the login page, but without any messages. But I'm trying to achieve that he'll see the message 'credentials aren't correct'. Can someone help me with this?
Login View
<?php
$loginEmail = array('placeholder' => "Email", 'name' => "loginEmail");
$loginPassword = array('placeholder' => "Wachtwoord", 'name' => "loginPassword");
$loginSubmit = array('name' => "loginSubmit", 'class' => "btn", 'value' => "Inloggen");
echo form_open('login/inloggen', array('class' => 'grid-100 formc'));
echo form_input($loginEmail, set_value('loginEmail'));
echo form_password($loginPassword);
echo form_submit($loginSubmit);
echo form_close();
?>
Login Controller
function index(){
$logged_in = $this->logged_in->is_logged_in();
if($logged_in){
$this->load->view('profile_view');
}
else{
$data['content'] = 'login_view';
$this->load->view('templates/template', $data);
}
}
function inloggen(){
if($this->input->post('loginSubmit')){
if($this->form_validation->run('login_validation_rules') == FALSE){
$this->index();
}
else{
$this->load->model('login_model');
$query = $this->login_model->validate();
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile');
}
else{
$this->index();// If credentials aren't correct, redirect them to login page. But how I set a message here?
}
}
}
}
Login Model
function validate(){
$this->db->where('email', $this->input->post('loginEmail'));
$this->db->where('password', md5($this->input->post('loginPassword')));
$query = $this->db->get('tbl_users');
if($query->num_rows == 1){
return true;
}
else{
return false;
}
}
I will prefer do to in one controller, and it will be more clear. I make one simple example, just to tell you the way how I think is good.
function login(){
$data['error_message'] = "";
$data['username'] = $this->input->post('username');
$data['password'] = $this->input->post('password');
if($this->input->post('loginSubmit')){
// Make rules of validation that need to be required
if($this->form_validation->run('login_validation_rules')){ // If true it goes IN
$this->load->model('login_model');
$query = $this->login_model->validate();
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile'); // Go IN profile
} else {
$data['error_message'] = "Something went wrong"; // This error you write on View
}
}
}
$this->load->view('login_view', $data) //Load view of login
}
I didn't test, and it will need to adapt in your data, but I just want to explain the way. It you have any problem, write an comment, and we will find the solution together.
I have solved this problem like so: Basically when the model sends a false. I make var with a message in it and then in my index I check if that var is there or not.
The only thing I want to know is, is it okay to set a message in my controller or should I have done that somewhere elsewhere??
function index(){
$logged_in = $this->logged_in->is_logged_in();
if($logged_in){
$this->load->view('profile_view');
}
else{
//Check here if my redirection submitted also a message
if(isset($this->ongeldig)){
$data['ongeldig'] = $this->ongeldig;
}
else{
$data['ongeldig'] = '';
}
$data['content'] = 'login_view';
$this->load->view('templates/template', $data);
}
}
function inloggen(){
if($this->input->post('loginSubmit')){
if($this->form_validation->run('login_validation_rules')){
$this->load->model('login_model');
$query = $this->login_model->validate();
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile');
}
else{// set a error message, when the models function returns false.
$this->ongeldig = "Ongeldig wachtwoord/gebruikersnaam";
$this->index();
}
}
else{
$this->index();
}
}
}

Resources