abbood
abbood

Reputation: 23548

How to give a user a single session extra permission in Django

Background

We have a service where a django super admin can login and view all the users in a specific org, and this super admin can "log in" in the place of that user. Ie suppose we have

super admin = joe
users = mike, abe, tony

then joe can log into an org, see mike, abe and tony, then joe can login into the system as if they are mike. Everything they see and do will be as if Mike were doing it. So if the super admin has permission to create public events, but mike doesn't, when the super admin logs in as mike, they won't be able to create events either.

So far so good.

However we realized that in many cases we would like the super admin to login as mike, and still be recognized as a super admin in the system. This is useful for data migration purposes, ie sometimes the super admin should actually do stuff in the name of mike that mike can't do themselves.

Problem

the idea here is that I would like the system to recognize that super admin is logged in as mike. However all questions I saw online (such as this one) are more about assigning permanent permissions (ie by storing them in the db), rather than temporary/ephemeral ones.

This is the code that gets called when the admin clicks on the login button beside mike:

class LoginAsView(APIView):
    permission_classes = []

    def get(self, request, *args, **kwargs):
        if request.user.is_superuser and 'username' in request.GET:
            user = User.objects.get(email=request.GET['username'])
            user.backend = settings.AUTHENTICATION_BACKENDS[0]
            login(self.request, user)
            return Response('/', 302, headers={'Location': '/'})
        raise PermissionDenied('NO U')

so as you can see the user I'm retrieving behaves exactly as if that user (ie mike) logged in organically. I would like in this method to assign mike some temporary special permissions that allows mike to do things he normally cannot.

Upvotes: 1

Views: 662

Answers (1)

abbood
abbood

Reputation: 23548

enter https://github.com/arteria/django-hijack

for example django-hijack add extra flag to session for checking is user hijacked https://github.com/arteria/django-hijack/search?utf8=%E2%9C%93&q=is_hijacked_user

Upvotes: 1

Related Questions