Manually logging in a user without password

前端 未结 5 1994
暖寄归人
暖寄归人 2020-12-07 10:18

I hope you can help me figure the best way to implement a manual (server-side initiated) login without using the password. Let me explain the workflow:

5条回答
  •  死守一世寂寞
    2020-12-07 10:58

    Daniel's answer is very good.

    Another way to do it is to create a HashModelBackend following the Custom Authorization backends https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#writing-an-authentication-backend like this:

    class HashModelBackend(object):
        def authenticate(self, hash=None):
            user = get_user_from_hash(hash)
            return user
    
        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    

    And then install this in your settings:

    AUTHENTICATION_BACKENDS = (
        'myproject.backends.HashModelBackend',
        'django.contrib.auth.backends.ModelBackend',
    )
    

    Then your view would be something like this:

    def activate_account(request, hash):
        user = authenticate(hash=hash)
        if user:
            # check if user is_active, and any other checks
            login(request, user)
        else:
            return user_not_found_bad_hash_message
    

提交回复
热议问题