コード例 #1
0
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
コード例 #2
0
    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'
コード例 #3
0
    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
コード例 #4
0
    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)]
コード例 #5
0
    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'
コード例 #6
0
    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"}'
コード例 #7
0
    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)
コード例 #8
0
    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')])
コード例 #9
0
    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')
コード例 #10
0
    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')
コード例 #11
0
    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')
コード例 #12
0
    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
コード例 #13
0
    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'
コード例 #14
0
ファイル: token.py プロジェクト: cosphere-org/lakey-service
    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')
コード例 #15
0
    def test_init(self):

        e = EventFactory.Generic(status_code=401, content='{"hello":"there"}')

        assert e.status_code == 401
        assert e.content == '{"hello":"there"}'
コード例 #16
0
ファイル: test_command.py プロジェクト: cosphere-org/lily
 def get_card_id(self, instance):
     raise EventFactory.AccessDenied('GO_AWAY')
コード例 #17
0
ファイル: test_command.py プロジェクト: cosphere-org/lily
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'):
コード例 #18
0
    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