1

In addition to the normal login route (UserSessionsController.create) I have a special route in a different controller that does a bunch of other stuff including creating a new user and I would like to be able to log in as that newly created user. To run this route you have to already be logged in, so I would like to destroy the current session and create a new session with the new user.

Pulling from the existing routes that work I have put together this code:

  @user_session = UserSession.find
  @user_session.destroy

  @user_session = UserSession.new({email: new_user.email, password: new_user.password})
  @user_session.save!

  redirect_to value_chain_hierarchy_path(new_business_entity)

Because the user was just created, we still have access to their password. Stepping through this code with a debugger I can see that the current session gets destroyed (has a nil user) and when I save the new session and ask for its user I get the new user back, but when the page loads I'm still logged in as the previous user.

I'm pretty stumped. I'm guessing it has something to do with updating the session cookies or something like that. But I don't know what to try next.

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
markv12
  • 334
  • 1
  • 11
  • Based on this answer: https://stackoverflow.com/questions/2279248/authlogic-and-multiple-sessions-for-the-same-user I am able to log the current user out by calling reset_persistence_token, but logging in as the new user still doesn't work. – markv12 Aug 09 '22 at 18:05
  • Authlogic has four persistence methods: params, cookies, session, and http_auth. Which are you trying to use? Most people use cookies or session, so you can try logging `cookies` and/or `session` throughout the process and observe the effects of `destroy` and `save`. – Jared Beck Aug 17 '22 at 18:16
  • @JaredBeck I'm using the cookie_store. But I have no idea why the same code works in UserSessionsController.create but doesn't work here. I'm guessing it's some magic behind the scenes in Authlogic. Totally making this up, but I'm imagining it's something like "outside of UserSessionsController you have to call .reset_session to persist the login" no idea though. – markv12 Aug 18 '22 at 21:17

0 Answers0