Пример #1
0
 def test_check_password(self):
     user = Account()
     user_info = user.one_from_where_clause('WHERE username =?', username)
     hashed_pw = (user_info.values['password_hash'])
     hashed_pw = hashed_pw.encode()
     password = password.encode()
     return bycrypt.checkpw(password, hashed_pw)  #returns True or False
Пример #2
0
 def add_deposit(id_client, id_offer, id_debet, sum):
     dateall = date.today()
     day = dateall.day
     month = dateall.month
     year = dateall.year
     period = (Offer.get(Offer.ID_offer == id_offer)).period
     year_period = period // 12
     if (day == 31):
         day -= 1
     if year_period > 0:
         year += year_period
         period -= year_period * 12
     if month + period > 12:
         k = 12 - month
         period -= k
         year += 1
     month += period
     if month == 2 & day == 30:
         day = 28
     date_close = datetime(year, month, day)
     if ((Account.get(Account.ID_account == id_debet)).sum > sum):
         Account.create(sum=sum,
                        ID_offer=id_offer,
                        ID_client=id_client,
                        date_open=dateall,
                        date_close=date_close)
         acc = Account.get(Account.ID_account == id_debet)
         acc.sum -= sum
         acc.save()
         s = 1
         return s
     else:
         s = 2
         return s
Пример #3
0
 def registration_client(name, surname, patronymic, passport_id,
                         passport_seria, date_of_birth, login, password):
     dateall = date_of_birth.split('-')
     day = int(dateall[2])
     month = int(dateall[1])
     year = int(dateall[0])
     if ((passport_id > 1970) & (passport_id < 2030) &
         (passport_seria > 100000) & (passport_seria < 999999)):
         Client.create(name=name,
                       surname=surname,
                       patronymic=patronymic,
                       passport_id=passport_id,
                       passport_seria=passport_seria,
                       date_of_birth=date(year, month, day),
                       login=login,
                       password=password)
         sumR = random.randint(500, 5000)
         Account.create(
             sum=sumR,
             ID_offer=Offer.get(Offer.ID_offer == 1),
             ID_client=Client.get((Client.passport_seria == passport_seria)
                                  & (Client.passport_id == passport_id)),
             date_open=date.today())
         s = 1
         return s
     else:
         s = 2
         return s
Пример #4
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     # check if account already exists
     account = Account.query.filter_by(
         email=post_data.get('email')).one_or_none()
     if not account:
         try:
             account = Account(email=post_data.get('email'),
                               password=post_data.get('password'))
             account.save()
             # generate auth token
             aut_token = account.encode_auth_token()
             response = {
                 'status': 'success',
                 'message': 'Successfully registered.',
                 'auth_token': aut_token.decode()
             }
             return make_response(jsonify(response)), 201
         except Exception as e:
             response = {
                 'status': 'fail',
                 'message': 'Some error occurred. Please try again.'
             }
             return make_response(jsonify(response)), 401
     else:
         response = {
             'status': 'fail',
             'message': 'User already exists. Please log in.'
         }
         return make_response(jsonify(response)), 202
Пример #5
0
 def add_credit(id_client, id_offer, id_debet, sum):
     acc = Account.get(Account.ID_account == id_debet)
     acc.sum += sum
     acc.save()
     dateall = date.today()
     day = dateall.day
     month = dateall.month
     year = dateall.year
     period = (Offer.get(Offer.ID_offer == id_offer)).period
     percent = (Offer.get(Offer.ID_offer == id_offer)).percent
     year_period = period // 12
     if day == 31:
         day -= 1
     if year_period > 0:
         year += year_period
         period -= year_period * 12
     if month + period > 12:
         k = 12 - month
         period -= k
         year += 1
     month += period
     if month == 2 & day == 30:
         day = 28
     date_close = datetime(year, month, day)
     summonth = round(((sum * percent) / (100 * 12)) /
                      (1 - (1 / ((1 + (percent / (100 * 12)))**(period)))),
                      2)
     sumcred = summonth * period
     Account.create(sum=(sumcred * -1),
                    ID_offer=id_offer,
                    ID_client=id_client,
                    date_open=dateall,
                    date_close=date_close)
Пример #6
0
    def test_encode_auth_token(self):
        account = Account(email="*****@*****.**", password="******")

        account.save()
        auth_token = account.encode_auth_token()

        assert isinstance(auth_token, bytes)
Пример #7
0
    async def post(self):
        username = self.post_data.get('username', '')
        password = self.post_data.get('password', '')
        try:
            libs.validator.username(username)
            libs.validator.password(password)
        except libs.validator.ValidationError as e:
            self.send_to_client(-1, message=e.__str__())
            return
        if username == Config().password_login.get(
                'username') and password == Config().password_login.get(
                    'password'):
            pb_account = await AccountServer().get_account_by_id(
                account_id=int(Config().password_login.get('account_id')),
                app_id=self.app_id_int64,
                request_id=self.request_id)

            account = Account(pb_account)
            # get account userinfo
            if account.status == pbaccount_pb2.STATUS_ACTIVATED:
                pb_userinfo = await AccountServer().get_userinfo(
                    account.account_id,
                    app_id=self.app_id_int64,
                    request_id=self.request_id)
                await account.set_userinfo(pb_userinfo)
                self.send_to_client(0, message='登陆成功', response=account.dump())
            else:
                self.send_to_client(-1, message='登录状态异常')

        else:
            self.send_to_client(-1, message='账号或密码错误')
Пример #8
0
 def transferfrom(sum, id_account_from):
     if (sum < Account.get(Account.ID_account == id_account_from).sum):
         acc = Account.get(Account.ID_account == id_account_from)
         acc.sum -= sum
         acc.save()
         return 1
     else:
         return 2
 def get_account(self, client_id):
     sql = 'SELECT * FROM account WHERE cl_id = %s'
     cursor = connection.cursor()
     cursor.execute(sql)
     records = cursor.fetchall()
     account_list = []
     for record in records:
         account = Account(record[0], record[1], record[2])
         account_list.append(account.json())
     return account_list
Пример #10
0
def create_account():
    if not request.json:
        return jsonify({'error': 'bad request'}), 400
    if 'username' not in request.json or 'password' not in request.json or 'firstname' not in request.json or 'lastname' not in request.json:
        return jsonify({'error': 'bad request'}), 400

    username = request.json['username']
    password = request.json['password']
    first = request.json['firstname']
    last = request.json['lastname']

    uniqueUsername = Account().username_preventduplicate(username)
    if uniqueUsername == None:
        new_account = Account(username=username,
                              balance=0,
                              first=first,
                              last=last)
        new_account.set_password(password)
        new_account.generate_api_key()
        new_account.save()
        return jsonify(
            {
                "Your account was created successfully.":
                "You start with a balance of $0.00"
            }, {"Your api key is": new_account.values['api_key']})
    else:
        return jsonify({"error": "bad username"})
Пример #11
0
 def payment(sum, acc_from, acc_to):
     if (sum < Account.get(Account.ID_account == acc_from).sum):
         acc = Account.get(Account.ID_account == acc_from)
         acc.sum -= sum
         acc.save()
         acc2 = Account.get(Account.ID_account == acc_to)
         acc2.sum += sum
         acc2.save()
         return 1
     else:
         return 2
Пример #12
0
 def verify_email(username):
     account = Account.query.filter(Account.username == username, Account.confirmed == True).first()
     if account is not None:
         raise ServiceException(ErrorCode.FAIL, 'email = %s exists' % username)
     account = Account.query.filter(Account.username == username, Account.confirmed == False).first()
     if account is not None:
         return account
     account = Account()
     account.username = username
     db.session.add(account)
     db.session.commit()
     return account
Пример #13
0
    def post(self):
        user = users.get_current_user()

        name = self.request.get("nameAccount", "none")
        description = self.request.get("descriptionAccount", "none")

        #Store the answer
        new_account = Account(name=name, description=description, id_user=user.user_id())
        new_account.put()
        time.sleep(1)

        self.redirect("/accounts")
Пример #14
0
    async def post(self):
        code = self.post_data.get('code', None)
        if not code:
            raise HTTPError(400, "code为空?", reason="code为空?")

        # login to fetch openid/session_key/unionid
        login_response = await WxCCServer().miniprogram_login(
            code, self.request_id)
        if login_response is None:
            raise HTTPError(500, "登录微信服务器出错", reason="登录微信服务器出错")

        # get account
        exists_wechat = await AccountServer().exists_partner_wechat(
            identifier=login_response.unionid,
            app_id=self.app_id_int64,
            request_id=self.request_id)

        if not exists_wechat:
            # create account
            pb_account = await AccountServer().create_account_by_partner(
                partner=pbaccount_pb2.PARTNER_WECHAT,
                identifier=login_response.unionid,
                origin_data={},
                app_id=self.app_id_int64,
                request_id=self.request_id)
            # 分配空间
            await MembershipServer().set_total_storage_change(
                account_id=pb_account.account_id,
                changed_value=Config().membership.get("register_default_size"),
                title=Config().membership.get("register_default_title"),
                details=Config().membership.get("register_default_details"),
                request_id=self.request_id)
        else:
            pb_account = await AccountServer().auth_partner_account(
                identifier=login_response.unionid,
                app_id=self.app_id_int64,
                request_id=self.request_id)

            # set account pair to wxcc server
        await WxCCServer().miniprogram_set_account_pair(
            account_id=pb_account.account_id,
            login_response=login_response,
            request_id=self.request_id)

        account = Account(pb_account)
        pb_userinfo = await AccountServer().get_userinfo(
            account.account_id,
            app_id=self.app_id_int64,
            request_id=self.request_id)
        await account.set_userinfo(pb_userinfo)

        self.send_to_client(0, message='登录成功', response=account.dump())
Пример #15
0
 def test_generate_api_key(self):
     user = Account(username='******', balance=10000)
     user.set_password('1234')
     user.save()
     user.generate_api_key()
     reloaded = Account.login('some_user', '1234')
     self.assertEqual(
         user.values['api_key'], reloaded.values['api_key'],
         "check that the user's api_key is the same as the one generated")
Пример #16
0
 def test_login(self):
     password = '******'
     user = Account.login('sami', password)
     self.assertIsInstance(
         user, Account,
         'if the username and password match what is in db, login returns an Account object'
     )
Пример #17
0
	def upgrade_awards(self, qt):
		for proficiency, type in self.awarded_proficiencies.items():
			logging.info('upgrading awards for user %s and proficiency %s', qt.unique_identifier, proficiency)
			#topic_list = self.topics_in_proficiency[proficiency]   - Only Needed if we need all the topics in the proficiency
			if type == "fluency": rankings = self.fluency[proficiency]
			if type == "excellence": rankings = self.excellence[proficiency]
			this_account = Account.get_by_key_name(qt.unique_identifier)
			this_profile = Profile.get_by_key_name(qt.unique_identifier)
			if not this_account: 
			    this_account = register_account(qt.unique_identifier)
			award_topics = [] 
			award_levels = []
			for rank_dict in rankings:
				for topic, level in rank_dict.items():
					award_topics.append(topic)
					award_levels.append(level)
					
			# make sure that awards are not duplicated - can we avoid the loop in general? 
			award_key_name = str(this_profile.unique_identifier) + str(proficiency.name) + str(type) # you can get more than one type of award per proficiency
			new_award = Award.get_or_insert(key_name = award_key_name,
			                   type = type,
			                   topics = award_topics,
			                   levels = award_levels,
			                   proficiency = proficiency,
			                   winner = this_profile )
			self.save_awards.append(new_award)
Пример #18
0
def register_account(user_key, nickname, save=True):
    new_account = Account.get_or_insert(key_name = user_key,
                                     unique_identifier = user_key, # redundancy
                                     nickname = nickname # redundancy 
                                     )
    if save: new_account.put()
    return new_account                                   
Пример #19
0
def set_routing_number(api_key):
    api_login_attempt = Account.api_authenticate(api_key)
    if not request.json:
        return jsonify({'error': 'bad request'}), 400
    if 'set_routing_number' not in request.json:
        return jsonify({'error': 'bad request'}), 400
    if api_login_attempt != None:
        api_login_attempt.set_routing_number(
            request.json['set_routing_number'])
        return jsonify(
            {'routing_number': api_login_attempt.values['routing_number']})


#pep3333 --> wsgi | uwhiskey --> uses binary language (not py)
#using nginx instead of apache (open-source and free, apache is bad for scaling will crash after 10k users at the same time)

#swap reassign some requests from RAM to disk temporarily

#ADD UNIT TESTS FOR ALL ROUTES

#CRON --> linux scheduler to check for updates and run codes at certain times
#^ good to test that your flask app is running

#selenium will move the mouse and click on shit for you --> can do "headless" as well

#push to github prior to deploying
Пример #20
0
 def Get_debet(ID_client):
     id_debet = []
     debet_account = Account.select().where(Account.ID_client == ID_client,
                                            Account.ID_offer == 1)
     for it in debet_account:
         id_debet.append(it.ID_account)
     return id_debet
Пример #21
0
        def CountRemaining(futurekey, cursor):
            logging.debug("Got here")
            accounts, cursor, kontinue = Account.query().fetch_page(
                100, start_cursor=cursor)

            numaccounts = len(accounts)

            if kontinue:
                lonallchildsuccessf = GenerateOnAllChildSuccess(
                    futurekey, numaccounts, lambda a, b: a + b)

                future(CountRemaining,
                       parentkey=futurekey,
                       queue="background",
                       onallchildsuccessf=lonallchildsuccessf)(cursor)

                logging.debug("raising")

            setlocalprogress(futurekey, numaccounts)

            if kontinue:
                raise FutureReadyForResult("still calculating")
            else:
                logging.debug("leaving")
                return numaccounts
Пример #22
0
 def Get_credit(ID_client):
     id_credit = []
     account = Account.select().where((Account.ID_client == ID_client))
     for it in account:
         if Offer.get(Offer.ID_offer == it.ID_offer).type == ('credit'):
             id_credit.append(it.ID_account)
     return id_credit
Пример #23
0
def buy_stock(api_key):
    api_login_attempt = Account.api_authenticate(api_key)
    if not request.json:
        return jsonify({'error': 'bad request'}), 400
    if 'ticker' not in request.json or 'shares' not in request.json:
        return jsonify({'error': 'bad request'}), 400
    ticker = request.json['ticker']
    shares = request.json['shares']

    api_login_attempt.buy(ticker, shares)

    new_position = api_login_attempt.get_position_for(ticker)
    return jsonify(
        {"purchase successful, new position is": new_position.json()})


#pep3333 --> wsgi | uwhiskey --> uses binary language (not py)
#using nginx instead of apache (open-source and free, apache is bad for scaling will crash after 10k users at the same time)

#swap reassign some requests from RAM to disk temporarily

#ADD UNIT TESTS FOR ALL ROUTES

#CRON --> linux scheduler to check for updates and run codes at certain times
#^ good to test that your flask app is running

#selenium will move the mouse and click on shit for you --> can do "headless" as well

#push to github prior to deploying
Пример #24
0
    def get(self):
        user = users.get_current_user()

        if user == None:
            self.redirect("/")
        else:
            # Look for the user's information
            user_id = user.user_id()
            name_info = user.nickname()
            stored_user = User.query(User.id_user == user_id)

            if stored_user.count() == 0:
                # Store the information
                img = User(id_user=user_id, name=name_info)
                img.put()
                time.sleep(1)



            accounts = Account.query(Account.id_user == user_id).order(Account.name)

            template_values = {
                'title': "Accounts",
                'accounts': accounts,
                'user_nickname': user.nickname(),
                'user_logout': users.create_logout_url("/"),
                'user_id': user.user_id()
            }

            template = JINJA_ENVIRONMENT.get_template("accounts.html")
            self.response.write(template.render(template_values));
Пример #25
0
 def test_api_authenticate(self):
     api_key = "12345678912345678902"
     login_with_api = Account.api_authenticate(api_key)
     self.assertIsInstance(
         login_with_api, Account,
         'checks that an instantiated Account class is returned after authenticating api'
     )
Пример #26
0
def delete_user(user_key):
  # check in case entity was sent
  if type(user_key).__name__ == "Profile":
    user_key = user_key.key()
  # this will only work with dummy users
  # does not yet get links, etc.
  # best for after messing up and creating a wrong user   
  from model.account import Account
  from model.user import Profile, QuizTaker
  from model.activity import ActivityProfile, UserTopicScores, PostedLink, Scoop, SharedItem
  from model.sponsor import Sponsor, Pledge
  from model.student import Student
  from model.timeline import ProfileTimeline
  
  delete = []    
  p = Profile.get(user_key)
  if p:
    delete.append(p)
  else:
    logging.error('unable to delete user. User key %s not found' % user_key)
    return False
  student = p.student.get()
  if student:
    delete.append(student)
    delete.extend(student.pledges.fetch(50))
  sponsor = p.sponsor.get()
  if sponsor:
    delete.append(sponsor)
    delete.extend(sponsor.pledges.fetch(50))
  key_name = p.key().name()
  failed_links = []
  activity_profiles = p.activity_profiles.fetch(5)
  for a in activity_profiles:
    if a:  
      delete.append(a)
      links = a.links.fetch(1000)
      failed_links.extend(links)
  delete_links(failed_links)
  ts = p.topic_scores.get()
  if ts:
    delete.append(ts)
  ac = Account.get_by_key_name(key_name)
  if ac:
    delete.append(ac)
  shared_items = p.shared_items.fetch(300)
  if shared_items:
    delete.extend(shared_items)
  pt = p.timeline.get()
  if pt:
    delete.append(pt)
  qt = QuizTaker.get_by_key_name(key_name)
  if qt:
    delete.append(qt)
  
  delete.extend(Scoop.all().filter(
    'scooper IN', [a.key() for a in activity_profiles]).fetch(1000))
  delete.extend(Scoop.all().filter(
    'scooped IN', [a.key() for a in activity_profiles]).fetch(1000))                      
  logging.error('deleting %d entities - %s' % (len(delete), str([e.key() for e in delete])))
  db.delete(delete)
Пример #27
0
    def post(self):
        request = get_post_json(self.request)
        if (not request):
            return self.finish({
                'code': RESP['ERROR']['CODE'],
                'msg': RESP['ERROR']['MSG']
            })
        account = Account.get_by_pk(request['id'])
        account.edit(request)
        old_asks = AccountAsk.get_by_account(account)

        update_asks_id = []
        times = 0
        for new_ask in request['asks']:
            try:
                account_ask = AccountAsk.get_by_ask(account, new_ask['ask'])
                account_ask.edit(new_ask)
                update_asks_id.append(new_ask['id'])
            except DoesNotExist:
                new_ask['account'] = account
                pass_ask = AccountAsk.new(new_ask)
                update_asks_id.append(pass_ask.id)
        for old_ask in old_asks:
            if not old_ask.id in update_asks_id:
                old_ask.remove()

        return self.finish({
            'code': RESP['SUCCESS']['CODE'],
            'msg': RESP['SUCCESS']['MSG']
        })
Пример #28
0
def get_trades_for(api_key, ticker):
    api_login_attempt = Account.api_authenticate(api_key)
    if api_login_attempt != None:
        trades = api_login_attempt.trades_for(ticker)
        return jsonify({"trades": [trade.json() for trade in trades]
                        })  #should i remove pk from response? YES
    else:
        return jsonify({"error": "404"})
Пример #29
0
    def deleteAccount(self, network, name):
        account = Account.getAccount(network, name)
        am = AccountManager()

        if account and am.remove(account):
            print 'Delete {0} account {1} : OK'.format(network, name)
        else:
            print 'Delete {0} account {1} : FAIL'.format(network, name)
        def AddFreeCredit(creditamount):
            def IncrementBalance(account, headers):
#                 headers = kwargs.get("headers")
                logging.debug("headers: %s" % headers)
                account.balance += creditamount
                account.put()
                
            ndbshardedmap(IncrementBalance, Account.query(), includeheaders = True)
 def AddFreeCredit(creditamount):
     def IncrementBalance(futurekey, account):
         account.balance += creditamount
         account.put()
         return 1
         
     futureobj = futurendbshardedmap(IncrementBalance, Account.query(), queue="background")
     return futureobj.key
    def _extract_account(self, headerContainer: BeautifulSoup) -> Account:
        account_container = headerContainer.select('a.account-group')[0]
        account_id = int(account_container.attrs['data-user-id'])
        account_href = account_container.attrs['href']
        full_name = headerContainer.select(
            'span.FullNameGroup > strong.fullname')[0].text

        return Account(account_id, full_name, account_href)
Пример #33
0
 def put_account(cl_id, account_id):
     account = Account.json_parse_account(request.json)
     account.account_id = int(account_id)
     try:
         AccountService.update_account(account)
         return jsonify(account.json()), 200
     except ValueError:
         print("Not Found")
Пример #34
0
    def createConfig(self, overwrite = False):
        if self.existsConfig() and not overwrite:
            return False

        config = {'app' : {}, 'accounts' : {net:[] for net in Account.supportedNetworks()}}

        with open(PersistenceManager.configFileName, 'w') as configFile:
            json.dump(config, configFile, indent = 4)

        return True
Пример #35
0
    def createAccount(self, network, name):
        account = Account.getAccount(network, name)
        am = AccountManager()

        if account and am.create(account):
            print 'Create {0} account {1} : OK'.format(network, name)

            accountType = Account.networkToAccount(network)
            callback = None

            if accountType == 'OAuth':
                callback = self.enterOAuthVerifier
            elif accountType == 'UserPass':
                callback = self.enterUserPass

            if callback and am.register(account, callback):
                print 'Register {0} account {1} : OK'.format(network, name)
            else:
                print 'Register {0} account {1} : FAIL'.format(network, name)
                am.remove(account)
        else:
            print 'Create {0} account {1} : FAIL'.format(network, name)
Пример #36
0
  def get(self):
	# Now prepared.html contains the full google checkout button html
	account = Account.get_by_key_name(self.session['user'])
	account.pass_count = 1
	account.put()
	try: pass_count = account.pass_count
	except: # no pass count yet
	    try: 
	        account.pass_count = 1      # this is just to upgrade model.
	        pass_count = account.pass_count
	    except: 
	        from accounts.methods import register_account
	        register_account(self.session['user'])
	        account = Account.get_by_key_name(self.session['user'])
	        account.pass_count = 1
	        pass_count = account.pass_count
	        # take previous block out
	        
	         
	    account.put()
	test = self.get_test()
	template_values = {'pass_count': pass_count}
	path = tpl_path(STORE_PATH +'take_test.html')
	self.response.out.write(template.render(path, template_values))
Пример #37
0
 def networks(self):
     print 'Networks:'
     k = 1
     for network in Account.supportedNetworks():
         print '\t[{0}] {1} (Authentication: {2})'.format(k, network, Account.networkToAccount(network))
         k += 1