#request.user is a instance of AnonymousUser even though sessionid is valid

15 messages · Page 1 of 1 (latest)

mossy cedar
#

So I was trying to get discord oauth2 login to work, I finished basically everything needed, but when I want to login, the sessionid does get stored and is valid when I check the DB, but request.user seems to be an instance of AnonymousUser, hence not being seen as logged in on the website.

auth.py:

from django.contrib.auth.backends import BaseBackend
from .models import DiscordUser

class DiscordAuthenticationBackend(BaseBackend):
    async def authenticate(self, request, user) -> DiscordUser:
        try:
            user = await DiscordUser.objects.aget(pk=user["id"])
            return user
        except DiscordUser.DoesNotExist:
            new_user = await DiscordUser.objects.create_discord_user(user)
            await new_user.asave()
            return new_user

views.py:

...
async def discordLoginCallback(request) -> HttpResponseRedirect:
    code = request.GET.get("code")
    user = await exchangeOauth2Code(code)
    if user: # login
        discord_user = await DiscordAuthenticationBackend().authenticate(request, user=user)
        await sync_to_async(login)(request, user=discord_user, backend="index.auth.DiscordAuthenticationBackend")
        return redirect("index")
    else:
        context = {
            "msg": "An error occurred while the OAuth2 authorization process"
        }
        return render(request, "index/message.html", context)

models.py:

class DiscordUser(models.Model):
    objects = DiscordUserOAuth2Manager()

    user_id = models.BigIntegerField(primary_key=True)
    username = models.CharField(max_length=100)
    avatar = models.CharField(max_length=36)
    
    # stored in base64
    encrypted_access_token = models.CharField(max_length=100)
    encrypted_refresh_token = models.CharField(max_length=100)
    encryption_nonce = models.CharField(max_length=100)

    is_premium = models.BooleanField(default=False)

    is_authenticated = True
    last_login = models.DateTimeField(null=True)
fathom bolt
#

Are you expecting to get an instance of a DiscordUser to be User that is authenticated?

mossy cedar
#

yes

fathom bolt
mossy cedar
#

hmm then can I just get a discorduser from request.user

#

while also keeping the original User model

fathom bolt
#

No, You can only have a single User model for authentication.

#

you could do request.user.discorduser

#

Assuming you have a OneToOne or FK between user and FK

mossy cedar
#

so I have to basically create a new custom user model for this to work?

fathom bolt
#

It depends on what you are trying to achieve for you authentication needs. Do you want native auth and Discord auth?

mossy cedar
#

I don't really need the native auth

#

I won't be using the admin panel

fathom bolt
#

Ok, then you would probably create a convert your DiscordUser into a custom user model as per the docs page I shared above.

mossy cedar
#

ok then