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"})
def test_encode_auth_token(self): account = Account(email="*****@*****.**", password="******") account.save() auth_token = account.encode_auth_token() assert isinstance(auth_token, bytes)
def seed(dbpath=DBPATH): ORM.dbpath = dbpath default = Account(username='******', balance=10000.00, first='sami', last='s', api_key="12345678912345678902") default.set_password('1234') default.save() default_buy = Trade(buy_sell='Buy', username='******', ticker='tsla', price='100', shares='10', time=time()) default_buy.save() default_sale = Trade(buy_sell='Sell', username='******', ticker='tsla', price='110', shares='5', time=time()) default_sale.save() default_position = Position(username='******', ticker='tsla', shares='5') default_position.save()
def get_account_details(self, id=None): self.id = id data_rows = None account_dictionary = {} accounts_list = [] with DatabaseConnect() as cursor: if self.id is None: sql_select_query = "select * from account_master" cursor.execute(sql_select_query) else: sql_select_query = """select * from account_master where id = %s""" cursor.execute(sql_select_query, (self.id, )) data_rows = cursor.fetchall() print("Total number of rows: ", cursor.rowcount) for each_record in data_rows: account_object = Account() account_object.id = each_record[0] account_object.type = each_record[1] account_object.open_date = SerializeObject.serialize_object( each_record[2]) account_object.isActive = each_record[3] account_dictionary = ConvertToDictionary.convert_to_dictionary( account_object) accounts_list.append(account_dictionary) return accounts_list
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
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
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='账号或密码错误')
def create_account(self, account): sql = 'INSERT INTO account VALUES (DEFAULT, %s, %s) RETURNING *' cursor = connection.cursor() cursor.execute(sql, (account.account_id, account.account_balance, account.cl_id)) connection.commit() record = cursor.fetchone() new_account = Account(record[0], record[1], record[2]) return new_account
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)
def query_to_account(query_array): """ Maps database query to an Account object :param query_array: db query to convert :return: Account object or None if not found """ return Account(query_array[0], query_array[1], query_array[2]) if len(query_array) > 2 else None
def testQueryToAccount(self): mock_query_array = [12345678, 3333, 0.0] expected = Account(12345678, 3333, 0.0) account = queryMapper.query_to_account(mock_query_array) assert isinstance(account, Account) self.assertEqual(account.account_id, expected.account_id) self.assertEqual(account.pin, expected.pin) self.assertEqual(account.balance, expected.balance)
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")
class TempDBAccount: accounts = { 1: Account(client_id=0, account_id=0, account_type="Withdraw", amount=2000), 2: Account(client_id=1, account_id=1, account_type="Withdraw", amount=7000), 3: Account(client_id=2, account_id=2, account_type="Withdraw", amount=29000) }
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
def handle_account_config(key, value): if key.lower() == "account": contents = value.split(":") if len(contents) >= 8: account = Account() account.m_eServerType = eval("ServerType.{}".format(contents[0])) account.m_nServerId = int(contents[1]) account.m_szUserName = contents[2] account.m_szPassword = base64.b64decode(contents[3]) account.m_szRoleName = contents[7] return account
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")
def getAccountInfo(self): params = {"method": ACCOUNT_INFO} extra = {} response = send2api(params, extra) if response and "code" not in response: account = Account() account.btc_balance = float(response["available_btc_display"]) account.cny_balance = float(response["available_cny_display"]) account.btc_frozen = float(response["frozen_btc_display"]) account.cny_frozen = float(response["frozen_cny_display"]) return account return None
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
def post_account(): """post account request: { "username": "******" "password": "******" } """ json_data = request.get_json() username_length = current_app.config['USERNAME_LENGTH'] password_length = current_app.config['PASSWORD_LENGTH'] if not json_data or not isinstance(json_data, dict): return error(400, 'Json parse error.') password = str(json_data.get('password')) pwhash = make_hash(password) if not password or not valid_password(password, password_length): return error(400, 'Password invalid.') username = str(json_data.get('username')) if username: if not valid_password(username, username_length): return error(400, 'Username invalid.') account = Account.query.filter(Account.username == username).first() if account: return error(403, 'Account alredy exists.') else: account = Account(username=username, password=pwhash, super=0) db.session.add(account) db.session.commit() else: while 1: username = random_username(username_length) account = Account.query.filter( Account.username == username).first() if not account: account = Account(username=username, password=pwhash, super=0) db.session.add(account) db.session.commit() break data = {'username': account.username, 'super': account.super} return success(data)
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())
def MakeAccounts(numaccounts, headers): logging.debug(headers) logging.debug(numaccounts) if numaccounts <= 10: accounts = [] for _ in range(numaccounts): account = Account() account.balance = 0 accounts.append(account) ndb.put_multi(accounts) else: doaccounts = numaccounts while doaccounts > 0: batch = (numaccounts / 10) if ( (numaccounts / 10) <= doaccounts) else doaccounts MakeAccounts(batch) doaccounts -= batch
def test_register_with_already_registered_account(self): """Test registration with already registered email.""" account = Account( email='*****@*****.**', password='******' ) account.save() with self.client: response = register_account(self, '*****@*****.**', '123456') assert response.content_type == 'application/json' assert response.status_code == 202 data = json.loads(response.data.decode()) assert data['status'] == 'fail' assert data['message'] == 'User already exists. Please log in.'
def get_account(self, username): url = tools.ACCOUNT_PAGE.format(username) resp = self.__req.get(url, headers=self.generate_header()) if resp.status_code != 200: return None regx = r"\s*.*\s*<script.*?>.*_sharedData\s*=\s*(.*?);<\/script>" match_result = re.match(regx, resp.text, re.S) if match_result: data = json.loads(match_result.group(1)) # with open('./test.json', 'a') as f: # f.write(json.dumps(data)) account_data = tools.get_from_dict( data, ['entry_data', 'ProfilePage', 0, 'graphql', 'user']) if not account_data: return None account = Account(account_data) return account
def getAccountInfo(self): USERINFO_RESOURCE = "/api/v1/userinfo.do" params = {} params['api_key'] = APIKEY params['sign'] = buildMySign(params, SECRETKEY) response = httpPost(URL, USERINFO_RESOURCE, params) if response and response['result']: account = Account() account.btc_balance = float( response['info']['funds']['free']['btc']) account.cny_balance = float( response['info']['funds']['free']['cny']) account.btc_frozen = float( response['info']['funds']['freezed']['btc']) account.cny_frozen = float( response['info']['funds']['freezed']['cny']) return account return None
def test_check_password(self): user = Account() username = '******' user_info = user.one_from_where_clause('WHERE username = ?', (username, )) self.assertIsInstance( user_info, Account, 'one_from_where_clause returns an account object where its username matches the username we gave it' ) hashed_pw = user_info.values['password_hash'] self.assertIsInstance(hashed_pw, bytes, 'hashed_pw from db') password = '******' password = password.encode() self.assertEqual(util.bcrypt.checkpw(password, hashed_pw), True) #returns True or False
def test_save_and_pk_load(self): user = Account(username="******") user.save() self.assertIsInstance(user.values['pk'], int, 'save sets pk') pk = user.values['pk'] same_user = Account.one_from_pk(pk) self.assertIsInstance(same_user, Account, "one_from_pk loads an Account object") self.assertEqual(same_user.values['username'], "Greg", "save creates database row") same_user.values['username'] = "******" same_user.save() same_again = Account.one_from_pk(pk) self.assertEqual(same_again.values['username'], "Gregory", "save updates an existing row")
def insertAccount(self, accountdata): # only deutsche bank try: newAccount = Account(username=accountdata['username'], password=accountdata['password'], access_token={"hello": "world"}) bankofaccount = self.getBankByBic(accountdata['bic']) newAccount.setBank(bankofaccount) newIbans = [] for iban in accountdata['ibans']: ibanofaccount = Iban(iban=iban) ibanofaccount.setBank(bankofaccount) newIbans.append(ibanofaccount) newAccount.ibans = newIbans self.session.add(newAccount) self.session.commit() except: self.session.rollback() raise Exception("Could not insert account") pass
def test_save_and_pk_load(self): user = Account(username='******') user.save() self.assertIsInstance( user.values['pk'], int, 'save sets pk' ) #assert will always return a boolean - if we get false back, something is broken pk = user.values['pk'] same_user = Account.one_from_pk(pk) self.assertIsInstance(same_user, Account, 'one_from_pk loads an Account object') self.assertEqual(same_user.values['username'], 'Sami', 'save creates database row') same_user.values['username'] = '******' same_user.save() same_again = Account.one_from_pk(pk) self.assertEqual(same_again.values['username'], 'Gregory', 'save updates an exisiting row')
def get_accounts(self, cluster_id): accounts = [] try: query = """SELECT Id, Username, Password, Cluster, OrderInCluster, Status FROM accounts WHERE (Status = %s OR Status = %s) AND Cluster = %s ORDER BY OrderInCluster ASC;""" data_tuple = (constant.STATUS_ACCOUNT_ACTIVATED, constant.STATUS_ACCOUNT_ERROR_NOT_REPLACED, cluster_id) self.curr.execute(query, data_tuple) result = self.curr.fetchall() for r in result: account = Account(r[0], r[1], r[2], r[3], r[4], r[5]) accounts.append(account) result.clear() except mysql.connector.Error as error: logging.error('MySQL server is disconnected: ', str(error)) logging.info('Reconnect to Mysql server..') self.connect() self.get_accounts(cluster_id) return accounts
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 'first_name' not in request.json or 'last_name' not in request.json: return jsonify({'error': 'bad request'}), 400 username = request.json['username'] password = request.json['password'] first = request.json['first_name'] last = request.json['last_name'] pword_hash = hash_password(password) new_account = Account(username=username, password_hash=pword_hash, balance=10000, first=first, last=last) new_account.generate_api_key new_account.save() return jsonify( { "Your account was created successfully.": "You start with a balance of $10,000." }, {"Your api key is": new_account.values['api_key']})