can not log out my users in codeigniter - codeigniter

By logic, once the users logged out, they cann't enter the system again till they login again.
I use some session data and cookies of the logged in users, and i want to delete this session data and cookies when the users logged out.
I use
delete_cookie("cookie_name");
$this->session->sess_destroy();
and also set the $config['sess_time_to_update'] ro 0
but this is didn't work, the session data and cookies didn't deleted.
What i can do to delete all session data and cookies once the user log out.

$this->session->sess_destroy();
should delete all the session data. How do you know that the session data wasn't deleted. just after sess_destroy(); try to echo one of the session data.
echo $this->session->userdata('item_name');
same way use echo after deleting a cookie like this-
echo get_cookie('cookie_name');
I believe, it's the logic of how user keep logged in. You are probably not checking whether the session exists for logged in user. You should check session and cookie for every page(method) the user visit. The best way to do this is to put the checker function in the constructor.

Try this -
http://php.net/manual/en/function.setcookie.php
// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
http://www.php.net/manual/en/function.setcookie.php#73484

Related

Laravel 7 loginUsingId not persisting / causing log out

I am trying to create a "Shadow" user feature, it's basically just to allow admins to log in as another user to use the system as the "shadowed user" would.
I've used Auth::loginUsingId before but i can't figure out why the below isn't working.
public function shadowUser($id, Request $request){
$user = User::query()->find($id);
$previousUserId = $request->user()->id;
Session()->flush();
Session()->put('shadow.user.id', $previousUserId);
$shadowedUser = Auth::loginUsingId($user->id);
dump(Auth::check());
return redirect()->route('home');
}
If I dump out the $shadowedUser it shows the correct user and the Auth::check() returns true.
I have also tried these but they made no difference: Auth::loginUsingId(1, true);, Auth::guard($guard)->loginUsingId($user->ID); and Auth::login($user, true);
There's no crazy middleware just laravel's defaults.
I've tried a few things like removing the session flush but it always just logs me out.
I found that Laravel sessions are a bit funky in this scenario, it looks like you're trying to log someone in when the session is already active, log the current user out, flush the session then log in the new user, this way it will tell Laravel that this is a new user signing in and reset the session.
In your script, once you've logged the user out, flushed the session and logged the new user in, add the previous users id to the new session otherwise it will get deleted then you'll be able to see the previous user who was logged in, or the person shadowing you in this case.
public function shadowUser($id, Request $request){
$user = User::query()->find($id);
$previousUserId = $request->user()->id;
Auth::logout($guard);
Session()->flush();
Auth::loginUsingId($user->id);
Session()->put('shadow.user.id', $previousUserId);
dump(Auth::check());
return redirect()->route('home');
}

Laravel 5.5 restrict duplicate login

I have overwritten Login and Logout functionality as I need to check many more conditions to authenticate the user like below.
public function login(Request $request)
{
$this->validateLogin($request);
$input=$request->all();
$user=User::where('username',$input['username'])->first();
//If Temp Password is set
if(strlen($user->temp_password)>10)
{
if (Hash::check($input['password'], $user->temp_password))
{
Auth::login($user);
$this->setUserSession($user);
$landing_page=Menu::find($user->landing_page);
return redirect()->route($landing_page->href);
}
else {
session()->put('failure','Invalid Username or Password');
return redirect('/login');
}
}
else{ //If Temp password is not set
if (Hash::check($input['password'], $user->password))
{
Auth::login($user);
$this->setUserSession($user);
$landing_page=Menu::find($user->landing_page);
return redirect()->route($landing_page->href);
}
else {
session()->put('failure','Invalid Username or Password');
return redirect('/login');
}
}
}
Now I need to restrict Same user from login once again in some other screen or place. I have checked Session Data but nothing is stored as Unique for a User.
ie. If a username admin is loged in US the same username admin must not be allowed to login from UK.
Update
Oh bagga, question wasn't quite clear. You are trying to restrict the number of sessions to 1 only. If I get it, then you will have to use a database session driver. Right now, I think you may be using the default driver (file). It only checks the session within the same browser. Using database session may allow you to check for session everywhere, and restrict the number of connections.
First, make sure your routes are within the web middleware so they can access sessions. Then, inside of the web middleware, create a group of routes that are only accessible for users who are not logged in.
Route::group(['middleware' => 'guest'], function () {
Route::get('login', 'LoginController#login');
// any other route
});
Logged in users won't be able to access the login route anymore.
You could also do the check in your login function to see if the user's is already connected by using
if (Auth::check()) {
// user is connected
// redirect them
}
What does this->setUserSession($user) do?
You can do this using login token.
Generate a login token and keep it in database.
And check for it's entry in database while logging in.
If it doesn't exist let log in success.
Else fail.
And delete login token every time user logs out.
Or
you can generate new token on each login success. And deleting old token and invalidating the old login.
But in this case you have to keep that token in session and for each request you have to check that token with database token.
If it matches, allow user
Else logout the user with notice.
I'll prefer the second method personally.
As you can check for the token in the middleware itself.

remember me for laravel5.2

Hello guys I want to make the remember me checkbox and I want to save the user info into cookies so next time when try to login he find the user name and password in their fields I try to use :
$rememberMe = false;
if(isset($req->remember_me)) {
$rememberMe = true;
}
if(Sentinel::authenticate($req->all(), $rememberMe)) {
$slug = Sentinel::getUser()->roles()->first()->slug();
}
The cookies was set, I see it in the chrome settings but it does not do as I expect
I'm using laravel 5.2
You can use Cookies
cookie, is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity
To create:
$response->withCookie(Cookie::make('name', 'value', $minutes));
To retrieve
$value = Cookie::get('name');
Your question is not to remember the user login.. The question is how to fill the inputs based on saved auth information. You can do that if you print the authentication values in the input value attribute while loading the page.
larval Cookies Docs
Also Laravel has it's own implementation of "Remember Me"
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
// The user is being remembered...
}
if (Auth::viaRemember())
{
//
}
More information about https://laravel.com/docs/5.4/authentication#remembering-users
There is two main thing need to taken care:
1) You must pass a bool value as second parameter to the method, make sure you cast it before passing it to the method. - In your code, it's perfect
$credentials = $req->only('LOGINNAME', 'PASSNAME')
if(Sentinel::authenticate($credentials , $req->has('remember_me'))){
//Other stuff
}
2) you can verify it works by ensuring a cookie is set with the key cartalyst_sentinel?
So first change as per 1) option and then check the 2) option, may be this is your answer.

Check existence of joomla session

I have tried to check sessions existence till user login in Joomla with JFactory::getSession(); but it's not working.
Also JFactory::getUser(); this method shows user ID after session lifetime expired.
Please let me know if any solutions are there to validate Joomla sessions.
You can use the following to get the Joomla session
$Jsession = JFactory::getSession();
$session = $Jsession->get('myVar');
and then perform a check if you wish, like so:
if($session) {
// session exists
}
else {
// session doesn't exist
}
As for showing the user ID, the ID will only show if the users is logged in as getUser() retrieves the current user object.

How to Destroy All Session With Exceptional in Codeigniter?

In my code, I have logout function as below
function logout()
{
$this->session->sess_destroy();
// but, don't destroy this session
$this->session->userdata('admin_id');
}
How to destroy all session, except 'admin_id'?
The Session destroy in CI is performed at the next request, so you can't destroy a session and open a new session without a request in between.
But you could unset all session data except the data you like to keep and the data Codeigniter needs to keep the session. This Depends how session is configured, by default is it the User Agent, the last activity and the session ID. See CI-Session class preferences (at bottom of page)
This function deletes all session data except the admin_id
$sessionData = $this->session->all_userdata();
foreach($sessionData as $key =>$val){
if($key!='session_id'
&& $key!='last_activity'
&& $key!='ip_address'
&& $key!='user_agent'
&& $key!='admin_id'){
$this->session->unset_userdata($key);
}
}
You might want to save the admin_id temporarily and just put it back to session after you destroyed all your session vars.
$temp = $this->session->userdata('admin_id');
$this->session->sess_destroy();
$this->session->set_userdata('admin_id', $temp);
you must save some of keys in session, here is correct code.
$sess_array = $this->session->all_userdata();
foreach($sess_array as $key =>$val){
if($key!='session_id'
&& $key!='last_activity'
&& $key!='ip_address'
&& $key!='user_agent'
&& $key!='RESERVER_KEY_HERE')$this->session->unset_userdata($key);
}
This will work for you :)
$this->session->sess_destroy(); destroys the session_id and last_activity of the session. So the session no longer exist. So this wont work.
Try this:
$sess_array = $this->session->all_userdata();
foreach($sess_array as $key =>$val){
if($key!='session_id'||$key!='last_activity'||$key!='admin_id'){
$this->session->unset_userdata($key);
}
}

Resources