Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

utils: add support for user impersonation #60

Merged
merged 1 commit into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion flask_security/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
RegisterForm, ResetPasswordForm
from .signals import confirm_instructions_sent, password_reset, \
reset_password_instructions_sent, user_confirmed, user_registered
from .utils import login_user, logout_user, url_for_security
from .utils import impersonate_user, login_user, logout_user, url_for_security

__version__ = '3.3.1'
__all__ = (
Expand All @@ -45,6 +45,7 @@
'ConfirmRegisterForm',
'current_user',
'ForgotPasswordForm',
'impersonate_user',
'login_required',
'login_user',
'LoginForm',
Expand Down
20 changes: 20 additions & 0 deletions flask_security/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,26 @@ def _(translate):
return translate


def impersonate_user(user, impersonator_idty):
"""Impersonate a user.

Logouts the current user, and login the new user.

Can login inactive users and doesn't track login time.
"""
logout_user()

session["_impersonator_id"] = impersonator_idty.id
if not _login_user(user, force=True):
if "_impersonator_id" in session:
session.pop("_impersonator_id")
return False

identity_changed.send(current_app._get_current_object(),
identity=Identity(user.id))
return True


def login_user(user, **kwargs):
"""Perform the login routine.

Expand Down
14 changes: 12 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,16 @@
from json import JSONEncoder as BaseEncoder

import pytest
from flask import Flask, render_template
from flask import Flask, current_app, render_template
from flask_babel import Babel
from flask_mail import Mail
from speaklater import is_lazy_string
from utils import Response, populate_data

from flask_security import RoleMixin, Security, \
SQLAlchemySessionUserDatastore, SQLAlchemyUserDatastore, UserMixin, \
auth_required, login_required, roles_accepted, roles_required
auth_required, impersonate_user, login_required, roles_accepted, \
roles_required


class JSONEncoder(BaseEncoder):
Expand Down Expand Up @@ -125,6 +126,15 @@ def unauthorized():
def page_1():
return "Page 1"

@login_required
@app.route("/impersonate/<user>", methods=["POST"])
def impersonate(user):
from flask import g
user = current_app.security.datastore.get_user(user)

impersonate_user(user, g.identity)
return "Page 1"

def delete_user_from_g(exception):
"""Delete user from `flask.g` when the request is tearing down.
Flask-login==0.6.2 changed the way the user is saved i.e uses `flask.g`.
Expand Down
12 changes: 12 additions & 0 deletions tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,15 @@ def test_user_deleted_during_session_reverts_to_anonymous_user(app, client):

response = client.get('/')
assert b'Hello [email protected]' not in response.data

def test_impersonate_user(app, client):
authenticate(client)
response = client.get('/')
assert b'Hello [email protected]' in response.data

# Impersonate
client.post('/impersonate/[email protected]')

response = client.get('/')
assert b'Hello [email protected]' not in response.data
assert b'Hello [email protected]' in response.data
Loading