def register(): # if method=GET take user to login page if request.method == 'GET': return render_template('login/register.html', page_header="Register") # if method=POST create a new username and password row in the users table elif request.method == 'POST': username = request.form.get('username') password = request.form.get('password') table = dynamodb.Table('Users') # look for username in 'Users' table response = table.get_item(Key={'username': username}, ProjectionExpression="username, password") # check if username already exists if 'Item' in response: return render_template('login/register.html', error_msg="Username already exits", username=request.form.get('username')) # if name doesn't already exist, add it response = table.put_item(Item={ 'username': username, 'password': password }) return redirect(url_for('login'), code=307)
def get_json_data(date): table = dynamodb.Table('footprint') response = table.query(KeyConditionExpression=Key('date').eq(date)) json_list = [] for i in response['Items']: print(i) json_list.append(i) return json_list
def update_datejson_fromdb(name_on_s3): date = name_on_s3.split(".")[0] if (check_file_exists(name_on_s3)): # old_data = json.load(S3.download_file_to_object(name_on_s3)) delete_file(name_on_s3) table = dynamodb.Table('footprint') response = table.query(KeyConditionExpression=Key('date').eq(date)) json_list = [] for i in response['Items']: print(i) json_list.append(i) json_list = json.dumps(json_list) upload_file_from_object(json_list, name_on_s3)
def get_user_footprint(user): table = dynamodb.Table('footprint') response = table.scan( IndexName='userindex', ScanFilter={ 'uuid': { 'AttributeValueList': [user + "_"], 'ComparisonOperator': 'BEGINS_WITH' } }, ) json_list = [] for i in response['Items']: print(i) json_list.append(i) return json_list
def login_submit(): username = request.form.get("username") password = request.form.get("password") # Validate if all fields have value if username == "" or password == "": # Save the error flag in cookies so an error message # can be displayed when page refreshes. session["login_error"] = LOGIN_ERROR_MANDATORY_FIELDS_MISSING return redirect(url_for("login")) table = dynamodb.Table('user') item = dynamo.get_item('user', {"user_id": username}) # Retrieve hashed password of the entered user from database # By default the program assumes either user is not found # or password does not match the record authenticated = False # If the user is found in database # Append salt to password and perform SHA256 print(item) if (item != None): combined = password + item["salt"] hashed = hashlib.sha256(combined.encode()).hexdigest() print(hashed) if hashed == item["password"]: authenticated = True # User is unique so there's no need to continue the loop if authenticated: # If identity is authenticated, save the username # and the flag showing a user has logged in to session cookie session['logged'] = True session['user'] = username session.permanent = True return redirect(url_for("main")) else: # Otherwise save the error message to session cookie. session['login_error'] = LOGIN_ERROR_INVALID_CREDENTIALS return redirect(url_for("login"))
def login(): # if user is already logged in (already has a session), go back to index if 'username' in session: return redirect(url_for('index')) else: # if method=GET take user to login page if request.method == 'GET': return render_template('login/login.html', page_header="Login") # if method=POST log the user in elif request.method == 'POST': table = dynamodb.Table('Users') provided_username = request.form.get('username') provided_password = request.form.get('password') # look up the username in the table and get the username/password pair response = table.get_item( Key={'username': provided_username}, ProjectionExpression="username, password") # if username does not exit, return error message if 'Item' not in response: return render_template('login/login.html', page_header="Login", error_msg="No such username", username=request.form.get('username')) # if username does exist, check that password matches else: true_password = response['Item']['password'] # if password matches, create a session for the user if provided_password == true_password: session['username'] = provided_username return redirect(url_for('index')) # if password doesn't match, return an error message and reload login page else: return render_template('login/login.html', page_header="Login", error_msg="Wrong password", username=request.form.get('username'))
def register(): username = request.form.get("username") password = request.form.get("password") confirm_password = request.form.get("confirm_password") # Validate if all fields have value if username == "" or password == "" or confirm_password == "": # Save the error flag in cookies so an error message # can be displayed when page refreshes. session["register_error"] = REGISTER_ERROR_MANDATORY_FIELDS_MISSING return redirect(url_for("register_form")) # Validate if username length is within right range if len(username) > 30 or len(username) < 6: session["register_error"] = REGISTER_ERROR_USERNAME_LENGTH_ERROR return redirect(url_for("register_form")) # Validate if username contains whitespace if (' ' in username): session["register_error"] = REGISTER_ERROR_USERNAME_CONTAIN_WHITESPACE_ERROR return redirect(url_for("register_form")) if ('_' in username): session["register_error"] = REGISTER_ERROR_USERNAME_CONTAIN_UNDERSCORE_ERROR return redirect(url_for("register_form")) # Validate if password password is within right range if len(password) > 30 or len(password) < 6: session["register_error"] = REGISTER_ERROR_PASSWORD_LENGTH_ERROR return redirect(url_for("register_form")) # Validate if password entered match if password != confirm_password: session["register_error"] = REGISTER_ERROR_PASSWORD_MISMATCH return redirect(url_for("register_form")) # connect dynamodb table = dynamodb.Table('user') item = dynamo.get_item('user',{"user_id":username}) user_exists = False if item != None: user_exists = True # # Retrieve user by the name entered # query = "SELECT * FROM users WHERE username=%s" # cursor.execute(query, (username,)) # user_exists = False # # If a record is successfully retrieved, then the user exists # for _ in cursor: # user_exists = True # break # If user exists, abort the registration and give error message. if user_exists: session['register_error'] = REGISTER_ERROR_USER_EXISTS return redirect(url_for("register_form")) # return safe_redirect(cursor, inst, '/registration') # Insert user into database with hashed password and salt # query = "INSERT INTO users (username, password, salt) VALUES (%s, %s, %s)" # Generate salt from a random value and convert it to hexadecimal representation salt = binascii.b2a_hex(os.urandom(8)).decode("utf-8") # Append salt to password combined = password + salt # Hash the combined password hashed = hashlib.sha256(combined.encode()).hexdigest() data = {"user_id":username, "password":hashed, "salt":salt} dynamo.insert_data('user',data) # cursor.execute(query, (username, hashed, salt)) # inst.commit() # # cursor.close() # inst.close() # Set the login error flag to "Successful registration" session["login_error"] = 2 return redirect(url_for("login"))
def stock_quote_get(): print(request.args.get('symbol')) symbol = str(request.args.get('symbol')) # get all the relevant data from the Yahoo Finance API stock = Share(symbol) stock_name = stock.get_name() stock_symbol = stock.symbol stock_price = stock.get_price() stock_change = stock.get_change() stock_change_pct = stock.get_percent_change() prev_close = stock.get_prev_close() open = stock.get_open() day_range = stock.get_days_range() year_range = stock.get_year_range() volume = stock.get_volume() avg_volume = stock.get_avg_daily_volume() market_cap = stock.get_market_cap() pe_ratio = stock.get_price_earnings_ratio() eps = stock.get_earnings_share() dividend = stock.get_dividend_share() dividend_yld = stock.get_dividend_yield() dividend_ex_date = stock.get_ex_dividend_date() yr_target = stock.get_one_yr_target_price() historical = stock.get_historical('2017-01-01', date.isoformat(date.today())) # put the data into the DynamoDB database table = dynamodb.Table('Stocks') response = table.put_item( Item={ 'symbol': symbol, 'date': date.isoformat(date.today()), 'prev_close': prev_close, 'open': open, 'day_range': day_range, 'year_range': year_range, 'volume': volume, 'avg_volume': avg_volume, 'market_cap': market_cap, 'pe_ratio': pe_ratio, 'eps': eps, 'dividend': dividend, 'dividend_yld': dividend_yld, 'dividend_ex_date': dividend_ex_date, 'yr_target': yr_target, }) close_history = [] for point in historical: close_date = point['Date'] close_date = int( time.mktime(datetime.strptime(close_date, "%Y-%m-%d").timetuple())) close_price = point['Adj_Close'] close_price = float(close_price) close_history.append([close_date, close_price]) return render_template("stock/stock_detail.html", stock_name=stock_name, stock_symbol=stock_symbol, stock_price=stock_price, stock_change=stock_change, stock_change_pct=stock_change_pct, prev_close=prev_close, open=open, day_range=day_range, year_range=year_range, volume=volume, avg_volume=avg_volume, market_cap=market_cap, pe_ratio=pe_ratio, eps=eps, dividend=dividend, dividend_yld=dividend_yld, dividend_ex_date=dividend_ex_date, yr_target=yr_target, close_history=close_history)