# -*- coding: utf-8 -*- # # ITerativ GmbH # http://www.iterativ.ch/ # # Copyright (c) 2019 ITerativ GmbH. All rights reserved. # # Created on 2019-10-01 # @author: chrigu 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, UNKNOWN_ERROR, EMAIL_NOT_VERIFIED class LoginError(graphene.ObjectType): field = graphene.String() class Login(relay.ClientIDMutation): class Input: username_input = graphene.String() password_input = graphene.String() success = graphene.Boolean() message = graphene.String() 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_message('invalid_credentials') else: hep_client = HepClient() token = kwargs.get('token') try: user_data = hep_client.customer_me(token) except HepClientUnauthorizedException: return cls.return_login_message('invalid_credentials') except HepClientException: return cls.return_login_message(UNKNOWN_ERROR) user, status_msg = handle_user_and_verify_products(user_data) # sync email if user changed it on hep account if user.email != user_data['email']: user.email = user_data['email'] user.username = user_data['email'] user.save() if user and status_msg != EMAIL_NOT_VERIFIED: login(info.context, user) if status_msg: return cls.return_login_message(status_msg) return cls(success=True, errors=[], message='success') @classmethod def return_login_message(cls, message): if message == EMAIL_NOT_VERIFIED or message == UNKNOWN_ERROR or message == 'invalid_credentials': error = LoginError(field=message) return cls(success=False, errors=[error], message='') return cls(success=True, errors=[], message=message) class UserMutations: login = Login.Field()