skillbox/server/users/mutations_public.py

73 lines
2.0 KiB
Python

# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2019 ITerativ GmbH. All rights reserved.
#
# Created on 2019-10-01
# @author: chrigu <christian.cueni@iterativ.ch>
import graphene
from django.conf import settings
from django.contrib.auth import authenticate, login
from graphene import relay
from core.hep_client import HepClient, HepClientUnauthorizedException, HepClientException
from users.user_signup_login_handler import handle_user_and_verify_products
class LoginError(graphene.ObjectType):
field = graphene.String()
class Login(relay.ClientIDMutation):
class Input:
username_input = graphene.String()
password_input = graphene.String()
success = graphene.Boolean()
errors = graphene.List(LoginError) # todo: change for consistency
@classmethod
def mutate_and_get_payload(cls, root, info, **kwargs):
username = kwargs.get('username_input')
if settings.USE_LOCAL_REGISTRATION:
password = kwargs.get('password_input')
user = authenticate(username=username, password=password)
if user is None:
return cls.return_login_error('invalid_credentials')
else:
hep_client = HepClient()
token = kwargs.get('token')
try:
user_data = hep_client.customer_me(token)
except HepClientUnauthorizedException:
return cls.return_login_error('invalid_credentials')
except HepClientException:
return cls.return_login_error('unknown_error')
user, error_msg = handle_user_and_verify_products(user_data)
if error_msg:
return cls.return_login_error(error_msg)
login(info.context, user)
return cls(success=True, errors=[])
@classmethod
def return_login_error(cls, message):
error = LoginError(field=message)
return cls(success=False, errors=[error])
class UserMutations:
login = Login.Field()