Programmatically logout current user - session

I am trying to programmatically logout the current user from inside a listener.
I read here that
$this->get('security.context')->setToken(null);
$this->get('request')->getSession()->invalidate();
does the trick but then I can't call $this->container->get('security.context')->getToken()->getUser(); anymore as the token is now NULL.
How can I log out the user but still let the application run normally?
I have calls to getUser() in my controller functions so I should set back the token to something corresponding to an non authenticated user. How can I do this?
Also, if there is a way to programmatically start a new session and set a flash message to inform the user he has been logged out, it would be awesome.

Try
$anonToken = new AnonymousToken('theTokensKey', 'anon.', array());
$this->get('security.context')->setToken($anonToken);
first parameter is the token's key (i.e. '50cdf89882454')

Related

How to login a user at backend without CSRF in Laravel?

I'm trying to make a user logged in at back-end who is already a user of another website of mine. For now I'm able to fetch the user's data from previous website's database using an API and make user registration during the login process. Same time I want this user to be logged in when data is just inserted because now user is existing. I tried to reuse same method $this->processLogin(); but this method takes request function processLogin(Request $request) I can't feel passing email & pass to utilize this same method. I have tried guzzle self request with 3 parms 'email, password, _token' using POST request which didn't work. I don't want to exclude this route as well because it is being used for normal login. How can i make this user logged in right after inserting the required data? Please advise. Thanks in advance.
// if $id is your user that you want to login, then:
auth()->loginUsingId($id);

Laravel Session does not deleted when using flush() or forget()

I'm trying to create an api which use a Session variable. This what I did:
Login
return auth('api')->attempt($credentials);
Call an api which save a variable test to Session
Session::put('test', $venueId);
Log out. In logoutController, call Session::flush() (I tried with Session::forget('test') too).
Session::flush();
// Session::forget('test');
auth()->logout();
Login again.
Call Session:all() in a randomly api. => Variable test still there.
I've checked in database, when I use auth()->logout() in controller, database create a new session in sessions table which has payload same with payload in step 2. And when I login again, it seems to use 2nd session (which created after logged out in step 3) to get value.
How can I handler this? I want all session to be flushed after user logout
I found out problem. I've used multi authentication, so I have 2 logout controller and I put Session::flush() to wrong controller. Put Session::flush() into correct controller and it worked.

CakePHP: When I change User session i get logout

I need to add possibility of Admin to enter User account, but i stucked when i change session data, i got logout.
$_SESSION['Auth']['User']['username']=$user_data['User']['username'];
To come back into admin session I made new variable
$_SESSION['Auth']['Admin']['id']=$user_id
Please help me to change admin data into user, and add possibility to come back as admin when logout
To login as a user when your are admin you can do this:
In your controller:
$user = $this->User->findById($idOfUserYouWantToLoginAs);
... // handle case where $user is empty
$this->Auth->login($user['User']);
Or you could just change the variables in the session as needed. I did it yesterday just changing the id of the logged user, but you can also change the stored username or email address or anything on session:
$this->Session->write('Auth.User.id',$newLoggedUserId);
$this->Session->write('Auth.User.username',$newLoggedUserName);
$this->Session->write('Auth.User.email',$newLoggedUserEmail);

How to implement one controller mapping method for different scenarios

I have a spring controller method which could be called in different scenarios. here is the example...
#RequestMapping("/resetpassword")
public ModelAndView resetpassword( #Valid #ModelAttribute("resetpasswordForm") ResetPawdFormForm resetPawdFormForm, ModelAndView modelAndView){
... this method could be executed in 3 different scenarios....
using the hyper link coming from the user reset password link sent to user email..
eg: localhost/myApp/login/resetpassword//
Here I can authenticate userID and activationSecretCode in DB and let user reset password
user can click on resetpassword link from user settings page.
eg: Since the user is already coming from user settings page, I can validate userSession and allow him to reset password
User can login for first time successfully, but are forced to reset password due to admin requirements for reset initial default password.
eg: in this user neither have session, nor passing any activationcode to validate.
login method validates userid/default password and redirects to resetpassword mapping(method=GET).
How can the system authenticate the user request and allow him to reset password?
One alternative for this is, to use flash attributes and set a authenticationKey as flash attributes...which could be verified in resetpassword method.
is there other way to implement this....
Note: I posted an issue in implementing this approach in
Post: Spring: How to pass Java objects during redirect while using ModelAttribute
Any help?
I think the best way to implement this is using three different action methods:
resetPassword (e-mails)
resetLoggedUserPassword (via settings)
changeDefaultPassword
They may even share the same view, but the behaviors are not equal, so I would avoid overloading the action responsibility.
EDIT: elaborating on your comment:
1) To secure the e-mail link, one way is to add a authentication token. The token can be as weak as a hashed user id plus some salt string, or as strong as a GUID with expiration time in a database table, generated whenever a user requests a password reset.
2) The settings way is not a problem, considering that the user is already logged in.
3) The temporary password action can be secured the same way as 1, or the same way as 2, if you put the user on the session. Logging in the user even with the default password status shouldn't be a concern if the code that verify the status of the account are inside a request filter.

Logging out user at session expiry with tank auth & Codeigniter

I use tank_auth to authenticate and log users in to my application developed using Codeigniter. I noticed that when the session expires after the default period, the user remains logged in. In tank_auth's login() function,
if ($this->tank_auth->is_logged_in())
check at the very beginning always returns true.
I'd like to log the user out when the session expires. Please could you point me in the right direction to implement this?
Thanks!
Mmiz

Resources