Question: I need some assistance with my python code. In the login route, it seems to only check the first line from the data_storage.txt file. Also,

I need some assistance with my python code. In the login route, it seems to only check the first line from the data_storage.txt file. Also, when doing a change password it replaces everything in the data_storage.txt instead of just the line with the correct email.

The data storage.txt is as follows:

user1@email.address Password11** user2@email.address Password22**

Python Code:

#Import statements import re import logging import socket from datetime import datetime from flask import Flask, render_template, redirect, url_for, request, session

app = Flask(__name__) #Define app

#Define secret key app.config['SECRET_KEY'] = 'secret key SDEV 300'

def logger_create(file, log_format, level, log_text): """Function to define the logger""" info_logger = logging.FileHandler(file) info_logger.setFormatter(log_format) logger = logging.getLogger(file) logger.setLevel(level) if not logger.handlers: logger.addHandler(info_logger) if level == logging.INFO: logger.info(log_text) if level == logging.ERROR: logger.error(log_text) if level == logging.WARNING: logger.warning(log_text) info_logger.close() logger.removeHandler(info_logger) #return

def invalid_login_info (): """Function to create host information""" hostname = socket.gethostname() ip_address = socket.gethostbyname(hostname) host_info = ("Invalid Login Credentials from: %s %s" %(hostname, ip_address)) return host_info

def validate_passwd(password): """Function to validate the password complexity""" reg = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{12,25}$" #Regular expression for password generation derived from bit.ly/3e9OMH6 #Stack Overflow, pattern = re.compile(reg) match = re.search(pattern, password) if match: return True else: return False

def current_time(): """Function to calculate current time""" now = datetime.now() #Returns current date/time dt_string = now.strftime ("%m/%d/%Y %H:%M:%S") #Formats the current date/time #return dt_string return dt_string

@app.route('/') @app.route('/index') def index(): """Function that renders the home page.""" if 'visited' not in session: #Check if the user has logged in before return redirect(url_for('login')) return render_template('index.html', title='Index Page', date=current_time() ) #Passes current date/time

@app.route('/requirements') def requirements(): """Function that renders requirements page""" return render_template('requirements.html',title='Requirements')

@app.route('/steps') def steps(): """Function that renders the steps page""" return render_template('steps.html',title='Steps' )

@app.route('/register', methods=['GET', 'POST']) def register(): """Function to register a new username from Form""" if request.method == 'POST': #Request info from form #username = request.form['username'] email = request.form['email'] password = request.form['password'] file = open("data_storage.txt", "a") #File to store passwords if not validate_passwd(password): #Validate password complexity message = "Password does not match complexity requirements" return render_template("register.html", error=message) else: #Write information to data file file.write("%s %s " % (email, password)) file.close() return render_template("register.html", error="You have successfully registered") else: return render_template("register.html")

@app.route('/login', methods=['GET', 'POST']) def login(): """Function to Login""" if request.method == 'POST': file = open("data_storage.txt", "r") data = file.readlines() file.close() data = [x.split() for x in data] for items in data: #Read just the email and password with open('data_storage.txt', 'r') as file_obj: list_of_lines = file_obj.readlines() print (list_of_lines) #email = request.form['email'] print(data) if request.form['email'] == items[0].strip() and request.form['pass' 'word']==items[1].strip(): session['visited'] = True #Check if the user has already logged in session['email'] = request.form['email'] #Current user return redirect(url_for('index')) #Once logged in redirect to index else: #Message if login information is not found in the data file error = "That is not valid login information" format_log = logging.Formatter('%(asctime)s %(levelname)s %(message)s') logger_create ("invalid_login.log", format_log , logging.INFO, invalid_login_info()) return render_template("login.html", error=error) else: return render_template("login.html")

@app.route('/logout') def logout(): """Function that logs the user out""" session['visited'] = False return render_template("login.html")

@app.route('/changepwd',methods=['GET','POST']) def changepwd(): if 'visited' in session: if request.method=='POST': email=session['email'] new_pwd=request.form['new_pwd'] if not validate_passwd(new_pwd): #Validate password complexity message="Password does not meet complexity requirements" return render_template("changepwd.html",error=message) file = open('CommonPassword.txt','r') data = file.readlines() file.close() for item in data: if request.form['new_pwd']==item.strip(): return render_template("changepwd.html",error="Please use another password. This " "password matches one known to be commonly-used, expected, or compromised") update_password = open("data_storage.txt","r") for line in update_password: text=line.split(" ") text[0].strip()==email: repl=line.replace(text[1], new_pwd) update_password.close() fdpout=open("data_storage.txt","w") fdpout.write(repl) fdpout.close() return render_template("changepwd.html",error="Password was changed successfully") else: return render_template("changepwd.html") #return render_template("login.html",error="Please login first")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!