def prevent_user_last_login(self): """ Disconnect last login signal """ from django.contrib.auth import user_logged_in from django.contrib.auth.models import update_last_login user_logged_in.disconnect(update_last_login)
def login_as_user(request, user_id): userobj = authenticate(su=True, user_id=user_id) if not userobj: raise Http404("User not found") exit_users_pk = request.session.get("exit_users_pk", default=[]) exit_users_pk.append( (request.session[SESSION_KEY], request.session[BACKEND_SESSION_KEY])) user_logged_in.disconnect(update_last_login) try: if not custom_login_action(request, userobj): login(request, userobj) finally: user_logged_in.connect(update_last_login) request.session["exit_users_pk"] = exit_users_pk if hasattr(settings, 'SU_REDIRECT_LOGIN'): warnings.warn( "SU_REDIRECT_LOGIN is deprecated, use SU_LOGIN_REDIRECT_URL", DeprecationWarning, ) return HttpResponseRedirect( getattr(settings, "SU_LOGIN_REDIRECT_URL", "/"))
def login_as_user(request, user_id): userobj = authenticate(su=True, user_id=user_id) if not userobj: raise Http404("User not found") exit_users_pk = request.session.get("exit_users_pk", default=[]) exit_users_pk.append( (request.session[SESSION_KEY], request.session[BACKEND_SESSION_KEY])) user_logged_in.disconnect(update_last_login) try: if not custom_login_action(request, userobj): login(request, userobj) finally: user_logged_in.connect(update_last_login) request.session["exit_users_pk"] = exit_users_pk if hasattr(settings, 'SU_REDIRECT_LOGIN'): warnings.warn( "SU_REDIRECT_LOGIN is deprecated, use SU_LOGIN_REDIRECT_URL", DeprecationWarning, ) return HttpResponseRedirect(getattr(settings, "SU_LOGIN_REDIRECT_URL", "/"))
def impersonate(request, user_id): """ Allows a superuser to impersonate another user. """ admin_user = request.user user = User.objects.get(id=user_id) # Login as the specified user user.backend = 'django.contrib.auth.backends.ModelBackend' user_logged_in.disconnect(update_last_login) login(request, user) user_logged_in.connect(update_last_login) request.session[IMPERSONATED_BY_KEY] = admin_user.id request.session[IMPERSONATING_KEY] = user.id messages.success(request, 'Impersonation successful.') return HttpResponseRedirect(reverse('home'))