def reissue_cookie_session(request, user_id='', su='', org=None, after=0, TokenClass=SessionToken, **kwargs): """Invalidate previous cookie session and issue a fresh one Params `user_id` and `su` can be instances of `User`, `user_id`s or emails. """ # First invalidate the current empty session session = session_from_request(request) if not isinstance(session, SessionToken): raise Exception("Can not reissue an API token session.") if after: revoke_token.apply_async(args=(session.token, ), countdown=after) else: session.invalidate() session.save() kwargs.update({ 'ip_address': mist.api.helpers.ip_from_request(request), 'user_agent': request.user_agent, }) # And then issue the new session new_session = TokenClass(**kwargs) # Pass on fingerprint & experiment choice to new session if session.fingerprint: new_session.fingerprint = session.fingerprint if session.experiment: new_session.experiment = session.experiment if session.choice: new_session.choice = session.choice session = new_session if user_id or su: # A user will be set to the session user_for_session = su if su else user_id user_is_effective = not user_id if isinstance(user_for_session, string_types): # Get the user object if an id has been provided if '@' in user_for_session: user_for_session = User.objects.get(email=user_for_session) else: user_for_session = User.objects.get(id=user_for_session) session.set_user(user_for_session, effective=user_is_effective) if not org: # If no org is provided then get the org from the last session old_session = SessionToken.objects( user_id=user_for_session.id).first() if old_session and old_session.org and \ user_for_session in old_session.org.members: # if the old session has an organization and user is still a # member of that organization then use that context org = old_session.org else: # If there is no previous session just get the first # organization that the user is a member of. orgs = Organization.objects(members=user_for_session) if len(orgs) > 0: org = orgs.first() else: # if for some reason the user is not a member of any # existing organization then create an anonymous one now from mist.api.users.methods import create_org_for_user org = create_org_for_user(user_for_session) session.org = org session.su = su session.save() request.environ['session'] = session return session