def pull_and_analyze_all_data_function():
    """Return: Should run in the background automatically at intervals"""
    # Connect to database
    connection_postgres, cursor = connect_to_postgres_function()
    # Get all symbol tracking data from db
    all_data_symbol_track_arr_dicts = select_all_stock_tracking_info_function(
        connection_postgres, cursor)
    # Get all phone number data from db
    all_data_phone_numbers_arr_dicts = select_all_user_phone_numbers_function(
        connection_postgres, cursor)
    # Close connection
    close_connection_cursor_to_database_function(connection_postgres, cursor)

    # Manipulate the pulled data into set & dicts
    unique_stocks_set = get_unique_stocks_set_function(
        all_data_symbol_track_arr_dicts)
    symbol_news_link_dict = invert_symbol_news_link_dict_function(
        all_data_symbol_track_arr_dicts)
    user_stocks_tracking_dict = invert_to_user_stocks_dict_function(
        all_data_symbol_track_arr_dicts)
    user_phone_numbers_dict = invert_to_user_phone_numbers_dict_function(
        all_data_phone_numbers_arr_dicts)

    # Get yfinance information for the stock symbols as dict
    symbol_percent_changes_dict = get_latest_symbol_info_function(
        unique_stocks_set)

    # Put all the information together into a queue
    queue_to_text_arr = create_queue_to_text_out_function(
        user_stocks_tracking_dict, user_phone_numbers_dict,
        symbol_percent_changes_dict, symbol_news_link_dict)
    connection_postgres, cursor = connect_to_postgres_function()
    for i in queue_to_text_arr:
        send_sms_function(connection_postgres, cursor, i)
    close_connection_cursor_to_database_function(connection_postgres, cursor)
Esempio n. 2
0
def pull_and_analyze_all_data_function():
  """Return: Should run in the background automatically at intervals"""

  # First check the day
  num_day_of_week = datetime.datetime.today().weekday()
  if num_day_of_week == 5 or num_day_of_week == 6:
    print('It is the weekend. The market is closed so texts do not go out on weekend!')
    return True

  # Connect to database
  connection_postgres, cursor = connect_to_postgres_function()

  # Pull data
  # Get all symbol tracking data from db
  all_data_symbol_track_arr_dicts = select_all_stock_tracking_info_function(connection_postgres, cursor)
  # Get all phone number data from db
  all_data_phone_numbers_arr_dicts = select_all_user_phone_numbers_function(connection_postgres, cursor)
  # Get all news link data from db
  all_news_links_arr = select_all_google_news_links_function(connection_postgres, cursor)
  
  # Close connection
  close_connection_cursor_to_database_function(connection_postgres, cursor)
  
  # Manipulate the pulled data into set & dicts
  unique_stocks_set = get_unique_stocks_set_function(all_data_symbol_track_arr_dicts)
  symbol_news_link_dict = create_news_links_dict_function(all_news_links_arr)
  user_stocks_tracking_dict = invert_to_user_stocks_dict_function(all_data_symbol_track_arr_dicts)
  user_phone_numbers_dict = invert_to_user_phone_numbers_dict_function(all_data_phone_numbers_arr_dicts)
  
  # Get yfinance information for the stock symbols as dict
  symbol_percent_changes_dict = get_latest_symbol_info_function(unique_stocks_set)
  
  # Put all the information together into a queue
  queue_to_text_arr = create_queue_to_text_out_function(user_stocks_tracking_dict, user_phone_numbers_dict, symbol_percent_changes_dict, symbol_news_link_dict)

  # Set variables for sending summary text to myself
  num_texts_to_send_out = len(queue_to_text_arr)
  num_texts_failed_to_send = 0

  # Open connection to database
  connection_postgres, cursor = connect_to_postgres_function()
  for i in queue_to_text_arr:
    try:
      send_sms_function(connection_postgres, cursor, i)
    except:
      num_texts_failed_to_send += 1
      pass

  # Send summary text to myself
  try:
    send_summary_sms_text_function(connection_postgres, cursor, num_texts_failed_to_send, num_texts_to_send_out)
  except:
    pass

  # Close connection to database
  close_connection_cursor_to_database_function(connection_postgres, cursor)
def confirm_email_page_function(confirm_email_token_url_variable):
    """Returns: confirms email token link"""
    serializer_instance = URLSafeTimedSerializer(
        os.environ.get('URL_SAFE_SERIALIZER_SECRET_KEY_EMAIL'))
    string_to_salt = os.environ.get(
        'URL_SAFE_SERIALIZER_SECRET_SALT_EMAIL').encode("utf-8")
    try:
        user_email_confirming = serializer_instance.loads(
            confirm_email_token_url_variable,
            salt=string_to_salt,
            max_age=86400)
        connection_postgres, cursor = connect_to_postgres_function()
        update_to_confirmed_email_function(connection_postgres, cursor,
                                           user_email_confirming)
        close_connection_cursor_to_database_function(connection_postgres,
                                                     cursor)
    except:
        # Set the session variables outgoing
        session[
            'dashboard_upload_output_message'] = 'the email token has expired!'
        session[
            'output_message_landing_page_session'] = 'the email token has expired!'

        # Redirect to page
        return redirect("https://symbolnews.com/dashboard", code=301)

    # Set the session variables outgoing
    session['dashboard_upload_output_message'] = 'Account email confirmed!'
    session['output_message_landing_page_session'] = 'Account email confirmed!'

    # Redirect to page
    return redirect("https://symbolnews.com/", code=301)
Esempio n. 4
0
def jobs_queues_function():
    """Return: Should run in the background automatically at intervals"""
    # Connect to database
    connection_postgres, cursor = connect_to_postgres_function()

    # get_company_short_name job
    job_name = 'get_company_short_name'
    symbols_to_get_company_short_name_arr = select_job_get_company_short_name_function(
        connection_postgres, cursor, job_name)

    # Loop through all symbols in job
    for sym in symbols_to_get_company_short_name_arr:
        # Get company short name
        try:
            sym_company_short_name = get_company_short_name_function(sym[0])
        # If company short name not found
        except:
            print(
                sym[0] +
                ' : Company short name cannot be found, or it took too long to find'
            )
            sym_company_short_name = 'none'
            pass

        # If company short name found/asigned
        if sym_company_short_name != 'none':
            try:
                # Update table with company short name
                update_stock_news_links_table_company_short_name_function(
                    connection_postgres, cursor, sym_company_short_name,
                    sym[0])
                # Get updated google link
                try:
                    google_news_link_with_company_short_name = get_google_news_page_function(
                        sym_company_short_name)
                except:
                    google_news_link_with_company_short_name = 'none'
                    pass

                # If Google news link with company short name has been found/created
                if google_news_link_with_company_short_name != 'none':
                    try:
                        update_stock_news_links_table_google_link_function(
                            connection_postgres, cursor,
                            google_news_link_with_company_short_name, sym[0])
                    except:
                        pass
            except:
                pass

            # Finally delete the symbol from the job table
            try:
                delete_job_company_short_name_function(connection_postgres,
                                                       cursor, job_name,
                                                       sym[0])
            except:
                pass

    # Close connection to database
    close_connection_cursor_to_database_function(connection_postgres, cursor)
Esempio n. 5
0
def job_remind_verify_email_text_reminder_function():
  """Return: Send reminder text to users to verify their emails/check spam folder"""
  # First check the day
  num_day_of_week = datetime.datetime.today().weekday()
  if num_day_of_week == 0 or num_day_of_week == 1 or num_day_of_week == 2 or num_day_of_week == 3 or num_day_of_week == 4 or num_day_of_week == 5:
    return True
  
  # Connect to database
  connection_postgres, cursor = connect_to_postgres_function()
  # Pull data - all phone needed data
  users_not_confirmed_arr = select_user_email_not_confirmed_status_but_phone_yes_confirmed_function(connection_postgres, cursor)
  
  if len(users_not_confirmed_arr) > 0:
    for i in users_not_confirmed_arr:
      try:
        # Message the confirmation link to user
        twilio_message_sid = send_reminder_phone_to_confirm_email_account_function(i[0], i[1], i[2])

        # Add the UUID and timestamp for datetime that the reminder was created/sent
        uuid_reminder_phone = create_uuid_function("rdpe_")
        reminder_phone_timestamp = create_timestamp_function()
        confirm_phone_number_token = ''

        # Insert data into database table
        attempt_insert_reminder_phone = insert_reminder_phone_table_function(connection_postgres, cursor, uuid_reminder_phone, reminder_phone_timestamp, i[3], confirm_phone_number_token, twilio_message_sid)
        print(attempt_insert_reminder_phone)
      except:
        pass
  # Close connection
  close_connection_cursor_to_database_function(connection_postgres, cursor)
Esempio n. 6
0
def login_attempt_function():
  """Returns: login attempt on the login_page"""
  # Check if user session data is already present/signed in
  if session and session.get('logged_in_user_email') != 'none':
    return redirect('https://symbolnews.com/dashboard', code=301)
  
  # Sanitize user inputs
  user_email_from_html_form_sanitized = sanitize_email_input_create_account_function(request.form.get('email'))
  user_password_from_html_form_sanitized = sanitize_password_input_create_account_function(request.form.get('psw'))
  
  # If postman invalid inputs used
  if user_email_from_html_form_sanitized == 'none' or user_password_from_html_form_sanitized == 'none':
    print('FAILED TO LOGIN!')
    return 'FAILED TO LOGIN!'

  # Login attempt with valid inputs
  connection_postgres, cursor = connect_to_postgres_function()
  session['logged_in_user_uuid'], session['logged_in_user_email'], session['logged_in_user_first_name'], session['logged_in_user_last_name'], session['logged_in_user_phone_number'] = select_password_query_function(connection_postgres, cursor, user_email_from_html_form_sanitized, user_password_from_html_form_sanitized)
  close_connection_cursor_to_database_function(connection_postgres, cursor)
  
  # Login attempt fail
  if session['logged_in_user_email'] == 'none' or session['logged_in_user_first_name'] == 'none' or session['logged_in_user_last_name'] == 'none' or session['logged_in_user_phone_number'] == 'none':
    session['output_message_login_page_session'] = 'Email/Password not found!'
    return redirect("https://symbolnews.com/login", code=301)
  
  # Login attempt Success
  else:
    session.permanent = True
    return redirect("/dashboard", code=301)
    #return redirect("https://symbolnews.com/dashboard", code=301)
def delete_account_perm_function():
    """Returns: Deletes all symbols associated with an account and then deletes the account itself as well"""
    if session['logged_in_user_email'] != 'none':
        # Set the incoming session variables
        user_email = session['logged_in_user_email']
        user_first_name = session['logged_in_user_first_name']

        # Connect to database
        connection_postgres, cursor = connect_to_postgres_function()

        # Mark account for deletion
        update_user_delete_account_requested_true_function(
            connection_postgres, cursor, session['logged_in_user_uuid'])

        # Send account deleted email
        send_email_account_deleted_function(user_email, user_first_name)

        # Close database connection
        close_connection_cursor_to_database_function(connection_postgres,
                                                     cursor)

        # Set all session variables to none
        set_session_variables_to_none_logout_function()

        # Set outgoing session variables
        session['output_message_landing_page_session'] = 'Account deleted!'

        # Redirect to landing page
        return redirect("https://symbolnews.com/", code=301)

    else:
        set_session_variables_to_none_logout_function()
        return redirect("https://symbolnews.com/", code=301)
Esempio n. 8
0
def confirm_new_password_set_function():
    """Returns: confirms new password was set"""
    # Check if user session data is already present/signed in
    if session and session.get('logged_in_user_email') != 'none':
        return redirect('https://symbolnews.com/dashboard', code=301)

    # Sanitize new password
    user_password_from_html_form_sanitized = sanitize_password_input_create_account_function(
        request.form.get('psw'))

    # If postman invalid inputs used
    if user_password_from_html_form_sanitized == 'none':
        print('FAILED TO CREATE ACCOUNT!')
        return 'FAILED TO CREATE ACCOUNT!'

    # Hash the user password from html form
    hashed_user_password_from_html_form = bcrypt.hashpw(
        user_password_from_html_form_sanitized.encode('utf-8'),
        bcrypt.gensalt())
    hashed_user_password_from_html_form_decoded_for_database_insert = hashed_user_password_from_html_form.decode(
        'ascii')

    # Connect to postgres and update password
    connection_postgres, cursor = connect_to_postgres_function()
    update_password_function(
        connection_postgres, cursor,
        hashed_user_password_from_html_form_decoded_for_database_insert,
        session['user_email_to_change_password'])
    close_connection_cursor_to_database_function(connection_postgres, cursor)

    session['output_message_landing_page_session'] = 'Password Updated!'
    return redirect("https://symbolnews.com/", code=301)
def job_remind_verify_phone_function():
    """Return: Go into all database tables, pull table info as separate csv files, store all csv's in s3 bucket for that day"""
    # Schedule for only certain days of the week
    """num_day_of_week = datetime.datetime.today().weekday()
  if num_day_of_week == 0 or num_day_of_week == 1 or num_day_of_week == 2 or num_day_of_week == 3 or num_day_of_week == 4 or num_day_of_week == 5:
    return True"""

    # Create AWS s3 client
    s3_resource = boto3.resource('s3')
    s3_bucket_name = os.environ.get('AWS_SYMBOLNEWS_BUCKET_NAME')

    # Connect to database
    connection_postgres, cursor = connect_to_postgres_function()

    # Get all table names in the current database
    db_table_names_arr = select_all_database_table_names_function(
        connection_postgres, cursor)

    for i in db_table_names_arr:
        # Get table name
        table_name = i[0]
        try:
            # Run sql statement on the table and get all row results
            cursor.execute("SELECT * FROM %s" % table_name)
            result_list = cursor.fetchall()

            # Get table headers, store in array
            headers_tuple = cursor.description
            headers_arr = []
            for i in headers_tuple:
                headers_arr.append(i.name)

            # Create into pandas dataframe
            df = pd.DataFrame(result_list, columns=headers_arr)

            # Get todays date as string
            todays_date_str = str(datetime.datetime.now().date())
            todays_date = todays_date_str.replace("-", "")

            # Upload pandas df into aws s3
            csv_buffer = StringIO()
            df.to_csv(csv_buffer)
            s3_resource.Object(s3_bucket_name, todays_date + ' ' + table_name +
                               '.csv').put(Body=csv_buffer.getvalue())

        except (Exception, psycopg2.Error) as error:
            if (connection_postgres):
                print("Error: ", error)
                result_list = 'none'
                return result_list

    # Close connection
    close_connection_cursor_to_database_function(connection_postgres, cursor)
def job_end_of_week_email_recap_function():
    """Pulls all users who recieved texts this week then sends them an end of week recap, with news links"""
    # First check the day
    num_day_of_week = datetime.datetime.today().weekday()
    if num_day_of_week == 0 or num_day_of_week == 1 or num_day_of_week == 2 or num_day_of_week == 3 or num_day_of_week == 5 or num_day_of_week == 6:
        return True

    if num_day_of_week == 4:
        # Connect to database
        connection_postgres, cursor = connect_to_postgres_function()

        # Pull user data who received texts this week
        texts_this_week_arr = select_users_received_text_this_week_function(
            connection_postgres, cursor)
        # Pull just the symbols for users who received texts this week
        texts_this_week_symbols_only_arr = select_users_received_text_this_week_symbols_only_function(
            connection_postgres, cursor)

        # Tuen the symbols only array into dictionary with weekly thresholds per symbol
        texts_this_week_symbols_only_dict = convert_arr_dict_symbols_this_week_with_change_function(
            texts_this_week_symbols_only_arr)

        # Turn the user data into a nested dict that included weekly thresholds per symbol
        texts_this_week_dict = convert_arr_dict_texts_this_week_function(
            texts_this_week_arr, texts_this_week_symbols_only_dict)

        # Get today's date for the email send subject
        todays_date = datetime.datetime.today()
        email_send_date = todays_date.strftime("%m/%d/%y")

        # Loop through nested dictionary and email each person the highlights for the week
        master_string = ''
        for k, v in texts_this_week_dict.items():
            # Arr of symbols for user this week
            symbols_sent_arr = []
            master_string = ''
            # Loop through each person email
            for symbol, v2 in v['symbols'].items():
                # Add symbol to arr
                symbols_sent_arr.append(symbol)
                # Create a long string for the body of the email
                string = symbol + ", " + v2[
                    'total_percent_change_this_week'] + ", " + v2[
                        'google_news_link'] + " \n\n\n"
                master_string += string
            # Send the email to the person
            send_email_weekly_recap_sym_thresholds_function(
                k, v, master_string, email_send_date, connection_postgres,
                cursor, symbols_sent_arr)

        # Close connection
        close_connection_cursor_to_database_function(connection_postgres,
                                                     cursor)
def job_remind_verify_phone_function():
    """Return: Send reminder text to users to verify their phone number"""
    # First check the day
    num_day_of_week = datetime.datetime.today().weekday()
    if num_day_of_week == 0 or num_day_of_week == 1 or num_day_of_week == 2 or num_day_of_week == 3 or num_day_of_week == 4 or num_day_of_week == 5:
        return True

    # Connect to database
    connection_postgres, cursor = connect_to_postgres_function()
    # Pull data - all phone needed data
    users_not_confirmed_arr = select_user_phone_not_confirmed_status_function(
        connection_postgres, cursor)

    if len(users_not_confirmed_arr) > 0:
        for i in users_not_confirmed_arr:
            try:
                # Create token for verification
                confirm_phone_number_token = create_confirm_token_function(
                    i[0],
                    os.environ.get('URL_SAFE_SERIALIZER_SECRET_KEY_PHONE'),
                    os.environ.get('URL_SAFE_SERIALIZER_SECRET_SALT_PHONE'))
                # Create the URL link for verification
                try:
                    url_for(
                        'confirm_phone_number_page.confirm_phone_number_page_function',
                        confirm_phone_number_token_url_variable=
                        confirm_phone_number_token)
                except:
                    pass
                # Message the confirmation link to user
                twilio_message_sid = send_reminder_phone_confirm_account_function(
                    i[0], i[1], confirm_phone_number_token)

                # Add the UUID and timestamp for datetime that the reminder was created/sent
                uuid_reminder_phone = create_uuid_function("rmdp_")
                reminder_phone_timestamp = create_timestamp_function()

                # Insert data into database table
                attempt_insert_reminder_phone = insert_reminder_phone_table_function(
                    connection_postgres, cursor, uuid_reminder_phone,
                    reminder_phone_timestamp, i[2], confirm_phone_number_token,
                    twilio_message_sid)
                print(attempt_insert_reminder_phone)
            except:
                pass
    # Close connection
    close_connection_cursor_to_database_function(connection_postgres, cursor)
def forgot_password_send_token_to_email_function():
    """Returns: reset link sent"""
    # Check if user session data is already present/signed in
    if session and session.get('logged_in_user_email') != 'none':
        return redirect('https://symbolnews.com/dashboard', code=301)

    # Sanatize the user email
    user_email_from_html_form_sanitized = sanitize_email_input_create_account_function(
        request.form.get('email'))

    # If postman invalid inputs used
    if user_email_from_html_form_sanitized == 'none':
        print('FAILED TO LOGIN!')
        return 'FAILED TO LOGIN!'

    # Check if email exists in db
    connection_postgres, cursor = connect_to_postgres_function()
    does_email_exist = select_login_information_table_query_function(
        connection_postgres, cursor, user_email_from_html_form_sanitized)
    close_connection_cursor_to_database_function(connection_postgres, cursor)

    # If email does exist then send email
    if does_email_exist == 'Account already exists':
        # Create tokens for email and phone number verification
        confirm_email_token = create_confirm_token_function(
            user_email_from_html_form_sanitized,
            os.environ.get('URL_SAFE_SERIALIZER_SECRET_KEY_EMAIL'),
            os.environ.get('URL_SAFE_SERIALIZER_SECRET_SALT_EMAIL'))
        # Create the URL links for password change verification
        url_for('set_new_password.set_new_password_function',
                confirm_email_token_url_variable=confirm_email_token)
        # Send the confirmation email link to user
        send_email_new_password_function(user_email_from_html_form_sanitized,
                                         confirm_email_token)

        session[
            'output_message_forgot_password_page_session'] = 'Email sent! Please check your email for the password reset link.'
        return redirect("https://symbolnews.com/forgot_password", code=301)

    # If email does not exist, just say you sent it anyway
    else:
        # Return the same output message so that hackers do not know if or if not email exists in database
        session[
            'output_message_forgot_password_page_session'] = 'Email sent! Please check your email for the password reset link.'
        return redirect("https://symbolnews.com/forgot_password", code=301)
Esempio n. 13
0
def delete_symbols_function():
    """Returns: Delete symbols from the data table"""
    if session['logged_in_user_email'] != 'none':
        if request.method == 'POST':
            # Get the json symbols from ajax and sanitize/check if they exist
            selected_symbols_to_delete_from_ajax = request.get_json()
            if len(selected_symbols_to_delete_from_ajax) == 0:
                set_session_variables_to_none_logout_function()
                return render_template(
                    'templates_login_and_create_account/index.html')
            symbols_arr = breakup_symbols_dict_from_ajax_function(
                selected_symbols_to_delete_from_ajax)
            all_symbols_arr_exist = check_if_all_symbols_arr_exist_function(
                symbols_arr)
            if all_symbols_arr_exist == 'none':
                print('This symbol does not exist!')
                set_session_variables_to_none_logout_function()
                return render_template(
                    'templates_login_and_create_account/index.html')
            connection_postgres, cursor = connect_to_postgres_function()
            delete_from_stock_tracking_table_function(
                connection_postgres, cursor, session['logged_in_user_uuid'],
                symbols_arr)
            symbol_tracking_list = select_user_tracking_list_function(
                connection_postgres, cursor, session['logged_in_user_uuid'])
            close_connection_cursor_to_database_function(
                connection_postgres, cursor)
            return jsonify(
                '',
                render_template(
                    'templates_user_logged_in/loggedin_dashboard_page_ajax_model.html',
                    user_email_from_session_to_html=session[
                        'logged_in_user_email'],
                    user_first_name_from_session_to_html=session[
                        'logged_in_user_first_name'],
                    user_last_name_from_session_to_html=session[
                        'logged_in_user_last_name'],
                    user_phone_number_from_session_to_html=session[
                        'logged_in_user_phone_number'],
                    symbol_tracking_list_from_python_to_html=
                    symbol_tracking_list))
    else:
        set_session_variables_to_none_logout_function()
        return render_template('templates_login_and_create_account/index.html')
def creating_account_to_postgres_function():
    """Returns: Uploads new account info to Postgres database, if it does not already exist."""
    # Check if user session data is already present/signed in
    if session and session.get('logged_in_user_email') != 'none':
        return redirect('https://symbolnews.com/dashboard', code=301)

    # Get and sanitize the user inputs from html form
    user_first_name_from_html_form_sanitized = sanitize_name_input_create_account_function(
        request.form.get('user_first_name'))
    user_last_name_from_html_form_sanitized = sanitize_name_input_create_account_function(
        request.form.get('user_last_name'))
    user_phone_number_from_html_form_sanitized = sanitize_phone_number_input_create_account_function(
        request.form.get('phone_number'))
    user_email_from_html_form_sanitized = sanitize_email_input_create_account_function(
        request.form.get('email'))
    user_password_from_html_form_sanitized = sanitize_password_input_create_account_function(
        request.form.get('psw'))

    # If postman invalid inputs used
    if user_first_name_from_html_form_sanitized == 'none' or user_last_name_from_html_form_sanitized == 'none' or user_phone_number_from_html_form_sanitized == 'none' or user_email_from_html_form_sanitized == 'none' or user_password_from_html_form_sanitized == 'none':
        print('FAILED TO CREATE ACCOUNT!')
        return 'FAILED TO CREATE ACCOUNT!'

    # Hash the user password from html form
    hashed_user_password_from_html_form = bcrypt.hashpw(
        user_password_from_html_form_sanitized.encode('utf-8'),
        bcrypt.gensalt())
    hashed_user_password_from_html_form_decoded_for_database_insert = hashed_user_password_from_html_form.decode(
        'ascii')

    # Connect to postgres
    connection_postgres, cursor = connect_to_postgres_function()

    # Search query if email is already in database
    email_exists = select_login_information_table_query_function(
        connection_postgres, cursor, user_email_from_html_form_sanitized)
    phone_exists = select_login_information_table_query_phone_number_function(
        connection_postgres, cursor,
        user_phone_number_from_html_form_sanitized)

    # If email account already exists in database
    if email_exists == 'Account already exists' or phone_exists == 'Account already exists':
        # Close connection to database
        close_connection_cursor_to_database_function(connection_postgres,
                                                     cursor)

        # Set outgoing session messages
        session[
            'output_message_create_account_page_session'] = 'Account already exists'

        # Redirect to page
        return redirect("https://symbolnews.com/create_account", code=301)

    # Add the UUID and timestamp for datetime that the account was created
    user_uuid_create_account = create_uuid_function("user_")
    user_create_account_timestamp = create_timestamp_function()

    # Insert query function to insert new user created data into postgres
    success_message, error_message = insert_login_information_table_query_function(
        connection_postgres, cursor, user_uuid_create_account,
        user_create_account_timestamp,
        user_first_name_from_html_form_sanitized,
        user_last_name_from_html_form_sanitized,
        user_phone_number_from_html_form_sanitized,
        user_email_from_html_form_sanitized,
        hashed_user_password_from_html_form_decoded_for_database_insert)

    # Close database connection and cursor
    close_connection_cursor_to_database_function(connection_postgres, cursor)

    # Continue based on query insert results
    if success_message == 'success' and error_message == 'none':
        # Create tokens for email and phone number verification
        confirm_email_token = create_confirm_token_function(
            user_email_from_html_form_sanitized,
            os.environ.get('URL_SAFE_SERIALIZER_SECRET_KEY_EMAIL'),
            os.environ.get('URL_SAFE_SERIALIZER_SECRET_SALT_EMAIL'))
        confirm_phone_number_token = create_confirm_token_function(
            user_phone_number_from_html_form_sanitized,
            os.environ.get('URL_SAFE_SERIALIZER_SECRET_KEY_PHONE'),
            os.environ.get('URL_SAFE_SERIALIZER_SECRET_SALT_PHONE'))

        # Create the URL links for email and phone number verification
        url_for('confirm_email_page.confirm_email_page_function',
                confirm_email_token_url_variable=confirm_email_token)
        url_for(
            'confirm_phone_number_page.confirm_phone_number_page_function',
            confirm_phone_number_token_url_variable=confirm_phone_number_token)

        # Send the confirmation email and text links to user
        try:
            send_phone_number_confirm_account_function(
                user_phone_number_from_html_form_sanitized,
                user_first_name_from_html_form_sanitized,
                confirm_phone_number_token)
            send_email_confirm_account_function(
                user_email_from_html_form_sanitized,
                user_first_name_from_html_form_sanitized, confirm_email_token)
        except:
            # If user inputs wrong format
            # Delete user that was just input to database
            connection_postgres, cursor = connect_to_postgres_function()
            delete_all_user_login_information_table_data_function(
                connection_postgres, cursor, user_uuid_create_account)
            close_connection_cursor_to_database_function(
                connection_postgres, cursor)

            set_session_variables_to_none_logout_function()
            session[
                'output_message_create_account_page_session'] = 'Unable to create account with the phone number provided!'
            return redirect("https://symbolnews.com/create_account", code=301)

        # Send admin email that account was created
        try:
            send_admin_email_account_created_function(
                user_first_name_from_html_form_sanitized,
                user_last_name_from_html_form_sanitized,
                user_email_from_html_form_sanitized,
                user_create_account_timestamp)
        except:
            print('did not send email to admin')

        # Flask set session variables and redirect to dashboard
        session['logged_in_user_uuid'] = user_uuid_create_account
        session['logged_in_user_email'] = user_email_from_html_form_sanitized
        session[
            'logged_in_user_first_name'] = user_first_name_from_html_form_sanitized
        session[
            'logged_in_user_last_name'] = user_last_name_from_html_form_sanitized
        session[
            'logged_in_user_phone_number'] = user_phone_number_from_html_form_sanitized
        session.permanent = True
        return redirect("https://symbolnews.com/dashboard", code=301)

    # If above fails at any point redirect back to create account page
    else:
        set_session_variables_to_none_logout_function()
        return redirect("https://symbolnews.com/create_account", code=301)
    return redirect("https://symbolnews.com/create_account", code=301)
def dashboard_page_render_function():
    """Returns: User dashboard with user symbol tracking list"""
    # Need to create a css unique key so that cache busting can be done
    css_cache_busting_variable = create_uuid_function('css_')

    if session and session.get(
            'logged_in_user_email') != 'none' and session.get(
                'logged_in_user_email') != None:
        # Get info for the page render
        # Connect to database
        connection_postgres, cursor = connect_to_postgres_function()

        # Pull tracking list from databse
        symbol_tracking_list = select_user_tracking_list_function(
            connection_postgres, cursor, session['logged_in_user_uuid'])
        # Check if email and phone number are verified
        display_output_message_email, display_output_message_phone_number = select_user_confirmed_account_status_function(
            connection_postgres, cursor, session['logged_in_user_uuid'])

        # If not verified yet, unhide the resend link text
        resend_email_confirm_link = ''
        resend_phone_number_confirm_link = ''

        # Add the resend link text words to html file if they are not blank/None
        if display_output_message_email != None and len(
                display_output_message_email) >= 2:
            resend_email_confirm_link = 'Click to resend email confirmation link.'
        if display_output_message_phone_number != None and len(
                display_output_message_phone_number) >= 2:
            resend_phone_number_confirm_link = 'Click to resend phone number confirmation link.'

        # Close the connnection to database
        close_connection_cursor_to_database_function(connection_postgres,
                                                     cursor)

        # When redirected to this page, first check if there is an session error message associated with this redirect
        if session and session.get(
                'output_message_dashboard_page_session') != None:
            try:
                return render_template(
                    'templates_user_logged_in/loggedin_dashboard_page.html',
                    user_email_from_session_to_html=session[
                        'logged_in_user_email'],
                    user_first_name_from_session_to_html=session[
                        'logged_in_user_first_name'],
                    user_last_name_from_session_to_html=session[
                        'logged_in_user_last_name'],
                    user_phone_number_from_session_to_html=session[
                        'logged_in_user_phone_number'],
                    symbol_tracking_list_from_python_to_html=
                    symbol_tracking_list,
                    output_message_from_python_to_html=session[
                        'output_message_dashboard_page_session'],
                    resend_email_confirm_link_to_html=resend_email_confirm_link,
                    resend_phone_number_confirm_link_to_html=
                    resend_phone_number_confirm_link,
                    css_cache_busting_variable_to_html=
                    css_cache_busting_variable)
            except:
                return 'failed'
            finally:
                session['output_message_dashboard_page_session'] = None

        # Render the page
        return render_template(
            'templates_user_logged_in/loggedin_dashboard_page.html',
            user_email_from_session_to_html=session['logged_in_user_email'],
            user_first_name_from_session_to_html=session[
                'logged_in_user_first_name'],
            user_last_name_from_session_to_html=session[
                'logged_in_user_last_name'],
            user_phone_number_from_session_to_html=session[
                'logged_in_user_phone_number'],
            symbol_tracking_list_from_python_to_html=symbol_tracking_list,
            resend_email_confirm_link_to_html=resend_email_confirm_link,
            resend_phone_number_confirm_link_to_html=
            resend_phone_number_confirm_link,
            css_cache_busting_variable_to_html=css_cache_busting_variable)

    # If no session info found
    else:
        set_session_variables_to_none_logout_function()
        return redirect("https://symbolnews.com/", code=301)
def upload_symbol_percent_change_input_function():
    """Returns: sanatizes the user input, then uploads it into the database and data table"""
    if session and session.get('logged_in_user_email') != 'none':
        # Sanitize/confirm user inputs
        user_symbol_from_html_form_sanitized = sanitize_symbol_input_function(
            request.form.get('track_symbol'))
        does_symbol_exist = yfinance_check_if_symbol_exists_function(
            user_symbol_from_html_form_sanitized)
        user_symbol_percent_change_from_html_form_sanitized = sanitize_symbol_percent_change_input_function(
            request.form.get('track_percent_change'))

        # If user inputs were invalid
        if user_symbol_from_html_form_sanitized == 'none' or does_symbol_exist == 'none' or user_symbol_percent_change_from_html_form_sanitized == 'none':
            session[
                'output_message_dashboard_page_session'] = 'Stock Symbol must exist and be 1-5 letters long. Minimum % Change must be 7.'
            return redirect("https://symbolnews.com/dashboard", code=301)

        # If user inputs were valid
        else:
            # Create uuid and timestamp for insertion
            user_table_insert_uuid = create_uuid_function("symt_")
            user_track_symbol_timestamp = create_timestamp_function()

            # Database insert
            connection_postgres, cursor = connect_to_postgres_function()
            # Check if user is already tracking this symbol
            error_message_check_if_exist = select_stock_tracking_table_duplicates_function(
                connection_postgres, cursor, session['logged_in_user_uuid'],
                user_symbol_from_html_form_sanitized)

            # If user is not already tracking this symbol
            if error_message_check_if_exist == 'none':
                # Insert stock tracking information into the stock_tracking_table
                session[
                    'output_message_dashboard_page_session'] = insert_stock_tracking_table_function(
                        connection_postgres, cursor, user_table_insert_uuid,
                        user_track_symbol_timestamp,
                        user_symbol_from_html_form_sanitized,
                        user_symbol_percent_change_from_html_form_sanitized,
                        session['logged_in_user_uuid'])

                # Get google news link for the symbol not company short name yet, a job will get the short name in order to save wait time for user
                temporary_google_search_input = user_symbol_from_html_form_sanitized + '_stock'
                google_news_url_link = get_google_news_page_function(
                    temporary_google_search_input)

                # Insert into the new stock_news_links_table the 1.symbol and 2.google_link(symbol search)
                try:
                    output_message_news_link_upload = insert_stock_news_links_table_function(
                        connection_postgres, cursor,
                        user_symbol_from_html_form_sanitized,
                        google_news_url_link)
                except:
                    pass

                # Insert into job/queue table so that the job can get the company short name every 10 min in the background
                try:
                    job_queue_name = 'get_company_short_name'
                    output_message_job_upload = insert_jobs_queues_table_function(
                        connection_postgres, cursor, job_queue_name,
                        user_symbol_from_html_form_sanitized)
                except:
                    pass
                return redirect("/dashboard", code=301)
                #return redirect("https://symbolnews.com/dashboard", code=301)

            # If user is already tracking this symbol
            else:
                session[
                    'output_message_dashboard_page_session'] = error_message_check_if_exist
                return redirect("/dashboard", code=301)
                #return redirect("https://symbolnews.com/dashboard", code=301)

    # If no session info found
    else:
        set_session_variables_to_none_logout_function()
        return redirect("https://symbolnews.com/", code=301)
Esempio n. 17
0
def updating_account_info_postgres_function():
    # If no account information was updated
    if request.form.get(
            "email") == session['logged_in_user_email'] and request.form.get(
                "user_first_name"
            ) == session['logged_in_user_first_name'] and request.form.get(
                "user_last_name"
            ) == session['logged_in_user_last_name'] and request.form.get(
                "phone_number") == session['logged_in_user_phone_number']:
        return redirect("https://symbolnews.com/account", code=301)

    # Check if email was updated, then sanitize input
    if request.form.get("email") != session['logged_in_user_email']:
        user_email_from_html_form_sanitized = sanitize_email_input_create_account_function(
            request.form.get("email"))
    else:
        user_email_from_html_form_sanitized = session['logged_in_user_email']

    # Check if first name was updated, then sanitize input
    if request.form.get(
            "user_first_name") != session['logged_in_user_first_name']:
        user_first_name_from_html_form_sanitized = sanitize_name_input_create_account_function(
            request.form.get("user_first_name"))
    else:
        user_first_name_from_html_form_sanitized = session[
            'logged_in_user_first_name']

    # Check if last name was updated, then sanitize input
    if request.form.get(
            "user_last_name") != session['logged_in_user_last_name']:
        user_last_name_from_html_form_sanitized = sanitize_name_input_create_account_function(
            request.form.get("user_last_name"))
    else:
        user_last_name_from_html_form_sanitized = session[
            'logged_in_user_last_name']

    # Check if phone number was updated, then sanitize input
    if request.form.get(
            "phone_number") != session['logged_in_user_phone_number']:
        user_phone_number_from_html_form_sanitized = sanitize_phone_number_input_create_account_function(
            request.form.get("phone_number"))
    else:
        user_phone_number_from_html_form_sanitized = session[
            'logged_in_user_phone_number']

    # If any invalid inputs/changes for form
    if user_email_from_html_form_sanitized == 'none' or user_first_name_from_html_form_sanitized == 'none' or user_last_name_from_html_form_sanitized == 'none' or user_phone_number_from_html_form_sanitized == 'none':
        print('FAILED TO CREATE ACCOUNT!')
        return 'FAILED TO UPDATE ACCOUNT!'

    # If valid inputs/changes for form
    if session['logged_in_user_email'] != 'none':
        # Connect to Database
        connection_postgres, cursor = connect_to_postgres_function()

        # Check/Update user first name
        if session[
                'logged_in_user_first_name'] != user_first_name_from_html_form_sanitized:
            update_user_first_name_function(
                connection_postgres, cursor,
                user_first_name_from_html_form_sanitized,
                session['logged_in_user_uuid'])
            session[
                'logged_in_user_first_name'] = user_first_name_from_html_form_sanitized

        # Check/Update user last name
        if session[
                'logged_in_user_last_name'] != user_last_name_from_html_form_sanitized:
            update_user_last_name_function(
                connection_postgres, cursor,
                user_last_name_from_html_form_sanitized,
                session['logged_in_user_uuid'])
            session[
                'logged_in_user_last_name'] = user_last_name_from_html_form_sanitized

        # Check/Update email
        if session[
                'logged_in_user_email'] != user_email_from_html_form_sanitized:
            does_email_exist = select_login_information_table_query_function(
                connection_postgres, cursor,
                user_email_from_html_form_sanitized)
            if does_email_exist == 'Account already exists':
                output_message = 'Cannot use that email/phone number combination'
                return redirect("https://symbolnews.com/account", code=301)
            else:
                update_user_email_function(
                    connection_postgres, cursor,
                    user_email_from_html_form_sanitized,
                    session['logged_in_user_uuid'])
                session[
                    'logged_in_user_email'] = user_email_from_html_form_sanitized
                update_user_email_verified_false_function(
                    connection_postgres, cursor,
                    session['logged_in_user_uuid'])
                confirm_email_token = create_confirm_token_function(
                    user_email_from_html_form_sanitized,
                    os.environ.get('URL_SAFE_SERIALIZER_SECRET_KEY_EMAIL'),
                    os.environ.get('URL_SAFE_SERIALIZER_SECRET_SALT_EMAIL'))
                url_for('confirm_email_page.confirm_email_page_function',
                        confirm_email_token_url_variable=confirm_email_token)
                send_email_confirm_account_function(
                    user_email_from_html_form_sanitized,
                    user_first_name_from_html_form_sanitized,
                    confirm_email_token)

        # Check/Update phone number
        if session[
                'logged_in_user_phone_number'] != user_phone_number_from_html_form_sanitized:
            does_phone_number_exist = select_login_information_table_query_phone_number_function(
                connection_postgres, cursor,
                user_phone_number_from_html_form_sanitized)
            if does_phone_number_exist == 'Account already exists':
                output_message = 'Cannot use that email/phone number combination'
                return redirect("https://symbolnews.com/account", code=301)
            else:
                update_user_phone_function(
                    connection_postgres, cursor,
                    user_phone_number_from_html_form_sanitized,
                    session['logged_in_user_uuid'])
                session[
                    'logged_in_user_phone_number'] = user_phone_number_from_html_form_sanitized
                update_user_phone_verified_false_function(
                    connection_postgres, cursor,
                    session['logged_in_user_uuid'])
                confirm_phone_number_token = create_confirm_token_function(
                    user_phone_number_from_html_form_sanitized,
                    os.environ.get('URL_SAFE_SERIALIZER_SECRET_KEY_PHONE'),
                    os.environ.get('URL_SAFE_SERIALIZER_SECRET_SALT_PHONE'))
                url_for(
                    'confirm_phone_number_page.confirm_phone_number_page_function',
                    confirm_phone_number_token_url_variable=
                    confirm_phone_number_token)
                send_phone_number_confirm_account_function(
                    user_phone_number_from_html_form_sanitized,
                    user_first_name_from_html_form_sanitized,
                    confirm_phone_number_token)

        # Close connection to database
        close_connection_cursor_to_database_function(connection_postgres,
                                                     cursor)

        output_message = 'Account Changes Saved'
        return redirect("https://symbolnews.com/account", code=301)
    else:
        set_session_variables_to_none_logout_function()
        return redirect("https://symbolnews.com/", code=301)