def validate_token(email, oauth_token): try: idinfo = id_token.verify_oauth2_token(oauth_token, requests.Request(), settings.GOOGLE_OAUTH2_CLIENT_ID) issuers = ['accounts.google.com', 'https://accounts.google.com'] if idinfo['iss'] not in issuers: raise EventFactory.Conflict( 'GOOGLE_OAUTH2_USER_INFO_ERROR_DETECTED') gmail_email = idinfo['email'] except ValueError: raise EventFactory.Conflict('GOOGLE_OAUTH2_USER_INFO_ERROR_DETECTED') # -- validate email if gmail_email != email: raise EventFactory.BrokenRequest('EMAIL_MISMATCH_DETECTED') # -- validate domain domain = email.split('@')[1] if domain not in settings.GOOGLE_OAUTH2_ALLOWED_DOMAINS: raise EventFactory.AuthError('WRONG_EMAIL_DOMAIN') return gmail_email
def test_render_event_name__accepts_many_finalizers(self): assert CreateOrRead('Car').render_event_name( Mock(), EventFactory.Created()) == 'CAR_CREATED' assert CreateOrRead('Box').render_event_name( Mock(), EventFactory.Read()) == 'BOX_READ'
def test_create_empty__defaults(self): e = EventFactory.BaseSuccessException() assert e.data == {} assert e.context == EventFactory.Context() assert e.event is None assert e.instance is None
def test_log__no_user_id_in_context(self): dumps = self.mocker.patch('lily.base.events.orjson.dumps') dumps.return_value = '{XX}' logger = Mock() e = EventFactory.BaseSuccessException( context=EventFactory.Context(), event='HELLO') logger = self.mocker.patch.object(e, 'logger') e.log() assert logger.info.call_args_list == [call('HELLO: {XX}')] assert dumps.call_args_list == [call({'@event': 'HELLO'}, option=4)]
def test_constructor(self): c = EventFactory.Context(user_id=12, email='[email protected]', origin='here') assert c.data['user_id'] == 12 assert c.data['email'] == '[email protected]' assert c.data['origin'] == 'here'
def test_response(self): e = EventFactory.Generic(status_code=401, content='{"hello":"there"}') response = e.response() assert isinstance(response, HttpResponse) assert response.status_code == 401 assert response.content == b'{"hello":"there"}'
def test_extend(self): e = EventFactory.Generic(status_code=401, content='{"hello":"there"}') extended = e.extend(method='POST', path='/hi/there') assert extended.method == 'POST' assert extended.path == '/hi/there' assert isinstance(extended, EventFactory.Generic)
def test_log(self): e = EventFactory.Generic(status_code=401, content='{"hello":"there"}') e.logger = Mock() e.extend(method='POST', path='/hi/there').log() assert e.logger.info.call_args_list == ( [call('[POST /hi/there] -> 401')])
def test_render_event_name__wrong_finalizer(self): try: assert Execute('Get', 'Car').render_event_name(Mock(), EventFactory.Created()) except EventFactory.BrokenRequest as e: assert e.event == ( 'INVALID_FINALIZER_USED_FOR_SPECIFIC_COMMAND_DETECTED')
def test_render_event_name__wrong_finalizer(self): # -- Success Executed of Created try: assert Create('Car').render_event_name(Mock(), EventFactory.Executed()) except EventFactory.BrokenRequest as e: assert e.event == ( 'INVALID_FINALIZER_USED_FOR_SPECIFIC_COMMAND_DETECTED') # -- Updated instead of Deleted try: assert Delete('Car').render_event_name(Mock(), EventFactory.Updated()) except EventFactory.BrokenRequest as e: assert e.event == ( 'INVALID_FINALIZER_USED_FOR_SPECIFIC_COMMAND_DETECTED')
def get_token_and_delete(self): if not self.expired: token = AuthToken.encode(self.account) self.delete() return token else: raise EventFactory.BrokenRequest('EXPIRED_AUTH_REQUEST_DETECTED')
def test_extend(self): context = Mock() e = EventFactory.BaseSuccessException() prev_context = e.context e.extend(event='HI', context=context) assert e.event == 'HI' assert e.context == context assert e.context != prev_context
def test_applies_pluralization(self): user = Mock(_meta=Mock(model_name='User')) # -- render_command_name assert BulkRead('Car').render_command_name() == 'BULK_READ_CARS' assert BulkRead('boxes').render_command_name() == 'BULK_READ_BOXES' assert BulkRead(user).render_command_name() == 'BULK_READ_USERS' # -- render_event_name assert BulkRead('Car').render_event_name( Mock(), EventFactory.BulkRead()) == 'CARS_BULK_READ' assert BulkRead('boxes').render_event_name( Mock(), EventFactory.BulkRead()) == 'BOXES_BULK_READ' assert BulkRead(user).render_event_name( Mock(), EventFactory.BulkRead()) == 'USERS_BULK_READ'
def decode(token): # -- token decode try: payload = jwt.decode(jwt=token, key=settings.AUTH_TOKEN_SECRET_KEY, verify=True, algorithm=settings.AUTH_TOKEN_ALGORITHM, options={'verify_exp': True}) except jwt.ExpiredSignature: raise EventFactory.AuthError('AUTH_TOKEN_EXPIRED') except jwt.DecodeError: raise EventFactory.AuthError('AUTH_TOKEN_WAS_BROKEN') # -- payload decode try: account_id = payload['id'] account_email = payload['email'] account_type = payload['type'] except KeyError: raise EventFactory.AuthError('AUTH_TOKEN_MISSING_FIELDS_DETECTED') # -- payload to account from account.models import Account # -- avoid cyclic imports # -- make sure that account exists try: return Account.objects.get(id=account_id, email=account_email, type=account_type) except Account.DoesNotExist: raise EventFactory.AuthError('AUTH_TOKEN_MISSING_ACCOUNT')
def test_init(self): e = EventFactory.Generic(status_code=401, content='{"hello":"there"}') assert e.status_code == 401 assert e.content == '{"hello":"there"}'
def get_card_id(self, instance): raise EventFactory.AccessDenied('GO_AWAY')
from django.core.exceptions import ValidationError from django.db.utils import DatabaseError from django.contrib.auth.models import User from django_fake_model import models as fake_models from django.db import models, transaction import pytest from lily.base.command import command, HTTPCommands from lily.base.access import Access from lily.base.meta import Meta, Domain from lily.base.input import Input from lily.base.output import Output from lily.base import serializers, parsers from lily.base.events import EventFactory event = EventFactory() def to_json(response, content_field='content'): return json.loads(str(getattr(response, content_field), encoding='utf8')) class Request: pass def dump_to_bytes(data): return bytes(json.dumps(data), 'utf8') def get_auth_headers(user_id, account_type='SUPER_PREMIUM'):
def test_is_empty(self): assert EventFactory.Context().is_empty() is True assert EventFactory.Context(user_id=11).is_empty() is False assert EventFactory.Context(origin='here').is_empty() is False assert EventFactory.Context(email='here@here').is_empty() is False