示例#1
0
    def setUp(self):
        super(AuthTest, self).setUp()

        self.account_1 = Account(
                passwd = hashlib.md5(b"123pass").hexdigest()
            )
        self.account_2 = Account()

        self.dbsess.add(self.account_1)
        self.dbsess.add(self.account_2)
        self.dbsess.flush()
        self.dbsess.add(Credential(
                uid = self.account_1.uid,
                cred_type = 'name',
                cred_value = 'john'
            ))
        self.dbsess.add(Credential(
                uid = self.account_2.uid,
                cred_type = 'name',
                cred_value = 'gump'
            ))
        self.dbsess.add(Credential(
                uid = self.account_2.uid,
                cred_type = 'email',
                cred_value = '*****@*****.**'
            ))
        self.dbsess.add(UserInfo(
                uid = self.account_2.uid,
                student_id = 2013999999,
                department = u'\u4e00\u70b9\u4eba\u751f\u7684\u7ecf\u9a8c',
                school = u'\u4e00\u70b9\u5fae\u5c0f\u7684\u5de5\u4f5c',
                introduction = u'\u4e00\u4e2a\u4e0a\u6d77\u7684\u4e66\u8bb0'
            ))
        self.dbsess.commit()
示例#2
0
def post_handler(event, context) -> Dict:
    """
    Add a new account for a given budget
    :param event: AWSEvent
    :param context: AWSContext
    :return: Dict
    """
    logger.info("Received input with body: %s", event["body"])

    try:
        input_obj = json.loads(event["body"])

        budget_id = int(input_obj["budgetId"])
        name = str(input_obj["name"])
        assert len(name) > 2
        if "parentId" in input_obj:
            parent_id = int(input_obj["parentId"])
        else:
            parent_id = None
    except Exception as err:
        logger.warning("Bad inputs provided with err: %s", err)
        return HttpResponse(400, message="Invalid input object").to_resp()

    with db_session:
        # check that budget exists
        budget = Budget.select(
            lambda b: b.id == budget_id)[:]  # type: List[Budget]
        if not budget:
            return HttpResponse(400, message="Bad budget provided").to_resp()

        kwargs = {
            "budget_id": budget[0],
            "name": name,
        }

        if parent_id:
            kwargs["parent_id"] = parent_id

        # insert into accounts
        new_account = Account(**kwargs)
        commit()
        new_account = Account.get(id=new_account.id).to_dict()

    logger.info("Created new account with id: %s", new_account["id"])
    return HttpResponse(200,
                        message="Successfully created",
                        body={
                            "account": new_account,
                        }).to_resp()
示例#3
0
 def __init__(self, session: Session, request_args):
     if 'Session-Id' in request_args:
         # TODO: Respect session's timeout
         user_session = session.query(UserSession).filter_by(
             session_id=request_args['Session-Id']).first()
         self.account = session.query(Account).filter_by(
             address=user_session.address).first()
         self.public_key = self.account.public_key
         self.address = self.account.address
         self.asset_id = user_session.currency
     else:
         self.asset_id = request_args['Asset-Id']
         self.auth_hash = b58decode(request_args['AuthHash'])
         self.auth_nonce = b58decode(request_args['AuthNonce'])
         self.public_key = bytes(request_args['Public-Key'], 'latin-1')
         self.address = request_args['Address']
         if self.address != public_key_to_account(
                 request_args['Public-Key']):
             raise PermissionError("Public key is and address differ")
         self.account = Account.get_or_create(session, self.address,
                                              self.public_key)
         if not self._is_auth_hash_valid(self.public_key, self.auth_hash,
                                         self.auth_nonce, self.asset_id):
             raise PermissionError("WAC header is invalid")
         user_session = UserSession(self.address, self.asset_id)
         session.add(user_session)
     self.session_id = user_session.session_id
示例#4
0
def get_handler(event, context) -> Dict:
    """
    Fetch all accounts for a given budget
    :param event: AWSEvent
    :param context: AWSContext
    :return: Dict
    """
    logger.info("Received event: %s", event["queryStringParameters"])

    try:
        budget_id = int(event["queryStringParameters"]["budgetId"])
    except (KeyError, ValueError):
        logger.warning("Bad inputs provided, returning.")
        return HttpResponse(400, message="Invalid input object").to_resp()

    with db_session:
        budget = Budget.select(
            lambda b: b.id == budget_id)[:]  # type: List[Budget]

        if not budget:
            return HttpResponse(
                404, message="No budget found for budget id").to_resp()

        accounts = Account.select(
            lambda a: a.budget_id == budget[0])[:]  # type: List[Account]

    logger.info("Found %s accounts for budget: %s", len(accounts), budget_id)
    return HttpResponse(200,
                        message="Found accounts",
                        body={
                            "accounts":
                            [account.to_dict() for account in accounts]
                        }).to_resp()
示例#5
0
    def test_create(self):
        from common.models import Withdrawal, Account
        # Here I am testing if combine-all-models-onto-one-giant-class works.
        withdrawal = Withdrawal.to_bank_account(
            "bank_account", Account("address", "public_key",
                                    "deposit_address"))

        self.assertEqual(withdrawal.address, "address")
示例#6
0
文件: base.py 项目: abelenki/Billy
    def _check_account(self, account):
        current_account = Account().current()

        if current_account.key() != account.key():
            self.accessForbidden()
示例#7
0
def sys(request, module, action=""):
  if 'loginToken' in request.session and request.session['user_sys']:
    if module == 'account':
      if action == "add":
        account = request.POST['account']
        name = request.POST['name']
        passwd = make_password(request.POST['passwd'], None, 'pbkdf2_sha256')
        mgr = request.POST['mgr']
        project = request.POST['project']
        date = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
        try:
          obj = Account(account=account,
                        name=name,
                        secpasswd=passwd,
                        status=1,
                        regist_time=date,
                        authorize=mgr,
                        module=project)
          obj.save()
          result = {}
          result['code'] = 1
          result['message'] = date
        except:
          result = {}
          result['code'] = 0
          result['message'] = "添加失败"
        return HttpResponse(json.dumps(result), content_type="application/json")
      else:
        if 'ctrl' in request.POST:
          ctrl = request.POST['ctrl']
          accnt_id = request.POST['id']
          accnt = Account.objects.get(id=accnt_id)
          if ctrl == "status":
            accnt_status = accnt.status
            if accnt_status == 1:
              Account.objects.filter(id=accnt_id).update(status=0)
            else:
              Account.objects.filter(id=accnt_id).update(status=1)
            result = {}
            result['code'] = 1
            result['message'] = "状态变更成功"
          elif ctrl == "admin":
            accnt_admin = accnt.authorize
            if accnt_admin == '1':
              Account.objects.filter(id=accnt_id).update(authorize='0')
            else:
              Account.objects.filter(id=accnt_id).update(authorize='1')
            result = {}
            result['code'] = 1
            result['message'] = "后台权限变成成功"
          else:
            result = {}
            result['code'] = 0
            result['message'] = "无操作"
          return HttpResponse(json.dumps(result), content_type="application/json")
        else:
          project_list = Project.objects.all()
          account_list = Account.objects.all()
          rsp = render(request, 'admin_account.html', locals())
          return HttpResponse(rsp)
    elif module == 'log':
      log_list = Logrecord.objects.all();
      rsp = render(request, 'admin_log.html', locals())
      return HttpResponse(rsp)
    else:
      return HttpResponseRedirect('account')
  else:
    return HttpResponseRedirect('/')
示例#8
0
    def setUp(self):
        super(AuthTest, self).setUp()

        self.account_1 = Account(passwd=hashlib.md5(b"123pass").hexdigest())
        self.account_2 = Account()
        self.account_3 = Account(passwd=hashlib.md5(b"123").hexdigest())

        self.dbsess.add(self.account_1)
        self.dbsess.add(self.account_2)
        self.dbsess.add(self.account_3)
        self.dbsess.flush()
        self.dbsess.add(
            Credential(uid=self.account_1.uid,
                       cred_type='name',
                       cred_value='john'))
        self.dbsess.add(
            Credential(uid=self.account_3.uid,
                       cred_type='name',
                       cred_value='patrick'))
        self.dbsess.add(MyTimetable(uid=self.account_1.uid, mon=1, wed=1))
        self.dbsess.add(MyTimetable(uid=self.account_1.uid, sat=1))
        self.dbsess.add(MyTimetable(uid=self.account_2.uid, tue=1))
        self.dbsess.add(MyTimetable(uid=self.account_3.uid, sun=1))
        self.dbsess.add(Timetable(mon=1, wed=1))
        self.dbsess.add(Timetable(sat=1))
        self.dbsess.add(
            Credential(uid=self.account_2.uid,
                       cred_type='name',
                       cred_value='gump'))
        self.dbsess.add(
            Credential(uid=self.account_2.uid,
                       cred_type='email',
                       cred_value='*****@*****.**'))
        self.dbsess.add(
            UserInfo(
                uid=self.account_2.uid,
                student_id=2013999999,
                department=u'\u4e00\u70b9\u4eba\u751f\u7684\u7ecf\u9a8c',
                school=u'\u4e00\u70b9\u5fae\u5c0f\u7684\u5de5\u4f5c',
                introduction=u'\u4e00\u4e2a\u4e0a\u6d77\u7684\u4e66\u8bb0'))
        self.dbsess.add(
            UserInfo(
                uid=self.account_3.uid,
                student_id=2013,
                department=u'\u4e00\u70b9\u4eba\u751f\u7684\u7ecf\u9a8c',
                school=u'\u4e00\u70b9\u5fae\u5c0f\u7684\u5de5\u4f5c',
                introduction=u'\u4e00\u4e2a\u4e0a\u6d77\u7684\u4e66\u8bb0'))
        self.dbsess.add(
            Applications(name='paul',
                         student_id=2015000000,
                         school='ist',
                         major='cst',
                         phone='15500000000',
                         department='技术组'))
        self.dbsess.add(
            Applications(name='ann',
                         student_id=2015000001,
                         school='ist',
                         major='cst',
                         phone='15500000001',
                         department='技术组'))
        self.dbsess.add(ApplyTime(start='9.12', end='10.12'))
        self.dbsess.add(Mission(
            id=1,
            act_name='night',
            act_date='5.23',
        ))
        self.dbsess.add(
            MnMember(id=1,
                     uid=self.account_1.uid,
                     name='john',
                     act_content='this'))
        self.dbsess.add(
            MnMember(id=1,
                     uid=self.account_2.uid,
                     name='gump',
                     act_content='that'))
        self.dbsess.add(
            Notification(title='a title',
                         department='技术组',
                         content='get girls'))

        self.dbsess.commit()
示例#9
0
    def _check_account(self, account):
        current_account = Account().current()

        if current_account.key() != account.key():
            self.accessForbidden()
示例#10
0
    def handle(self, *args, **options):
        # 城市
        cd = City(name='成都')
        bj = City(name='北京')

        cd.save()
        bj.save()

        # 区域
        area_smq = Area(city=cd, name='驷马桥')

        area_wks = Area(city=cd, name='五块石')

        area_smq.save()
        area_wks.save()

        # 商户类型
        merchant_category_yinshi = MerchantCategory(name='饮食')
        merchant_category_yule = MerchantCategory(name='娱乐')

        merchant_category_yinshi.save()
        merchant_category_yule.save()

        # 付款码
        pay_code = PaymentQRCode(uuid=uuid.uuid4())
        pay_code.save()

        # account
        merchant_account = Account(bank_name='招商银行成都分行高新支行',
                                   bank_card_number='7678442831579099123',
                                   bank_account_name='陈冠希',
                                   balance=10000,
                                   withdrawable_balance=8000)
        merchant_account.save()

        marketer_account = Account(bank_name='招商银行成都分行高新支行',
                                   bank_card_number='7678442831579099145',
                                   bank_account_name='流川枫',
                                   balance=10000,
                                   withdrawable_balance=8000)
        marketer_account.save()

        # 业务员
        marketer = Marketer(wechat_openid='saxsdadf00xx',
                            wechat_unionid='xx456asdfnn',
                            inviter_type=config.MARKETER_TYPES.SALESMAN,
                            status=config.SYSTEM_USER_STATUS.USING,
                            name='流川枫',
                            phone='18109045756',
                            account=marketer_account,
                            worker_number='tnt001')
        marketer.save()
        marketer.working_areas.add(area_wks)

        # 商户
        merchant = Merchant(
            status=config.MERCHANT_STATUS.USING,
            name='生如夏花泰式火锅(鹭洲里店)',
            account=merchant_account,
            payment_qr_code=pay_code,
            category=merchant_category_yinshi,
            contact_phone='18945236754',
            area=area_wks,
            address='成都市五块石北城天街98号',
            location_lon=10,
            location_lat=10,
            description='纯正泰式火锅,家门口的泰式美食旅行',
            avatar_url=
            'https://img.meituan.net/msmerchant/96814ff238209b8b9ecc8144338f9c09253790.jpg',  # noqa
            photo_url=
            'https://img.meituan.net/msmerchant/96814ff238209b8b9ecc8144338f9c09253790.jpg',  # noqa
            license_url=
            'https://img.meituan.net/msmerchant/96814ff238209b8b9ecc8144338f9c09253790.jpg',  # noqa
            id_card_front_url=
            'http://img.wenzhangba.com/userup/883/1P4020F057-35O-0.jpg',
            id_card_back_url=
            'http://image2.sina.com.cn/dy/c/2004-03-29/U48P1T1D3073262F23DT20040329135445.jpg',  # noqa
            create_datetime=timezone.now())
        merchant.save()
        merchant.auditors.add(marketer)

        # 用户
        client = Client(openid='oUkVN5WSmOYbYSgR74rRPamWmoAM',
                        openid_channel=config.PAY_CHANNELS.WECHAT)
        client.save()

        # 优惠券rule
        coupon_rule = CouponRule(
            merchant=merchant,
            discount=10,
            min_charge=50,
            valid_strategy=config.VALID_STRATEGY.EXPIRATION,
            expiration_days=15,
            stock=30,
            photo_url=
            'https://img.meituan.net/msmerchant/96814ff238209b8b9ecc8144338f9c09253790.jpg'
        )  # noqa
        coupon_rule.save()

        coupon = Coupon(rule=coupon_rule,
                        client=client,
                        discount=10,
                        min_charge=50,
                        originator_merchant=merchant,
                        status=config.COUPON_STATUS.NOT_USED,
                        obtain_datetime=timezone.now())
        coupon.save()
示例#11
0
def sys(request, module, action=""):
    if "loginToken" in request.session and request.session["user_sys"]:
        if module == "account":
            if action == "add":
                account = request.POST["account"]
                name = request.POST["name"]
                passwd = make_password(request.POST["passwd"], None, "pbkdf2_sha256")
                mgr = request.POST["mgr"]
                project = request.POST["project"]
                date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                try:
                    obj = Account(
                        account=account,
                        name=name,
                        secpasswd=passwd,
                        status=1,
                        regist_time=date,
                        authorize=mgr,
                        module=project,
                    )
                    obj.save()
                    result = {}
                    result["code"] = 1
                    result["message"] = date
                except:
                    result = {}
                    result["code"] = 0
                    result["message"] = "添加失败"
                return HttpResponse(json.dumps(result), content_type="application/json")
            else:
                if "ctrl" in request.POST:
                    ctrl = request.POST["ctrl"]
                    accnt_id = request.POST["id"]
                    accnt = Account.objects.get(id=accnt_id)
                    if ctrl == "status":
                        accnt_status = accnt.status
                        if accnt_status == 1:
                            Account.objects.filter(id=accnt_id).update(status=0)
                        else:
                            Account.objects.filter(id=accnt_id).update(status=1)
                        result = {}
                        result["code"] = 1
                        result["message"] = "状态变更成功"
                    elif ctrl == "admin":
                        accnt_admin = accnt.authorize
                        if accnt_admin == "1":
                            Account.objects.filter(id=accnt_id).update(authorize="0")
                        else:
                            Account.objects.filter(id=accnt_id).update(authorize="1")
                        result = {}
                        result["code"] = 1
                        result["message"] = "后台权限变成成功"
                    else:
                        result = {}
                        result["code"] = 0
                        result["message"] = "无操作"
                    return HttpResponse(json.dumps(result), content_type="application/json")
                else:
                    project_list = Project.objects.all()
                    account_list = Account.objects.all()
                    rsp = render(request, "admin_account.html", locals())
                    return HttpResponse(rsp)
        elif module == "log":
            log_list = Logrecord.objects.all()
            rsp = render(request, "admin_log.html", locals())
            return HttpResponse(rsp)
        else:
            return HttpResponseRedirect("account")
    else:
        return HttpResponseRedirect("/")