def get_user(id): try: id = int(id) except: print("Invalid ID") return {"error": "Invalid ID"}, 400 if not session.get('logged_in') or session['user']["id"] != id: return {'error': 'Authentication failed'}, 401 db = DBConnection() user_query = "select * from user where id={}".format(id) db.cursor.execute(user_query) data = db.cursor.fetchone() if not data: return {'error': 'User does not exists'}, 404 print(data) response = { "id": data[0], "fname": data[1], "lname": data[2], "email": data[3], "type": data[5] } return response
def get_companies(): company_query = "select * from company" if not session.get('logged_in'): return {'error': 'Authentication failed'}, 401 db = DBConnection() try: db.cursor.execute(company_query) result = db.cursor.fetchall() except Exception as e: print(e) return {"error": "Error while getting the companies"}, 500 response = [] for item in result: temp = { "id": item[0], "name": item[1], "code_name": item[2], "total_stocks": item[3], "address": item[4], "about": item[5] } response.append(temp) return jsonify(response)
def create_wallet(): try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 user = request_body.get('user') if not user: return {'error': 'User ID is required'}, 400 if not session.get('logged_in') or session['user']["id"] != user: return {'error': 'Authentication failed'}, 401 wallet_amount = 0 wallet = get_user_wallet(user) if wallet: return {'error': 'Wallet for user already exists'}, 400 wallet_create_query = """insert into wallet (owner, wallet_amount) VALUES ('{}', '{}')""".format( user, wallet_amount) db = DBConnection() try: db.cursor.execute(wallet_create_query) db.conn.commit() except Exception as e: db.conn.rollback() print(e) return {"error": "Error while creating the wallet for user"}, 500 wallet = get_user_wallet(user) return wallet
def get_txns(id): if not session.get('logged_in'): return {'error': 'Authentication failed'}, 401 try: uid = int(id) except: print("Invalid user ID") return {"error": "Invalid ID"}, 400 txn_query = "select * from transactions where user={}".format(uid) db = DBConnection() try: db.cursor.execute(txn_query) result = db.cursor.fetchall() except Exception as e: print(e) return {"error": "Error while getting the transactions"}, 500 response = [] for item in result: temp = { "id": item[0], "type": item[1], "price": item[2], "qty": item[3], "date_time": item[4], "amount": item[5], "user": item[6], "stock": item[7] } response.append(temp) return jsonify(response)
def get_stock_by_id(id): db = DBConnection() stock_query = """select stock.id, current_price, available_stocks, company.id as companyID, name, total_stocks, address, about, code_name from stock join company on stock.company=company.id where stock.id={}""".format(id) db.cursor.execute(stock_query) data = db.cursor.fetchone() if not data: return stock = { "id": data[0], "current_price": data[1], "available_stocks": data[2], "company": data[3], "name": data[4], "total_stocks": data[5], "address": data[6], "about": data[7], "code_name": data[8] } return stock
def get_price_history(id): if not session.get('logged_in'): return {'error': 'Authentication failed'}, 401 try: id = int(id) except: print("Invalid ID") return {"error": "Invalid ID"}, 400 stock = get_stock_by_id(id) if not stock: return {"error": 'Stock does not exists'}, 404 price_history_query = "select datetime, price from price_history where stock={} ORDER BY datetime desc".format( id) db = DBConnection() db.cursor.execute(price_history_query) data = db.cursor.fetchall() response = [] for item in data: temp = {} temp['datetime'] = item[0] temp['price'] = item[1] response.append(temp) return jsonify(response)
def get_portfolio(id): try: uid = int(id) # request_body = json.loads(request.data) except: return {"error": 'Invalid ID'}, 400 if not session.get('logged_in') or session['user']['id'] != uid: return {'error': 'Authentication failed'}, 401 # uid = request_body.get('id') print(uid) # if not uid: # return {'error': 'User ID is required'}, 400 portfolio_query = "select * from all_portfolio where USERID={}".format(uid) db = DBConnection() try: db.cursor.execute(portfolio_query) result = db.cursor.fetchall() except Exception as e: print(e) return {"error": "Error while getting the portfolio"}, 500 response = [] if len(result) > 0: u = { "User ID": result[0][0], "User Firstname": result[0][1], "Buying Power": result[0][6] } response.append(u) for item in result: temp = { "Ticker": item[2], "Share Price": item[3], "No. of Shares owned": item[4], "Value of these shares": item[5] } response.append(temp) else: profile_query = "select * from all_profiles where USERID={}".format( uid) try: db.cursor.execute(profile_query) result = db.cursor.fetchone() except Exception as e: print(e) return {"error": "Error while getting the user profiles"}, 500 u = { "User ID": result[0], "User Firstname": result[1], "Buying Power": result[2] } response.append(u) return jsonify(response)
def get_stocks(): if not session.get('logged_in'): return {'error': 'Authentication failed'}, 401 stock_query = """select stock.id, current_price, available_stocks, company.id as companyID, name, total_stocks, address, about, code_name from stock join company on stock.company=company.id""" db = DBConnection() try: db.cursor.execute(stock_query) result = db.cursor.fetchall() except Exception as e: print(e) return {"error": "Error while getting the companies"}, 500 response = [] for item in result: temp = { "id": item[0], "current_price": item[1], "available_stocks": item[2], "company": item[3], "name": item[4], "total_stocks": item[5], "address": item[6], "about": item[7], "code_name": item[8] } response.append(temp) return jsonify(response)
def update_company(id): if not session.get('logged_in') or session['user']["type"] != "admin": return {'error': 'Authentication failed'}, 401 try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 try: id = int(id) except: print("Invalid ID") return {"error": "Invalid ID"}, 400 company = get_company_by_id(id) if not company: return {'error': 'Company does not exists'}, 404 update_string = '' if request_body.get('name'): update_string += "name='{}'".format(request_body['name']) if request_body.get('total_stocks') is not None and type( request_body.get('total_stocks')) != str: update_string += "total_stocks={}".format(request_body['total_stocks']) if request_body.get('address'): if update_string: update_string += ", " update_string += "address='{}'".format(request_body['address']) if request_body.get('about'): if update_string: update_string += ", " update_string += "about='{}'".format(request_body['about']) if not update_string: return company else: update_string += ' ' update_query = """Update company set {update} where id={id}""".format( update=update_string, id=id) print(update_query) db = DBConnection() try: db.cursor.execute(update_query) db.conn.commit() except Exception as e: db.conn.rollback() print(e) return {"error": "Error while updating the company"}, 500 company = get_company_by_id(id) return company
def enroll(): db = DBConnection() success, dbId = db.addUserCredentials() if success != True: return False, None dbUsername, dbPassword = db.getUserCredentials(dbId) print('Starting the Enrollment process') counter = 0 while counter < 2: print('Sample => {}'.format(counter + 1)) username = input('Enter username:\n').strip() if username != dbUsername: print('Removed the sample as username did not match') continue print('Enter password:') user = linuxGetTimelog.User(dbId, dbUsername, dbPassword) success, date = user.startLogging() if success == True: extractFeatures(dbId, date) addToCSV(dbId, date) counter += 1 sys.stdout.flush(); tcflush(sys.stdin, TCIOFLUSH) db.closeConnection() global userId userId = dbId print("Enrollment Process over") return True, userId
def register(): session['logged_in'] = False try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 email = request_body.get('email') if not email: return {"error": "Email is required"}, 400 db = DBConnection() email_exists_query = "select * from user where email='{}'".format(email) db.cursor.execute(email_exists_query) data = db.cursor.fetchone() if data: return {"error": "Email is already registered"}, 400 if not re.match(r'[^@]+@[^@]+\.[^@]+', email): return {"error": "Invalid email"}, 400 try: fname = request_body['first_name'] lname = request_body['last_name'] password = request_body['password'] user_type = request_body['type'] except: print("Missing required field") return {"error": "Missing required field"}, 400 salt = bcrypt.gensalt() password = bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8') print(password) insert_query = """insert into user(fname, lname, email, password, type) values('{}', '{}', '{}', "{}", '{}')""".format( fname, lname, email, password, user_type) try: db.cursor.execute(insert_query) db.conn.commit() except Exception as e: db.conn.rollback() print(e) return {"error": "Error while registring the user"}, 500 retrieve_query = "select id, fname, lname, email, type from user where email='{}'".format( email) db.cursor.execute(retrieve_query) user_data = db.cursor.fetchone() user_data_json = {} user_data_json['id'] = user_data[0] user_data_json['fname'] = user_data[1] user_data_json['lname'] = user_data[2] user_data_json['email'] = user_data[3] user_data_json['type'] = user_data[4] return user_data_json
def get_user_wallet(id): db = DBConnection() wallet_query = "select * from wallet where owner={}".format(id) db.cursor.execute(wallet_query) data = db.cursor.fetchone() if not data: return wallet = {'id': data[0], 'owner': data[1], 'wallet_amount': data[2]} return wallet
def update_company_stocks(id): if not session.get('logged_in') or session['user']["type"] != "admin": return {'error': 'Authentication failed'}, 401 try: id = int(id) except: print("Invalid ID") return {"error": "Invalid ID"}, 400 try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 stock = get_stock_by_company(id) if not stock: return {'error': 'Stock does not exists'}, 404 stockId = stock['id'] db = DBConnection() current_price = request_body.get('current_price') available_stocks = request_body.get('available_stocks') if not current_price and not available_stocks: return {'error': 'Missing required fields'}, 400 if current_price and available_stocks: return {'error': 'You can update only one parameter at a time'}, 400 if current_price: db.cursor.callproc("updatePrice", (stockId, current_price)) else: update_query = "update stock set available_stocks={} where id={}".format( available_stocks, stockId) try: db.cursor.execute(update_query) db.conn.commit() except Exception as e: db.conn.rollback() print(e) return {'error': "Error while updating the data"}, 500 stock = get_stock_by_company(id) return stock
def create_company(): if not session.get('logged_in') or session['user']["type"] != "admin": return {'error': 'Authentication failed'}, 401 try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 name = request_body.get('name') code_name = request_body.get('code') if name is None or code_name is None: return {'error': 'Missing required field'}, 400 company = get_company_by_code(code_name) if company: return {'error': 'Company code already used'}, 400 total_stocks = request_body.get('total_stocks', 0) address = request_body.get('address', '') about = request_body.get('about', '') company_create_query = """insert into company (name, code_name, total_stocks, address, about) VALUES ('{name}', '{code_name}', {total_stocks}, '{address}', '{about}')""".format( name=name, code_name=code_name, total_stocks=total_stocks, address=address, about=about) db = DBConnection() try: db.cursor.execute(company_create_query) db.conn.commit() except Exception as e: db.conn.rollback() print(e) return {"error": "Error while creating the company"}, 500 company = get_company_by_code(code_name) return company
def testModel(userId): print('Let us test the created model') db = DBConnection() dbUsername, dbPassword = db.getUserCredentials(userId) username = input('Enter username:\n').strip() if username != dbUsername: print('Removed the sample as username did not match') return print('Enter password:'******'data/user_input/{}/userData.csv'.format(userId), header=0).tail(1) X = userData[[ 'release_codes', 'pp', 'pr', 'rp', 'rr', 'ppavg', 'pravg', 'rpavg', 'rravg', 'total' ]] X = get_hashed_matrix(X) names = [ "Isolation Forest Ensemble", ] classifiers = [ IsolationForest(random_state=np.random.RandomState(42)), ] for name, clf in zip(names, classifiers): # print("\nLoading classifier : {}".format(name)) clf = joblib.load('data/user_input/{}/userModel-{}.pkl'.format( userId, name)) result = clf.predict(X) if result[0] == 1: print('Welcome') else: print('Stay away impostor!') # testModel(114)
def get_company_by_id(id): db = DBConnection() company_query = "select * from company where id={}".format(id) db.cursor.execute(company_query) data = db.cursor.fetchone() if not data: return company = { 'id': data[0], 'name': data[1], 'code_name': data[2], 'total_stocks': data[3], 'address': data[4], 'about': data[5] } return company
def update_wallet(id): try: id = int(id) except: print("Invalid ID") return {"error": "Invalid ID"}, 400 wallet = get_wallet_by_id(id) if not wallet: return {'error': 'Wallet does not exists'}, 404 if not session.get( 'logged_in') or session['user']["id"] != wallet['owner']: return {'error': 'Authentication failed'}, 401 try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 wallet_amount = request_body.get('wallet_amount') if wallet_amount is None: return {'error': 'Missing required field'}, 400 wallet_update_query = """update wallet set wallet_amount={} where id={}""".format( wallet_amount, id) db = DBConnection() try: db.cursor.execute(wallet_update_query) db.conn.commit() except Exception as e: db.conn.rollback() print(e) return {"error": "Error while updating the wallet for user"}, 500 wallet = get_wallet_by_id(id) return wallet
def login(): try: request_body = json.loads(request.data) except: return {"error": "Invalid request body"}, 400 try: email = request_body['email'] password = request_body['password'] except: print("Missing required field") return {"error": "Missing required field"}, 400 db = DBConnection() email_exists_query = "select * from user where email='{}'".format(email) db.cursor.execute(email_exists_query) data = db.cursor.fetchone() if not data: return {'error': 'Invalid email or password'}, 401 stored_pwd = data[4] if not bcrypt.checkpw(password.encode('utf-8'), stored_pwd.encode('utf-8')): print("Invalid password") return {'error': "Authentication failed"}, 401 session['logged_in'] = True response = { "id": data[0], "fname": data[1], "lname": data[2], "email": data[3], "type": data[5] } session['user'] = response return response
def create_stock(): if not session.get('logged_in') or session['user']["type"] != "admin": return {'error': 'Authentication failed'}, 401 try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 company = request_body.get('company') if company is None: return {'error': 'Missing required field'}, 400 current_price = request_body.get('current_price', 0) available_stocks = request_body.get('available_stocks', 0) stock = get_stock_by_company(company) if stock: return {'error': 'Company stock already exists'}, 400 stock_create_query = """insert into stock (company, current_price, available_stocks) VALUES ({company}, {current_price}, {available_stocks})""".format( company=company, current_price=current_price, available_stocks=available_stocks) db = DBConnection() try: db.cursor.execute(stock_create_query) db.conn.commit() except Exception as e: db.conn.rollback() print(e) return {"error": "Error while creating the stock"}, 500 stock = get_stock_by_company(company) return stock
def sell(): try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 user = request_body.get('user') print(user) if not user: return {'error': 'User ID is required'}, 400 if not session.get('logged_in') or session['user']["id"] != user: return {'error': 'Authentication failed'}, 401 try: stock = request_body['stock_id'] qty = request_body['quantity'] except: print("Missing required field") return {"error": "Missing required field"}, 400 print(stock) print(qty) db = DBConnection() stock_exists_query = "select * from company where code_name='{}'".format( stock) db.cursor.execute(stock_exists_query) data = db.cursor.fetchone() if not data: return {"error": "Stock assigned to sell does not exist"}, 400 try: db.cursor.callproc("sellStock", (stock, qty, user)) except: return {"error": "Selling Failed"}, 400 return {"Success": "Selling Request Completed Successfully "}, 200
def deposit(): try: request_body = json.loads(request.data) except: return {"error": 'Invalid request body'}, 400 user = request_body.get('user') print(user) if not user: return {'error': 'User ID is required'}, 400 if not session.get('logged_in') or session['user']["id"] != user: return {'error': 'Authentication failed'}, 401 try: dep_amt = request_body.get('deposit_amount') except: print("Missing required field") return {"error": "Missing required field"}, 400 print(dep_amt) if dep_amt <= 0: return {"error": "Deposit at least 1 dollar"}, 400 db = DBConnection() data = get_user_wallet(user) if not data: return {"error": "There's no wallet related to this User"}, 400 try: db.cursor.callproc("depositAmount", (dep_amt, user)) except: return {"error": "Deposit Failed"}, 400 return {"Success": "Deposit Request Completed Successfully "}, 200
from Manager import Manager from dbConnection import DBConnection from flask import Flask from flask import request import requests app = Flask(__name__) # creating the device object lotManager = Manager() # create the database connection for it managerCon = DBConnection() if managerCon.createConnection(): print("Conection successful") print("Lots avaliable are: "+str(lotManager.lotsAvailable)) # write the API's for it @app.route("/") def home(): return "Home app of the Manager App" @app.route("/receiveStateChange") def receiveStateChange(): device = 'None' device = request.args.get('device') if device == 'lot':
from user import User from dbConnection import DBConnection import pytest import argparse from csv import reader import base64 import os import hashlib db = DBConnection() def main(): with open('MOCK_DATA.csv', 'r') as read_obj: # pass the file object to reader() to get the reader object csv_reader = reader(read_obj) testUsers(csv_reader) def test_connection(): # assume rethinkdb is running, otherwise connection will fail with db.createConnection("database.db") as conn: assert conn.is_open() == True def testUsers(userRows): header = next(userRows) if header != None: for elem in userRows:
from Device import Device from dbConnection import DBConnection from flask import Flask from flask import request from datetime import datetime from status_led import status_change_led import requests app = Flask(__name__) # creating the device object lotSensor = Device() # create the database connection for it deviceCon = DBConnection() if deviceCon.createConnection(): print("Conection successful") # setting up the base tables for the database deviceCon.setupTables() # write the API's for it @app.route("/") def home(): return "Home app of the Device App" @app.route("/receiveStateChange") def receiveStateChange(): lotSensor.receiveStateChange() #timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')