Exemplo n.º 1
0
def set_kc_require_auth(user_id, require_auth):
    '''
    Configure whether or not authentication is required to see and submit data to a user's projects.
    WRITES to KC's UserProfile.require_auth

    :param int user_id: ID/primary key of the :py:class:`User` object.
    :param bool require_auth: The desired setting.
    '''

    # Get/generate the user's auth. token.
    user = User.objects.get(pk=user_id)
    token, is_new = Token.objects.get_or_create(user=user)

    # Trigger the user's KoBoCAT profile to be generated if it doesn't exist.
    url = settings.KOBOCAT_URL + '/api/v1/user'
    response = requests.get(url, headers={'Authorization': 'Token ' + token.key})
    if not response.status_code == 200:
        raise RuntimeError('Bad HTTP status code `{}` when retrieving KoBoCAT user profile'
                           ' for `{}`.'.format(response.status_code, user.username))

    try:
        profile = _models.UserProfile.objects.get(
            user_id=user_id)
        if profile.require_auth != require_auth:
            profile.require_auth = require_auth
            profile.save()
    except ProgrammingError as e:
        raise ProgrammingError(u'set_kc_require_auth error accessing kobocat '
                               u'tables: {}'.format(e.message))
Exemplo n.º 2
0
 def _wrapper(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except ProgrammingError as e:
         raise ProgrammingError(
             'kc_access error accessing kobocat tables: {}'.format(str(e))
         )
Exemplo n.º 3
0
def payment_post_before_handler(sender, **kwargs):
    """
    Триггер проверки контракта перед сохранением оплаты
    :param sender:
    :param kwargs:
    :return:
    """
    if kwargs['raw']:
        return
    instance = kwargs['instance']
    contract = Contract.objects.get(pk=instance.id_contract.id)
    print(contract.contract_state)
    if contract.contract_state == CONTRACT_STATE_DRAFT:
        raise ProgrammingError(
            'Контракт в состоянии черновика, оплата невозможна!')
    if contract.contract_state == CONTRACT_STATE_READY:
        raise ProgrammingError('Контракт исполнен!')
Exemplo n.º 4
0
    def create(self, token):
        if self.account_id:
            raise ProgrammingError('Stripe Account is already created')

        self._account = stripe.Account.create_external_account(
            self.connect_account.account_id, external_account=token)
        self.account_id = self._account.id
        self.save()
Exemplo n.º 5
0
    def save(self, *args, **kwargs):
        is_new = self._state.adding

        if is_new:
            # This is a CREATE operation

            # Check that the chat referenced does not contain more than 1 other user in the chat in the database.
            chat_users_in_chat = self.chat_id.chatuser_set.all()

            # Check that the chat you want to insert the chat user in is not already full
            if len(chat_users_in_chat) >= 2:
                raise DataError(
                    "Cannot assign this ChatUser instance to a Chat with pk %(pk)s because this \
					chat already contains at least 2 users (the chat is full)" %
                    {'pk': self.chat_id.pk})

            # Check that as a result of inserting the chat user instances you won't have
            # two chats in the database after calling save() that each have the 'same' chat users.
            #
            # For example:
            #	A chat with pk 16 with Joe and Jessica in the chat
            #	and another chat with pk 32 with Joe and Jessica again.
            #
            # This check is necessary as to not violate the business logic that there should
            # not be more than one chat between two different warframe accounts to capture the
            # idea of a sort of "unique chat area" that two warframe accounts use to chat between each other.

            if len(chat_users_in_chat) == 1:
                chat_user_in_chat = chat_users_in_chat[0]
                chat_user_wfa = chat_user_in_chat.warframe_account_id

                #print("chat_user_in_chat.warframe_account_id.pk: ")
                #print(chat_user_in_chat.warframe_account_id.pk)
                #print("self.warframe_account_id.pk:")
                #print(self.warframe_account_id.pk)
                #print("chat_user_in_chat.warframe_account_id.pk != (self.warframe_account_id.pk):")
                #print(chat_user_in_chat.warframe_account_id.pk != self.warframe_account_id.pk)

                if (chat_user_in_chat.warframe_account_id.pk !=
                    (self.warframe_account_id.pk)):
                    if (self._chat_between_wfa_already_exists(
                            chat_user_wfa, self.warframe_account_id)):
                        raise DataError("Attempted to add a chat user to a chat that would result " + \
                         "in duplicate chats between two particular WarframeAcccount instances.")
                else:
                    # chat_user_in_chat's warframe_account_id is the same as self.warframe_account_id
                    # meaning that after the save() there will be two warframe accounts in the same chat room.
                    # But since this case is handled by the 'no_duplicate_warframe_accounts_in_chat' constraint
                    # will just let the database constraint handle it.
                    pass
        else:
            # This is an update. Don't do anything on an update since a chat user cannot be updated
            raise ProgrammingError(
                "An attempt was made to update a ChatUser model. ChatUser should not and cannot be updated!"
            )

        super(ChatUser, self).save(*args, **kwargs)
Exemplo n.º 6
0
def get_route_path(route):
    if hasattr(route, '_route'):
        route = route._route
    elif hasattr(route, '_regex'):
        route = route._regex
    else:
        raise ProgrammingError(
            'Route is not available on {} object'.format(route))
    return route.lstrip('^').rstrip('$')
Exemplo n.º 7
0
def set_kc_require_auth(user_id, require_auth):
    ''' WRITES to KC's UserProfile.require_auth '''
    try:
        profile, created = _models.UserProfile.objects.get_or_create(
            user_id=user_id)
        if profile.require_auth != require_auth:
            profile.require_auth = require_auth
            profile.save()
    except ProgrammingError as e:
        raise ProgrammingError(u'set_kc_require_auth error accessing kobocat '
                               u'tables: {}'.format(e.message))
Exemplo n.º 8
0
def register_anonym(models):
    for model, cls_anonym in models:

        if model._meta.db_table not in connection.introspection.table_names():
            raise ProgrammingError(f'Model {Anonymizer.key(model)} '
                                   f'registered, but table does not exist')

        cls_anonym.init_meta(model)

        anonym_fields = set(cls_anonym.get_fields_names())
        model_fields = set(field.name for field in model._meta.get_fields()
                           if isinstance(field, Field))

        if hasattr(cls_anonym.Meta, 'exclude_fields'):
            exclude_fields = set(cls_anonym.Meta.exclude_fields)
        else:
            exclude_fields = model_fields - anonym_fields

        exclude_fields.update(cls_anonym.get_relation_fields(model))

        if exclude_fields & anonym_fields:
            raise LookupError(
                f'Fields {list(exclude_fields & anonym_fields)} of model '
                f'{Anonymizer.key(model)} are present in both anonymization '
                f'and excluded lists')

        specified_fields = exclude_fields | anonym_fields

        if specified_fields < model_fields:
            raise LookupError(
                f'Fields {list(model_fields - specified_fields)} were not '
                f'registered in {Anonymizer.key(cls_anonym)} class for '
                f'{Anonymizer.key(model)} model')
        if specified_fields > model_fields:
            raise LookupError(
                f'Fields {list(specified_fields - model_fields)} present in '
                f'{Anonymizer.key(cls_anonym)} class, but does not exist in '
                f'{Anonymizer.key(model)} model'
                '')
        if specified_fields != model_fields:
            raise LookupError(
                f'Fields in {Anonymizer.key(cls_anonym)} are not '
                f'the same as in {Anonymizer.key(model)} Check spelling')

        if Anonymizer.key(model) in Anonymizer.anonym_models.keys():
            raise ValueError(f'Model {Anonymizer.key(model)} '
                             f'is already declared in register_anonym')
        Anonymizer.anonym_models[Anonymizer.key(model)] = cls_anonym
Exemplo n.º 9
0
    def _validate_lookup(self, question, lookup):
        try:
            valid_lookups = self.VALID_LOOKUPS[question.type]
        except KeyError:  # pragma: no cover
            # Not covered in tests - this only happens when you add a new
            # question type and forget to update the lookup config above.  In
            # that case, the fix is simple - go up a few lines and adjust the
            # VALID_LOOKUPS dict.
            raise ProgrammingError(
                f"Valid lookups not configured for question type {question.type}"
            )

        if lookup not in valid_lookups:
            raise exceptions.ValidationError(
                f"Invalid lookup for question slug={question.slug} ({question.type.upper()}): {lookup.upper()}"
            )
Exemplo n.º 10
0
    def get_db_table(cls, sharding):
        db_table = generate_db_table_name(cls, sharding)

        if db_table not in _shard_tables:
            register_model(cls, sharding)

        with closing(connection.cursor()) as cursor:
            tables = [
                table_info.name for table_info in
                connection.introspection.get_table_list(cursor)
            ]

        if db_table not in tables:
            raise ProgrammingError(f"relation {db_table} does not exist")

        return db_table
Exemplo n.º 11
0
    def _get_declared_fields(
        cls,
        name: str,
        bases: Sequence,
        attrs: Dict[str, Any],
        meta_fields: Sequence[str],
    ) -> Dict[str, Field]:
        bases_fields = cls._get_declared_fields_from_bases(bases=bases)
        local_fields = {
            name: attrs.pop(name)
            for name, obj in list(attrs.items()) if isinstance(obj, Field)
        }

        if any(field not in meta_fields for field in local_fields):
            raise ProgrammingError(
                f"[{name}] One or more declared fields are not present in Meta.fields"
            )
        return {**bases_fields, **local_fields}
Exemplo n.º 12
0
def register_clean(models):
    for model, cls_anonym in models:
        if not (cls_anonym == AnonymBase
                or isinstance(cls_anonym, AnonymBase)):
            raise TypeError(
                f'Class used for cleaning model {Anonymizer.key(model)} does '
                f'not belong to the allowed {Anonymizer.key(AnonymBase)}')

        if model._meta.db_table not in connection.introspection.table_names():
            raise ProgrammingError(f'Model {Anonymizer.key(model)} '
                                   f'registered, but table does not exist')

        queryset = model.objects.all()
        queryset.truncate = cls_anonym.truncate
        if Anonymizer.key(model) in Anonymizer.clean_models.keys():
            raise ValueError(f'Model {Anonymizer.key(model)} '
                             f'is already declared in register_clean')
        Anonymizer.clean_models[Anonymizer.key(model)] = queryset
Exemplo n.º 13
0
def set_kc_require_auth(user_id, require_auth):
    '''
    Configure whether or not authentication is required to see and submit data
    to a user's projects.
    WRITES to KC's UserProfile.require_auth

    :param int user_id: ID/primary key of the :py:class:`User` object.
    :param bool require_auth: The desired setting.
    '''
    user = User.objects.get(pk=user_id)
    _trigger_kc_profile_creation(user)
    token, _ = Token.objects.get_or_create(user=user)
    with transaction.atomic():
        try:
            profile = _models.UserProfile.objects.get(user_id=user_id)
        except ProgrammingError as e:
            raise ProgrammingError(u'set_kc_require_auth error accessing '
                                   u'kobocat tables: {}'.format(repr(e)))
        else:
            if profile.require_auth != require_auth:
                profile.require_auth = require_auth
                profile.save()
Exemplo n.º 14
0
    def create_test_db(self,
                       verbosity=1,
                       autoclobber=False,
                       serialize=True,
                       keepdb=False):
        """
        Create a test database, prompting the user for confirmation if the
        database already exists. Return the name of the test database created.
        """
        # Don't import django.core.management if it isn't needed.

        test_database_name = self._get_test_db_name()
        if verbosity >= 1:
            action = 'Creating'
            if keepdb:
                action = "Using existing"

            print("%s test database for alias %s..." % (
                action,
                self._get_database_display_str(verbosity, test_database_name),
            ))

        # We could skip this call if keepdb is True, but we instead
        # give it the keepdb param. This is to handle the case
        # where the test DB doesn't exist, in which case we need to
        # create it, then just not destroy it. If we instead skip
        # this, we will get an exception.
        self._create_test_db(verbosity, autoclobber, keepdb)

        self.connection.close()
        settings.DATABASES[self.connection.alias]["NAME"] = test_database_name
        self.connection.settings_dict["NAME"] = test_database_name
        if keepdb:
            return

        cur = self.connection.cursor()
        cur.execute(
            raw_sql(
                "CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA pg_catalog;"
            ))

        header = """
CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA {schema};
CREATE EXTENSION IF NOT EXISTS fuzzystrmatch WITH SCHEMA {schema};
CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA {schema};
SET default_tablespace = '';
"""
        public_dump = Path(settings.ETOOLS_DUMP_LOCATION) / "public.sqldump"
        # tenant_dump = Path(settings.ETOOLS_DUMP_LOCATION) / "tenant.sql"
        if not public_dump.exists():
            raise ProgrammingError(f"'{public_dump}' not not found")
        # if not tenant_dump.exists():
        #     raise ProgrammingError(f"'{tenant_dump}' not not found")
        for i, schema in enumerate(settings.TEST_SCHEMAS, 1):
            tenant_dump = Path(
                settings.ETOOLS_DUMP_LOCATION) / ("tenant%s.sql" % i)
            if not tenant_dump.exists():
                raise ProgrammingError(f"'{tenant_dump}' not not found")

        if verbosity >= 1:
            print("Restoring %s" % public_dump)

        cmds = [
            "pg_restore", "-U", self.connection.settings_dict['USER'], "-p",
            str(self.connection.settings_dict['PORT']), "-h",
            self.connection.settings_dict['HOST'], "-d",
            self.connection.settings_dict['NAME'], "--no-owner", "--clean",
            "--if-exists", "--disable-triggers", "--exit-on-error",
            str(public_dump)
        ]
        try:
            subprocess.check_call(cmds)
        except BaseException as e:
            print(" ======= UNRECOVERABLE ERROR ========= ")
            print(e)
            print(" ".join(cmds))
            if hasattr(sys, '_called_from_test'):
                import pytest
                pytest.exit("--")
            sys.exit(2)
        try:
            cur.execute(raw_sql(header.format(schema='public')))
        except BaseException as e:
            raise BaseException(f"Error creating schema 'public'") from e

        for i, schema in enumerate(settings.TEST_SCHEMAS, 1):
            tenant_dump = Path(
                settings.ETOOLS_DUMP_LOCATION) / ("tenant%s.sql" % i)

            if verbosity >= 1:
                print("Creating schema %s" % schema)

            try:
                sql = tenant_dump.read_text()
                sql = sql.replace("[[schema]]", schema).replace(
                    "SET default_tablespace = '';",
                    header.format(schema=schema))
                cur.execute(raw_sql(sql))
            except BaseException as e:
                raise BaseException(f"Error creating schema {schema}") from e

        self.connection.close()
        self.connection.ensure_connection()

        return test_database_name
Exemplo n.º 15
0
 def __init__(self):
     raise ProgrammingError(f'{self.__class__.__name__} must not be initialized')
Exemplo n.º 16
0
 def _wrapper(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except ProgrammingError as e:
         raise ProgrammingError('kc_reader error accessing kobocat '
                                'tables: {}'.format(e.message))