Exemple #1
0
    def mutate(self, info, email=None, password=None):
        if email is None:
            error = 'You must provide a valid email'
            return AuthenticateUser(success=False, error=error)

        if password is None:
            error = 'You must provide a valid password'
            return AuthenticateUser(success=False, error=error)

        try:
            user = CustomUser.users.get(email=email)
        except ObjectDoesNotExist:
            error = "user does not exist"
            return AuthenticateUser(success=False, error=error)

        authenticated_user = authenticate(email=email, password=password)

        if authenticated_user is None:
            error = "wrong email or password provided"
            return AuthenticateUser(success=False, error=error)

        token = get_token(user)

        return AuthenticateUser(success=True,
                                token=token,
                                user=authenticated_user)
Exemple #2
0
 def perform_mutate(cls, form, info):
     user = form.save()
     token = get_token(user)
     return cls(
         error=ValidationErrors(validation_errors=[]),
         user=user, token=token, success=True
     )
Exemple #3
0
    def test_refresh_error(self):
        token = get_token(self.user)
        response = self.execute({
            'token': token,
        })

        self.assertTrue(response.errors)
Exemple #4
0
    def mutate(cls, _, info, **kwargs):
        data = {
            'uid': kwargs.get('uid'),
            'token': kwargs.get('token'),
            'new_password1': kwargs.get('password'),
            'new_password2': kwargs.get('password')
        }

        try:
            uid = force_text(uid_decoder(data['uid']))
            user = User.objects.get(pk=uid)
        except (TypeError, ValueError, OverflowError, User.DoesNotExist):
            raise ValueError('The uid is not valid.')

        form = SetPasswordForm(user=user, data=data)

        if not form.is_valid() or not token_generator.check_token(user, data['token']):
            raise ValueError("The token is not valid.")

        form.save()
        change_password_confirmation.send(sender=User, user=user, request=info.context)

        token = get_token(user, info.context)
        payload = get_payload(token, info.context)

        return cls(user=user, token=token, payload=payload)
Exemple #5
0
    def mutate(cls, root, info, **kwargs):

        request = info.context

        phone = kwargs.get("phone")
        auth_code = kwargs.get("auth_code")
        provider = kwargs.get("provider")

        if phone:
            try:
                has_verified_phone(request, phone)
            except exceptions.InvalidPhone as e:
                return Result(success=False, message=e.message)
            except exceptions.WrongVerifyCode as e:
                return Result(success=False, message=e.message)

            try:
                shop_user = ShopUser.objects.get(phone=phone)
            except ShopUser.DoesNotExist:
                return Result(success=False,
                              message="not_exist_user_with_phone")

        elif auth_code and provider:
            try:
                shop_user = ShopUser.objects.get_user_by_auth_code(
                    provider, auth_code)
            except ShopUser.DoesNotExist:
                return Result(success=False,
                              message="not_exist_user_with_auth_code")

        request.user = shop_user.user
        token = get_token(shop_user.user)

        return cls(me=shop_user, token=token)
Exemple #6
0
    def mutate(self, info, **kwargs):

        print('hi')

        first_name = kwargs.get('first_name')
        last_name = kwargs.get('last_name')
        username = kwargs.get('username')
        email = kwargs.get('email')
        password = kwargs.get('password')
        avatar = kwargs.get('avatar', None)

        try:
            existing_user = User.objects.get(username=username)
            raise Exception("Username is already taken")
        except User.DoesNotExist:
            pass

        try:
            user = User.objects.create_user(username, email, password)
            user.first_name = first_name
            user.last_name = last_name
            user.save()
        except IntegrityError as e:
            print(e)
            raise Exception("Can't Create Account")

        try:
            profile = models.Profile.objects.create(user=user, avatar=avatar)
            token = get_token(user)
            return types.CreateAccountResponse(token=token)
        except IntegrityError as e:
            print(e)
            raise Exception("Can't Create Account")
Exemple #7
0
    def mutate(self,
               info,
               phone,
               provider=None,
               auth_code=None,
               user_info=None):
        try:
            phone = parse_phone(phone)
        except exceptions.InvalidPhone as e:
            raise exceptions.GQLError(e.message)

        try:
            shop_user = ShopUser.objects.get(phone=phone)
        except ShopUser.DoesNotExist:
            shop_user = ShopUser.objects.create_user(phone=phone)

        if provider and auth_code:
            try:
                shop_user.bind_third_account(provider, auth_code)
            except (
                    exceptions.AlreadyBinded,
                    exceptions.DoNotSupportBindType,
                    exceptions.CodeBeUsed,
            ) as e:
                raise exceptions.GQLError(e.message)

        if user_info:
            for k, v in user_info.items():
                setattr(shop_user, k, v)
                shop_user.save(update_fields=[k])

        token = get_token(shop_user.user)
        refresh_token = create_refresh_token(shop_user.user)
        return SignUp(me=shop_user, token=token, refresh_token=refresh_token)
Exemple #8
0
 def prepare_response(cls, instance, errors, **data):
     return_kwargs = {
         cls.model_name: instance,
         'jwt': jwt.get_token(instance),
         'errors': errors,
     }
     return cls(**return_kwargs)
Exemple #9
0
    def test_auth_categories_query(self):
        user = sample_user_role('accountant')
        token = get_token(user)

        response = self.query(CATEGORIES_QUERY,
                              headers={'HTTP_AUTHORIZATION': f"JWT {token}"})
        content = json.loads(response.content)
        expected = {
            'data': {
                'categories': {
                    'edges': [{
                        'node': {
                            'code': 'BTTP',
                            'name': 'Bê Tông Thương Phẩm'
                        }
                    }, {
                        'node': {
                            'code': 'BOM',
                            'name': 'Bơm'
                        }
                    }]
                }
            }
        }
        self.assertResponseNoErrors(response)
        self.assertEqual(content, expected)
Exemple #10
0
 def mutate(self, info, **kwargs):
     from .form import UserSignupForm
     SignupForm = UserSignupForm(kwargs)
     if SignupForm.is_valid():
         values = SignupForm.cleaned_data
         new_user = User(
             username=values['username'],
             email=values['email'],
             display_name=values['display_name'],
             school=values['school'],
             company=values['company'],
             location=values['location'],
             is_staff=False,
             is_superuser=False,
         )
         new_user.set_password(values['password'])
         new_user.save()
         new_user.set_group(Group.NORMAL_USER)
         token = get_token(new_user)
         payload = get_payload(token, info.context)
         return Register(payload=payload,
                         token=token,
                         permission=list(new_user.get_all_permissions()),
                         user=new_user)
     else:
         raise RuntimeError(SignupForm.errors.as_json())
    def test_refresh_error(self):
        token = get_token(self.user)
        response = self.execute({
            'token': token,
        })

        self.assertTrue(response.errors)
Exemple #12
0
def test_verify_user_mutation_2(snapshot, request):
    """ Test unsuccessful verify user mutation with wrong code """

    verification_code = "1111"
    user = User.objects.create(email=faker.email(),
                               last_verification_code=verification_code)

    token = get_token(user)
    request.headers = dict()
    request.headers['AUTHORIZATION'] = "Bearer {token}".format(token=token)
    client = Client(schema, context=request)

    executed = client.execute('''
    mutation verifyUser($code: String!) {
    verifyUser(code: $code) {
			errors
			success
			user{
				id
				isVerified
			}
    	}
  	}
    ''',
                              variables={'code': 2222})

    assert not executed['data']['verifyUser']['success']
    assert executed['data']['verifyUser']['errors'][0] == 'Code is incorrect.'
    assert not executed['data']['verifyUser']['user']
Exemple #13
0
    def mutate(self, info, username, password):
        user = authenticate(username=username, password=password)

        if user is None:
            raise GraphQLError('Your credentials are invalid')

        return LoginUser(user=user, token=get_token(user))
Exemple #14
0
    def mutate(self, info, **kwargs):

        key = kwargs.get('key')

        try:
            verification = models.Verification.objects.get(key=key,
                                                           target="email",
                                                           is_verified=False,
                                                           is_edit=True)
            verification.user.email_address = verification.payload
            verification.user.is_verified_email_address = True
            verification.user.save()
            verification.is_verified = True
            token = get_token(verification.user)
            verification.save()
            return types.CompleteEditEmailVerificationResponse(
                ok=True,
                token=token,
                user=verification.user,
            )

        except models.Verification.DoesNotExist:
            return types.CompleteEditEmailVerificationResponse(
                ok=False,
                token=None,
                user=None,
            )
    def mutate(self, info, password, email):
        user = get_user_model()(email=email, )
        user.set_password(password)
        user.save()
        user_token = get_token(user)

        return CreateUser(user=user, token=user_token)
Exemple #16
0
    def mutate(self, info, **kwargs):
        if "account" in kwargs:
            if not account_validation(kwargs["account"]):
                raise GraphQLError("Incorrect Account Format")
            if User.objects.filter(account=kwargs["account"]):
                raise GraphQLError("Already Exist Account")
        if "phone_number" in kwargs:
            if not phone_number_validation(kwargs["phone_number"]):
                raise GraphQLError("Incorrect Phone Number Format")
            if User.objects.filter(phone_number=kwargs["phone_number"]):
                raise GraphQLError("Already Exist Phone_Number")
        if "email" in kwargs:
            if User.objects.filter(email=kwargs["email"]):
                raise GraphQLError("Already Exist Email")

        user = User.objects.get(id=globals.user)
        kwargs["updated_at"] = datetime.now()

        for key, value in kwargs.items():
            setattr(user, key, value)

        if "password" in kwargs:
            if not password_validation(kwargs["password"]):
                raise GraphQLError("Incorrect Password Format")
            user.set_password(kwargs["password"])

        user.save()

        token = get_token(user)
        refresh_token = create_refresh_token(user)
        return UpdateUser(user=user, token=token, refresh_token=refresh_token)
 def authenticate(self, user):
     """Payload for authentication in viterbi requires a special userID parameter."""
     self._credentials = {
         jwt_settings.JWT_AUTH_HEADER_NAME:
         "{0} {1}".format(jwt_settings.JWT_AUTH_HEADER_PREFIX,
                          get_token(user, userId=user.id, isLigo=True)),
     }
Exemple #18
0
    def mutate(self, info, email, password):
        errors = list()
        success = False
        user = None
        token = None
        try:
            user = User.objects.get(email=email)
        except ObjectDoesNotExist:
            errors.append('User with specified email does not exists.')
            return LoginMutation(success=False,
                                 errors=errors,
                                 user=user,
                                 token=token)

        if not user.check_password(password):
            errors.append(
                'User with specified email does not exists or password in incorrect.'
            )
            return LoginMutation(user=None,
                                 token=None,
                                 errors=errors,
                                 success=success)

        token = get_token(user)
        success = True

        if not user.is_verified:
            code = send_verification_code(user.email, 'Verification code')
            user.last_verification_code = code
            user.save()
        return LoginMutation(user=user,
                             token=token,
                             errors=errors,
                             success=success)
Exemple #19
0
 def test_verify_token(self):
     user = self.create_user()
     token = get_token(user)
     with self.assertNumQueries(0):
         result = self.execute(self.verify_token_mutation,
                               dict(token=token))
     self.assert_payload(result['verifyToken']['payload'], user)
Exemple #20
0
    def test_refresh_error(self):
        token = get_token(self.user)
        response = self.execute({
            "token": token,
        })

        self.assertIsNotNone(response.errors)
    def resolve_jwt_token(self, info, token):
        user = APIToken.objects.get(token=token).user

        token = get_token(user)
        refresh_token = refresh_token_lazy(user)

        return JWTType(jwt_token=token, refresh_token=str(refresh_token))
Exemple #22
0
    def mutate(
        self,
        info,
        username,
        password,
        email,
        first_name,
        last_name,
        street_address,
        city,
        state,
        zipcode,
        business_name="",
    ):
        new_user = get_user_model()(
            username=username,
            email=email,
            first_name=first_name,
            last_name=last_name,
            street_address=street_address,
            city=city,
            state=state,
            zipcode=zipcode,
            business_name=business_name,
        )

        # IMPORTANT to remember to set password instead of just password=password
        new_user.set_password(password)
        new_user.save()
        token = get_token(new_user)
        return CreateUser(user=new_user, token=token, ok=True, status="ok")
 def resolve(cls, root, info, social, **kwargs):
     try:
         from graphql_jwt.shortcuts import get_token, get_refresh_token, create_refresh_token
     except ImportError:
         raise ImportError(
             'django-graphql-jwt not installed.\n'
             'Use `pip install \'django-graphql-social-auth[jwt]\'`.')
     return cls(user=social.user, token=get_token(social.user))
Exemple #24
0
 def test_refresh_token(self):
     user = self.create_user()
     token = get_token(user)
     with self.assertNumQueries(1):
         result = self.execute(self.refresh_token_mutation,
                               dict(token=token))
     self.assert_token(result['refreshToken']['token'], user)
     self.assert_payload(result['refreshToken']['payload'], user)
Exemple #25
0
 def prepare_response(cls, instance, errors, **data):
     return_kwargs = {
         cls.model_name: instance,
         'errors': errors,
     }
     if instance and instance.pk is not None:
         return_kwargs['jwt'] = jwt.get_token(instance)
     return cls(**return_kwargs)
Exemple #26
0
    def mutate(self, info, password, username):
        token = ''

        # Return token
        if Signup.objects.filter(username=username).exists():
            user = Signup.objects.get(username=username)
            token = get_token(user)
        return CreateLogin(user=user, token=token)
Exemple #27
0
def test_verify_token(api_client, customer_user):
    variables = {
        "token": get_token(customer_user)
    }
    response = api_client.post_graphql(MUTATION_TOKEN_VERIFY, variables)
    content = get_graphql_content(response)
    user_email = content['data']['tokenVerify']['user']['email']
    assert customer_user.email == user_email
Exemple #28
0
 def mutate(self, info, username, password, email):
     user = User(
         username=username,
         email=email,
     )
     user.set_password(password)
     user.save()
     return CreateUser(token=get_token(user))
Exemple #29
0
 def get_context(self, user=None):
     kwargs = {}
     if user:
         token = get_token(user)
         headers = {'HTTP_AUTHORIZATION': f'JWT {token}'}
         kwargs['user'] = user
         kwargs['Meta'] = kwargs['META'] = headers
     return Context(**kwargs)
        def on_resolve(values):
            user, payload = values
            payload.token = get_token(user, context)

            if jwt_settings.JWT_LONG_RUNNING_REFRESH_TOKEN:
                payload.refresh_token = refresh_token_lazy(user)

            return payload
Exemple #31
0
    def resolve(cls, root, info, social, **kwargs):
        try:
            from graphql_jwt.shortcuts import get_token
        except ImportError:
            raise ImportError(
                'django-graphql-jwt not installed.\n'
                "Use `pip install 'django-graphql-social-auth[jwt]'`.")

        return cls(token=get_token(social.user))
Exemple #32
0
def test_jwt_middleware(admin_user):
    def get_response(request):
        return HttpResponse()

    rf = RequestFactory()
    middleware = jwt_middleware(get_response)

    # test setting AnonymousUser on unauthorized request to API
    request = rf.get(reverse("api"))
    assert not hasattr(request, "user")
    middleware(request)
    assert isinstance(request.user, AnonymousUser)

    # test request with proper JWT token authorizes the request to API
    token = get_token(admin_user)
    request = rf.get(reverse("api"), **{"HTTP_AUTHORIZATION": "JWT %s" % token})
    assert not hasattr(request, "user")
    middleware(request)
    assert request.user == admin_user
Exemple #33
0
def test_verify_token(api_client, customer_user):
    variables = {"token": get_token(customer_user)}
    response = api_client.post_graphql(MUTATION_TOKEN_VERIFY, variables)
    content = get_graphql_content(response)
    user_email = content["data"]["tokenVerify"]["user"]["email"]
    assert customer_user.email == user_email
Exemple #34
0
 def __init__(self, *args, **kwargs):
     user = kwargs.pop("user")
     self.user = user
     if not user.is_anonymous:
         self.token = get_token(user)
     super().__init__(*args, **kwargs)
Exemple #35
0
 def __init__(self, *args, **kwargs):
     user = kwargs.pop('user')
     self.token = get_token(user)
     super().__init__(*args, **kwargs)