Unable to login users with session authentication
See original GitHub issueI’ve written the following mutation for logging users in. It’s been adapted to work with channels, before I was using Django’s default login
function (which worked fine with graphene):
# ...
from asgiref.sync import async_to_sync
from channels.auth import login
# ...
class Login(graphene.Mutation):
user = graphene.Field(UserNode)
success = graphene.Boolean(required=True)
errors = graphene.List(FormFieldError)
class Arguments:
username = graphene.String(required=True)
password = graphene.String(required=True)
def mutate(self, info, username, password):
success = False
errors = []
user = authenticate(info.context, username=username, password=password)
context = vars(info.context) # by default this is a namespace, `login` expects a dictionary
if user is not None:
async_to_sync(login)(context, user)
success = True
context['session'].save()
else:
errors.append(FormFieldError(
field='password', messages=['Authentication failed.'],
))
return Login(success=success, user=user, errors=errors)
This successfully logs the user in. I’ve inserted a breakpoint after the user is logged in, and info.context.user.is_authenticated
is True
.
The issue is this doesn’t persist. If you make another request, info.context.user.is_authenticated
is False
. It doesn’t persist the user’s session.
I followed the channels authentication documentation as recommended in this project’s README.
It seems like the issue might be that the user isn’t logged in within a consumer’s receive
method, which is described in the channels docs. But this isn’t possible because I’m using graphene mutations to login the user (therefore the login code can’t be in the consumer).
How can I get this working? Thanks in advance.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:7 (6 by maintainers)
Top GitHub Comments
@prokher sorry for the late response. I never managed to find a solution for this. Thanks for the fix!
Thanks for reporting. We will take a look.