Manually logging in a user without password

前端 未结 5 2019
暖寄归人
暖寄归人 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条回答
  •  旧时难觅i
    2020-12-07 10:51

    You don't need a password to log a user in. The auth.login function just takes a User object, which you are presumably already getting from the database when you enable the account. So you can pass that straight to login.

    Of course, you'll need to be very careful that there's no way a user can spoof a link to an existing already-enabled account, which would then automatically log them in as that user.

    from django.contrib.auth import login
    
    def activate_account(request, hash):
        account = get_account_from_hash(hash)
        if not account.is_active:
            account.activate()
            account.save()
            user = account.user
            login(request, user)
    

    ... etc.

    Edited:

    Hmm, didn't notice that requirement to use authenticate because of the extra property it adds. Looking at the code, all it does is a backend attribute equivalent to the module path of the authenticating backend. So you could just fake it - before the login call above, do this:

    user.backend = 'django.contrib.auth.backends.ModelBackend'
    

提交回复
热议问题