Ejemplo n.º 1
0
    def post(self):
        apply_id = request.values.get("apply_id")
        af = Applyform.query.filter_by(id=apply_id).first()
        UserExist = DesignerInfo.query.filter_by(user_id=af.user.id).first()
        if UserExist:
            return jsonify({'code': -1, 'data': {'msg': "已存在"}})
        u = af.user
        # 如果是企业用户,还需设置昵称为企业名称
        if u.usertype == 1:
            u.nickname = af.company_name
        u.applystatus = APPLYSTATUS['PASS']
        db.session.add(u)
        db.session.commit()

        di = DesignerInfo.from_apply(af)
        db.session.add(di)
        # 添加category_user信息
        cats = af.categories.all()
        for i in cats:
            i.users.append(u)
            db.session.add(i)
        db.session.commit()
        # 生成钱包
        Wallet.init_wallet(u)

        # 发送通过的邮件
        send_mail_in_html(di.email, '恭喜您通过了猴小胖的入驻审核', AGREE_EMAIL_HTML)
        ApplySuccess(u.id)

        return jsonify({'code': 0})
Ejemplo n.º 2
0
    def test_success_multiple_listings(self):
        Listing.objects.create(item=self.item,
                               count=20,
                               price=20,
                               direction=Listing.Direction.SELL,
                               submitter=self.seller)
        Listing.objects.create(item=self.item,
                               count=20,
                               price=10,
                               direction=Listing.Direction.SELL,
                               submitter=self.seller)
        wallet = Wallet.get_users_wallet(self.user)
        wallet.add(200 + 100)

        result = self.item.make_buy_transaction(self.user, count=25)
        self.assertEquals(25, result['items_purchased'])
        self.assertEquals(200 + 100, result['coins_spent'])

        self.assertEqual(0, Wallet.get_users_wallet(self.user).coins)
        self.assertEqual(300, Wallet.get_users_wallet(self.seller).coins)
        self.assertEqual(
            25,
            InventoryItem.objects.get(user=self.user, item=self.item).count)
        self.assertEqual(1, Listing.objects.filter(item=self.item).count())
        self.assertEqual(15,
                         Listing.objects.filter(item=self.item).first().count)
        self.assertEqual(20,
                         Listing.objects.filter(item=self.item).first().price)
Ejemplo n.º 3
0
 def test_spend(self):
     wallet = Wallet.get_users_wallet(self.user)
     wallet.add(6)
     wallet = Wallet.get_users_wallet(self.user)
     wallet.spend(5)
     wallet = Wallet.get_users_wallet(self.user)
     self.assertEqual(1, wallet.coins)
Ejemplo n.º 4
0
 def regist():
     form = RegistForm()
     if request.method == 'POST':
         username = form.username.data
         password = form.password.data
         email = form.email.data
         idcard = form.idcard.data
         bankcard = form.bankcard.data
         location = form.location.data
         tel = form.tel.data
         wallet = Wallet()
         shop = ShoppingCar()
         customer = User(username=username,
                         email=email,
                         password=password,
                         idCard=idcard,
                         bindBankCard=bankcard,
                         location=location,
                         role='user',
                         wallet_id=wallet,
                         shoppingcar=shop,
                         tel=tel)
         #customer.encrypt_password(password)
         wallet.save() and shop.save() and customer.save()
         flash('注册成功 !')
         return redirect('/')
     return render_template('regist.html')
Ejemplo n.º 5
0
 def test_spend_should_raise_exception_when_user_does_not_have_enough_coins(
         self):
     wallet = Wallet.get_users_wallet(self.user)
     wallet.add(6)
     with self.assertRaises(CannotAffordError):
         wallet = Wallet.get_users_wallet(self.user)
         wallet.spend(10)
Ejemplo n.º 6
0
def create_wallet(user, network, address, balance=None):
    wallet = Wallet(user_id=user.id, network=network, address=address)
    if balance:
        wallet.balance = balance

    db.session.add(wallet)
    db.session.commit()
    return wallet
Ejemplo n.º 7
0
def seed_wallets():

    demo = Wallet(name="Ethan's Wallet 1", user_id=2, balance=25000)
    second = Wallet(name="Ethan's Wallet No 2", user_id=2, balance=24500)

    db.session.add(demo, second)

    db.session.commit()
Ejemplo n.º 8
0
def post_wallet():
    data = request.json
    wallet = Wallet(
        user_id=data['user_id'],
        name=data['name'],
        balance=data['balance'],
        startingBalance=data['balance'])
    db.session.add(wallet)
    db.session.commit()
    return wallet.to_dict()
Ejemplo n.º 9
0
def createUser(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        isAdmin = False
        if form.is_valid():
            invite = None
            # Checking if user invite is enabled
            if getAdminOptions().inviteCodeEnabled:
                inviteCode = form.data.get('godFather')
                if InviteCode.objects.filter(code=inviteCode).count() == 1:
                    invite = InviteCode.objects.get(code=inviteCode)
                    if UserPreferences.objects.get(
                            user=invite.user).group.permissions.filter(
                                code="SPON").count() != 1:
                        return render(request, 'signup.html', {'form': form})
                else:
                    return render(request, 'signup.html', {'form': form})

            # FIXME: TOO LONG! Make smaller functions
            form.save()
            # Special condition for the first user to be administrator
            if User.objects.all().count() == 1:
                isAdmin = True
                populateDB()

            # Creating user if tests are ok
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            user.is_superuser = isAdmin
            user.save()

            # Setting the user preferences
            userPref = UserPreferences()
            userPref.user = user
            if isAdmin:
                userPref.group = Groups.objects.get(rank=5)
            else:
                userPref.group = Groups.objects.get(rank=1)
            wallet = Wallet()
            wallet.save()
            userPref.wallet = wallet
            if invite is not None:
                userPref.inviteCode = invite

            # creating user avatar
            userPref.avatar = identicon.create_identicon(username)

            userPref.save()
            createUserInviteCode(user)
            login(request, user)
            return HttpResponseRedirect(reverse('app:index'))
    else:
        form = UserCreationForm()
    return render(request, 'signup.html', {'form': form})
Ejemplo n.º 10
0
def test_wallet_donate(client: TestClient, db: Session) -> None:
    db_wallet = {'wallet_id': WALLET_ID, 'amount': 11.11}
    request = {'wallet_id': WALLET_ID, 'amount': 22.22}
    expected = {'wallet_id': WALLET_ID, 'amount': 33.33}

    # save in db
    db.add(Wallet(**db_wallet))
    db.commit()

    response = client.post('v1/wallet/donate', json=request, headers=HEADERS)
    assert response.status_code == 200
    assert response.json() == expected

    # check idempotency
    response = client.post('v1/wallet/donate', json=request, headers=HEADERS)
    assert response.json() == expected

    # check DB wallet
    db_wallet = db.query(Wallet).filter(Wallet.wallet_id == WALLET_ID).first()
    assert not db_wallet.idempotency_key
    assert db_wallet.amount == Decimal(str(expected['amount']))
    assert db_wallet.updated_at

    # check DB transaction
    db_transaction = (db.query(Transaction).filter(
        Transaction.idempotency_key == IDEMPOTENCY_KEY).first())
    assert db_transaction.amount == Decimal(str(request['amount']))
    assert db_transaction.to_wallet_id == uuid.UUID(WALLET_ID)
    assert db_transaction.to_wallet_amount == Decimal(str(expected['amount']))
    assert db_wallet.created_at
Ejemplo n.º 11
0
def signup():
    form = SignupForm(request.form)

    if request.method == 'POST' and form.validate_on_submit():
        user = User(form.username.data, form.email.data, form.password.data)
        user.password = bcrypt.generate_password_hash(user.password)

        # TODO: Change how this is initialized. Im sure there is a cleaner way.
        wallet = Wallet()
        wallet.save_to_db()

        user.wallet_id = wallet.account_number
        user.save_to_db()
        flash('Thanks for registering')
        return redirect(url_for('auth.login'))
    return render_template('auth/signup.html', form=form)
Ejemplo n.º 12
0
    def test_user_has_no_coins(self):
        listing = Listing.objects.create(item=self.item,
                                         count=5,
                                         price=10,
                                         direction=Listing.Direction.SELL,
                                         submitter=self.seller)

        result = self.item.make_buy_transaction(self.user, count=5)
        self.assertEquals(0, result['items_purchased'])
        self.assertEquals(0, result['coins_spent'])

        self.assertEqual(0, Wallet.get_users_wallet(self.user).coins)
        self.assertEqual(0, Wallet.get_users_wallet(self.seller).coins)
        self.assertFalse(
            InventoryItem.objects.filter(user=self.user,
                                         item=self.item).exists())
        self.assertEqual(listing, Listing.objects.get(pk=listing.pk))
Ejemplo n.º 13
0
def init_database():
    # Create the database and the database table
    db.create_all()

    # Insert user data
    user1 = User(msisdn='2349060010101')
    user1.wallet = Wallet()
    user2 = User(msisdn='2349060010102')
    user2.wallet = Wallet()
    db.session.add(user1)
    db.session.add(user2)

    # Commit the changes for the users
    db.session.commit()

    yield db  # this is where the testing happens!

    db.drop_all()
Ejemplo n.º 14
0
def get_or_create_wallet(user):
    try:
        wallet = Wallet.objects.get(user=user)
    except Wallet.DoesNotExist:
        # creating new wallet
        wallet = Wallet()
        wallet.user = user
        wallet.local_id = random.randint(1000000, 9999999)
        wallet.title = 'DUCK.{}'.format(wallet.local_id)
        wallet.display_name = None
        wallet.balance = 0
        wallet.save()
    # print("New wallet id =", wallet.pk)

    return wallet
Ejemplo n.º 15
0
 def test_cancel_buy_listing(self):
     listing = Listing.objects.create(item=self.item,
                                      count=5,
                                      price=10,
                                      submitter=self.user,
                                      direction=Listing.Direction.BUY)
     listing.cancel()
     self.assertEqual(0, Listing.objects.count())
     self.assertEqual(50, Wallet.get_users_wallet(self.user).coins)
     self.assertEqual(0, InventoryItem.objects.count())
Ejemplo n.º 16
0
def dashboard(request):
    sell_listings = Listing.objects.filter(submitter=request.user, direction=Listing.Direction.SELL).order_by('-pk')
    buy_listings = Listing.objects.filter(submitter=request.user, direction=Listing.Direction.BUY).order_by('-pk')
    inventory_items = InventoryItem.objects.filter(user=request.user)
    return render(request, 'app/dashboard.html', {
        'wallet': Wallet.get_users_wallet(request.user),
        'sell_listings': sell_listings,
        'buy_listings': buy_listings,
        'inventory_items': inventory_items,
    })
Ejemplo n.º 17
0
    def test_success_listing_deleted(self):
        Listing.objects.create(item=self.item,
                               count=5,
                               price=10,
                               direction=Listing.Direction.SELL,
                               submitter=self.seller)
        wallet = Wallet.get_users_wallet(self.user)
        wallet.add(50)

        result = self.item.make_buy_transaction(self.user, count=5)
        self.assertEquals(5, result['items_purchased'])
        self.assertEquals(50, result['coins_spent'])

        self.assertEqual(0, Wallet.get_users_wallet(self.user).coins)
        self.assertEqual(50, Wallet.get_users_wallet(self.seller).coins)
        self.assertEqual(
            5,
            InventoryItem.objects.get(user=self.user, item=self.item).count)
        self.assertFalse(Listing.objects.filter(item=self.item).exists())
Ejemplo n.º 18
0
    def setUp(self) -> None:
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        self.client = self.app.test_client()

        # Create user
        self.user = User.from_json({
            'username': '******',
            'email': '*****@*****.**',
            'password': '******',
            'confirmed': True,
            'first_name': 'test_first_name',
            'last_name': 'test_last_name'
        })
        db.session.add(self.user)

        # Login user
        response = self.client.post(url_for('api.login'),
                                    headers=self.get_api_headers(
                                        'test_user', 'new_password'))
        self.token = response.json['token']

        # Create wallet
        self.wallet = Wallet.from_json({
            'title': 'test_wallet',
            'currency': 'usd',
            'initial_balance': randint(0, 100),
            'owner_id': self.user.id
        })
        db.session.add(self.wallet)
        db.session.commit()

        # Create parent category
        self.parent_category = ParentCategory.from_json({
            'title':
            'test_parent_category',
            'budget':
            randint(0, 1000),
            'is_income':
            choice([True, False]),
            'wallet_id':
            self.wallet.id
        })
        db.session.add(self.parent_category)
        db.session.commit()

        self.data = {
            'title': 'test_parent_category2',
            'budget': randint(0, 1000),
            'is_income': choice([True, False]),
            'wallet_id': self.wallet.id
        }
Ejemplo n.º 19
0
def test_wallet_get_success(client: TestClient, db: Session) -> None:
    expected_wallet = {'wallet_id': WALLET_ID, 'amount': 12.34}

    # save in db
    db.add(Wallet(**expected_wallet))
    db.commit()

    response = client.post('v1/wallet/get',
                           json={'wallet_id': expected_wallet['wallet_id']})
    assert response.status_code == 200
    assert response.json() == expected_wallet
Ejemplo n.º 20
0
    def test_partial_success_not_enough_listings(self):
        Listing.objects.create(item=self.item,
                               count=20,
                               price=20,
                               direction=Listing.Direction.SELL,
                               submitter=self.seller)
        Listing.objects.create(item=self.item,
                               count=20,
                               price=10,
                               direction=Listing.Direction.SELL,
                               submitter=self.seller)
        wallet = Wallet.get_users_wallet(self.user)
        wallet.add(800)

        result = self.item.make_buy_transaction(self.user, count=50)
        self.assertEquals(40, result['items_purchased'])
        self.assertEquals(200 + 400, result['coins_spent'])

        self.assertEqual(200, Wallet.get_users_wallet(self.user).coins)
        self.assertEqual(600, Wallet.get_users_wallet(self.seller).coins)
        self.assertEqual(
            40,
            InventoryItem.objects.get(user=self.user, item=self.item).count)
        self.assertEqual(0, Listing.objects.filter(item=self.item).count())
Ejemplo n.º 21
0
async def add_user(
        *,
        full_name: str,
        phone_number: str,
        raw_password: str,
        is_active: bool,
        country_id: int,
        email: Optional[str] = None
) -> User:
    password = get_password_hash(raw_password)
    return User(
        full_name=full_name,
        phone_number=str(phone_number),
        password=password,
        is_active=is_active,
        email=email,
        country_id=country_id,
        wallet=Wallet()
    )
    def test_get_all_wallets(self):
        """
        The test case for get_all_wallets view.
        """
        # Create 3 wallets
        for i in range(3):
            wallet = Wallet.from_json({
                'title': 'wallet{}'.format(i),
                'currency': choice(['usd', 'eur', 'rub']),
                'initial_balance': randint(0, 100),
                'owner_id': self.user.id
            })
            db.session.add(wallet)
        db.session.commit()

        response = self.client.get(url_for('api.get_all_wallets'),
                                   headers=self.get_token_headers(self.token))

        self.assertTrue(response.status_code == 200)
        self.assertTrue(len(response.json['wallets']) == 4)
Ejemplo n.º 23
0
def test_wallet_donate_precision(client: TestClient, db: Session) -> None:
    def _get_headers():
        return {'Idempotency-Key': uuid.uuid4().hex}

    # save in db
    db.add(Wallet(wallet_id=WALLET_ID))
    db.commit()

    request = {'wallet_id': WALLET_ID, 'amount': 0.1}

    # check double problem
    assert 0.2 + 0.1 != 0.3
    assert 0.7 + 0.1 != 0.8

    for value in range(1, 10):
        response = client.post(
            'v1/wallet/donate',
            json=request,
            headers=_get_headers(),
        )
        assert response.json() == {
            'wallet_id': WALLET_ID,
            'amount': value / 10
        }
Ejemplo n.º 24
0
 def test_add(self):
     wallet = Wallet.get_users_wallet(self.user)
     wallet.add(6)
     wallet = Wallet.get_users_wallet(self.user)
     self.assertEqual(6, wallet.coins)
Ejemplo n.º 25
0
 def test_get_users_wallet(self):
     wallet = Wallet.get_users_wallet(self.user)
     self.assertEqual(self.user, wallet.user)
     self.assertEqual(0, wallet.coins)
Ejemplo n.º 26
0
 def make_object(self, data, **kwargs):
     return Wallet(**data)
Ejemplo n.º 27
0
def create_wallet():
    """
    创建钱包
    :return:
    """
    req = request.data.decode()
    req = json.loads(req)

    email = req.get('email_address')
    first_xpub = req.get('first_xpub')
    secondary_xpub = req.get('secondary_xpub')
    is_test = req.get('is_test', None)
    type_of_service = req.get('type_of_service')

    if not email \
            or not first_xpub \
            or not secondary_xpub \
            or is_test is None \
            or is_test not in [tc_constants.BITCOIN_MAIN, tc_constants.BITCOIN_TEST] \
            or type_of_service not in [tc_constants.WALLET_TYPE_ENTERPRISE, tc_constants.WALLET_TYPE_PERSONAL,
                                       tc_constants.WALLET_TYPE_SPACECHAIN]:
        logger.info('==========invalid args==========%s' % str(req))
        return jsonify({
            'message': 'invalid args',
            "status": 400,
        }), 400

    if not re_email(email):
        logger.info('==========email error==========%s' % str(email))
        return jsonify({
            'message': 'invalid email',
            "status": 400,
        }), 400

    # 查询钱包是否存在
    wallet_info = Wallet.query.filter_by(
        first_xpub=first_xpub, secondary_xpub=secondary_xpub).first()
    if wallet_info:
        wallet_info.email = email
        wallet_info.otp_index = 1
        db.session.add(wallet_info)
        db.session.commit()

        # 随意交换下字符串顺序 客户端再拼装
        otp_secret_key = wallet_info.otp_secret_key[
            5:] + wallet_info.otp_secret_key[:5]
        sat_xpub = wallet_info.sat_xpub_info.xpub
        sat_xpub = sat_xpub[5:] + sat_xpub[:5]
        return jsonify({'otp_secret': otp_secret_key, 'sat_xpub': sat_xpub})

    # 随机分配
    sats = SatXpub.query.filter_by(is_testnet=tc_constants.BITCOIN_MAIN)
    rand = random.randrange(0, sats.count())
    sat_info = sats[rand]
    constants.set_mainnet()

    sat_xpub = sat_info.xpub

    long_id, short_id = Wallet.get_user_id(first_xpub, secondary_xpub)

    wallet = Wallet(email=email,
                    first_xpub=first_xpub,
                    secondary_xpub=secondary_xpub,
                    sat_xpub_id=sat_info.id,
                    short_id=short_id,
                    is_testnet=is_test,
                    type_of_service=type_of_service)

    db.session.add(wallet)
    db.session.commit()
    wallet.billing_address = Wallet.make_billing_address(wallet.id)
    db.session.commit()

    # 随意交换下字符串顺序 客户端再拼装
    otp_secret_key = wallet.otp_secret_key[5:] + wallet.otp_secret_key[:5]
    sat_xpub = sat_xpub[5:] + sat_xpub[:5]
    if "\x00" in sat_xpub:
        sat_xpub = sat_xpub.replace("\x00", '')

    return jsonify({'otp_secret': otp_secret_key, 'sat_xpub': sat_xpub})
Ejemplo n.º 28
0
def create_wallet():
    """
    创建钱包
    :return:
    """
    req = request.data.decode()
    req = json.loads(req)

    email = req.get('email_address')
    first_xpub = req.get('first_xpub')
    secondary_xpub = req.get('secondary_xpub')
    is_test = req.get('is_test', None)
    type_of_service = req.get('type_of_service')

    if not email \
            or not first_xpub \
            or not secondary_xpub \
            or is_test is None \
            or is_test not in [tc_constants.BITCOIN_MAIN, tc_constants.BITCOIN_TEST] \
            or type_of_service not in ['personal', 'enterprise']:
        logger.info('==========invalid args==========%s' % str(req))
        return jsonify({'message': 'email error', "status": 400, }), 400

    is_test = is_test

    if not re_email(email):
        logger.info('==========email error==========%s' % str(email))
        return jsonify({'message': 'email error', "status": 400, }), 400

    # 分配卫星公钥 私钥
    if not is_test:
        wallet_xpub = current_app.config['FEE_XPUB']
        sat_info = SatXpub.query.filter_by(is_testnet=tc_constants.BITCOIN_MAIN).first()
        constants.set_mainnet()
    else:
        wallet_xpub = current_app.config['FEE_XPUB_BY_TESTNET']
        constants.set_testnet()
        sat_info = SatXpub.query.filter_by(is_testnet=tc_constants.BITCOIN_TEST).first()

    sat_xpub = sat_info.xpub

    long_id, short_id = Wallet.get_user_id(first_xpub, secondary_xpub)

    # 生成收费钱包子地址
    try:
        legacy_address, segwit_address = Wallet.make_billing_address(long_id, wallet_xpub, 1)
    except:
        logger.info('===================get((legacy_address,segwit_address))error===================')
        return jsonify({"status": 400,
                        'message': 'error'}), 400

    wallet = Wallet(email=email, first_xpub=first_xpub, secondary_xpub=secondary_xpub, sat_xpub_id=sat_info.id,
                    short_id=short_id, is_testnet=is_test, segwit_address=segwit_address,
                    legacy_address=legacy_address, type_of_service=type_of_service)

    db.session.add(wallet)
    db.session.commit()
    # 随意交换下字符串顺序 客户端再拼装
    otp_secret_key = wallet.otp_secret_key[5:] + wallet.otp_secret_key[:5]
    sat_xpub = sat_xpub[5:] + sat_xpub[:5]
    return jsonify({
        'otp_secret': otp_secret_key,
        'sat_xpub': sat_xpub
    })