コード例 #1
0
ファイル: views.py プロジェクト: avral/mapala
    def delete(self, request):
        if not self._member_exists(request):
            return Response('not exists')

        ins = LocoMember.objects.get(
            user_blockchain__blockchain=BlockChain.current(),
            user_blockchain__user=request.user)

        ins.delete()

        return Response('OK')
コード例 #2
0
def register(request):
    if settings.LOCALE == 'en':
        # Регистрируем юзера в блокчейне, пока GOLOS
        raise ValueError('Registration for existing steemit accounts only')

    slz = UserRegiserSerializer(data=request.data)

    if slz.is_valid(raise_exception=True):
        password = slz.validated_data['password']
        bc_username = slz.validated_data['bc_username']

        golos = Golos(BlockChain.current().wss,
                      keys=[settings.REGISTRAR['wif']])

        try:
            golos.create_account(
                bc_username,
                password=password,
                creator=settings.REGISTRAR['name'],
                storekeys=False,
            )['operations'][0][1]
        except AccountExistsException:
            return Response('Blockchain account name already exists',
                            status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logger.exception('Ошибка создания юзера golos')
            return Response('Invalid blockchain username',
                            status=status.HTTP_400_BAD_REQUEST)

        logger.info('Registration {} from {}'.format(
            slz.validated_data['username'], get_client_ip(request)))

        user = User.objects.create_user(
            username=slz.validated_data['username'],
            number=slz.validated_data['number'],
            password=password)

        # Хук для создания юзера на альфе
        requests.get('http://alfa.mapala.net/api/v1/site/create_user?user=%s' %
                     slz.validated_data['username'])

        UserBlockChain.objects.create(
            user=user,
            username=bc_username,
            blockchain=BlockChain.objects.get(name='golos'))

        result = jwt_response_by_user(user)

        # Возвращаем постинг ключ при успешной регистрации
        result['posting_key'] = str(
            PasswordKey(bc_username, password, role="posting").get_private())
        return Response(result)
コード例 #3
0
    def __init__(self):
        self.blockchain = BlockChain.current().name

        db_params = settings.BLOCKCHAIN_DATABASES[self.blockchain]
        self.conn = pyodbc.connect(
            self.params_tpl.format(
                db_params['driver'],
                db_params['server'],
                db_params['database'],
                db_params['username'],
                db_params['password']
            ), autocommit=True
        )
        self.cursor = self.conn.cursor()
コード例 #4
0
def register_existing_user(request):
    slz = ExistUserRegiserSerializer(data=request.data)

    if slz.is_valid():
        db = BlockChainDB()

        wif = slz.validated_data['wif']
        mapala_username = slz.validated_data['username']

        username = db.get_user_by_posting_key(PrivateKey(wif).pubkey)

        if username is None:
            return Response('User with this key not exists',
                            status.HTTP_404_NOT_FOUND)

        existng_bc = UserBlockChain.on_bc.filter(username=username)

        if existng_bc.exists():
            user = existng_bc.first().user

            if '_unactivated' in user.username:
                user.username = mapala_username
                user.set_password(request.data.get('password'))
                user.save()
            else:
                return Response(
                    'Mapala user with this key already exists: %s' %
                    user.username, status.HTTP_400_BAD_REQUEST)
        else:
            user = User.objects.create_user(
                username=mapala_username,
                password=request.data.get('password'))

            UserBlockChain.objects.create(username=username,
                                          user=user,
                                          blockchain=BlockChain.current())

        # Хук для создания юзера на альфе
        requests.get('http://alfa.mapala.net/api/v1/site/create_user?user=%s' %
                     mapala_username)

        logger.info('Registration {} from {}'.format(username,
                                                     get_client_ip(request)))

        return Response(jwt_response_by_user(user))
    else:
        return Response(slz._errors, status=status.HTTP_400_BAD_REQUEST)
コード例 #5
0
    def create(self, request):
        """
        Блокчейна привязывается к аккаунту только один раз.
        Отвязать блокчейн от аккаунта или привязать к другому невозможно.
        """
        # TODO Поменять логику работы с поспами и их авторами.(ТЗ v2)
        wif = request.data.get('wif', '<non_valid>')

        try:
            # HACK не валидируем юзера в бч тк не исправили баг на голосе
            #   rpc = BaseUpdater('golos').rpc
            #   username = rpc.wallet.getAccountFromPrivateKey(wif).lower()
            # except (ValueError, AssertionError, AttributeError):

            db = BlockChainDB()
            pubkey = PrivateKey(wif).pubkey
            username = db.get_user_by_posting_key(pubkey).lower()
        except (ValueError, AssertionError, AttributeError):
            raise ValidationError('Invalid posting key')

        bc_by_user = UserBlockChain.on_bc.filter(user=request.user).first()

        if bc_by_user is not None:
            if username != bc_by_user.username:
                return Response(
                    'You already have account: %s, set key for it' %
                    bc_by_user.username, status.HTTP_400_BAD_REQUEST)

            return Response(self.serializer_class(bc_by_user).data)

        user_bc = UserBlockChain.on_bc.filter(username=username).first()

        if user_bc is not None:
            user = user_bc.user

            # тут проверка на uncativated
            if user != request.user:
                if '_unactivated' in user.username:
                    # TODO Удалять промежуточных юзеров
                    # Меняем автора с промежуточного юзера на текущего.
                    Page.objects.filter(author=user_bc.user).update(
                        author=request.user)
                    Comment.objects.filter(author=user_bc.user).update(
                        author=request.user)

                    user_bc.user = request.user
                    user_bc.save()
                    return Response(self.serializer_class(bc_by_user).data)
                else:
                    return Response(
                        'user with this key exists: %s' % user.username,
                        status.HTTP_400_BAD_REQUEST)
            else:
                return Response(self.serializer_class(user_bc).data)

        user_bc = UserBlockChain.objects.create(
            user=request.user,
            username=username,
            blockchain=BlockChain.current())

        return Response(self.serializer_class(user_bc).data)
コード例 #6
0
ファイル: views.py プロジェクト: avral/mapala
 def _member_exists(self, request):
     return LocoMember.objects.filter(
         user_blockchain__blockchain=BlockChain.current(),
         user_blockchain__user=request.user).exists()
コード例 #7
0
ファイル: sync.py プロジェクト: avral/mapala
 def __init__(self, db_connect=False):
     self.blockchain = BlockChain.current()
     self.db = BlockChainDB() if db_connect else None
     self.rpc = Steem(self.blockchain.wss)