def login(): if request.method == "POST": session.clear() user_id = request.form.get("user_id") password = request.form.get("password") if not user_id or user_id.__len__() != 7 or not user_id.isdigit(): return apology(title="INVALID ID", message="Your id must contain only 7 digits") elif len(password) < 6: return apology( title="INVALID PASSWORD", message="Your password must be longer than 5 characters") db = db_init() stored_user = db.execute("SELECT * FROM users WHERE id LIKE :id", { 'id': user_id }).fetchone() if stored_user is None: return apology(title="INVALID ID", message="Wrong id" + user_id) if password != stored_user['password']: return apology(title="INVALID PASSWORD", message="Your id and password don't match") session["user_id"] = stored_user['id'] session["user_permission"] = stored_user['permission'] session["user_first_name"] = stored_user['first_name'] session["user_last_name"] = stored_user['last_name'] return url_for("index") else: return render_template('login.html')
def register(): if request.method == "POST": #ensure username input if not request.form.get("username"): return apology("must provide username", 400) elif not request.form.get("password"): return apology("must provide passwords", 400) elif not request.form.get("password") == request.form.get( "confirmation"): return apology("Password do not match") hash = generate_password_hash(request.form.get("password")) new_user_id = db.execute( "INSERT INTO users (username, hash) VALUES (:username, :hash)", username=request.form.get("username"), hash=hash) if not new_user_id: return apology("username taken", 400) session["user_id"] = new_user_id #display flash message flash("Registered!") return redirect(url_for("homepage")) else: return render_template("register.html")
def register(): # User reached route via GET (as by clicking a link or via redirect) if request.method == "GET": return render_template("register.html") else: if request.form.get("password") != request.form.get("confirmation"): return apology("Those passwords didn't match.", 403) username = request.form.get('username') email = request.form.get('email') pass_hash = generate_password_hash(request.form.get('password')) regex_email = re.search( "^[a-zA-Z0-9.!#$%&''*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", email) if not regex_email: return apology("Please enter an email.", 403) regex = re.search("^[a-zA-Z0-9_]*$", username) if not regex: return apology("Only alphanumeric and underscores are allowed", 403) query = f"INSERT INTO users(username, email, hash) VALUES('{username}', '{email}', '{pass_hash}');" try: query_create_insert(connection, query) except psycopg2.errors.UniqueViolation as e: return apology("This username or email is already in use!", 403) query = f"SELECT * FROM users WHERE username = '******';" rows = query_select(connection, query) session["user_id"] = rows[0][0] return redirect("/")
def users(): """Add a User""" if request.method == "GET": userData = db.execute("SELECT id, username, role FROM users") # print(userData) return render_template("users.html", userData=userData) elif request.method == "POST": username = request.form.get("username") password = request.form.get("password") confirm = request.form.get("confirm") role = request.form.get("role") if password != confirm: return apology("Password Mismatch") if not username: return apology("You must input a username") if not role: return apology("You must choose a role") hash = generate_password_hash(password, method='pbkdf2:sha256', salt_length=8) # print("hash=", hash) rows = db.execute( "INSERT INTO users (username, hash, role) VALUES (:username, :hash, :role)", username=username, hash=hash, role=role) # print("rows=",rows) return redirect("/users")
def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash( rows[0]["hash"], request.form.get("password")): return apology("invalid username and/or password", 403) # Remember which user has logged in session["user_id"] = rows[0]["id"] # Redirect user to home page return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html")
def register(): """Register user""" if request.method == "GET": return render_template("register.html") else: # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) if len(rows) != 0: return apology("this username is taken :(", 403) pas1 = request.form.get("password") pas2 = request.form.get("confirmPassword") if pas1 != pas2: pas1 = "" pas2 = "" return apology("passwords don't match", 403) pas1 = "" pas2 = "" nicknames = db.execute( "SELECT * FROM users WHERE nickname = :nickname", nickname=request.form.get("nickname")) if len(nicknames) != 0: return apology("this nickname is taken :(", 403) db.execute( "INSERT INTO users (username, nickname, hash) VALUES (:username, :nickname, :password)", username=request.form.get("username"), nickname=request.form.get("nickname"), password=generate_password_hash(request.form.get("password"))) rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) # Remember which user has logged in session["user_id"] = rows[0]["id"] # Redirect user to home page return redirect("/")
def remove_table(user, table): if request.method == "GET": userid = session["user_id"] query = f"SELECT * FROM timetable WHERE usersid = '{userid}';" timetables = query_select(connection, query) query = f"SELECT * FROM users WHERE id = '{userid}';" rows = query_select(connection, query) username = rows[0][1] url = "/timetable/" + user + "/" + table + "/remove-timetable" for i in timetables: if i[2] == table: if user == username: return render_template("remove-timetable.html", user=user, table=table, url=url) return apology("This table does not exist", 403) else: if request.form.get("choice") == "yes": userid = session["user_id"] query = f"SELECT * FROM timetable WHERE usersid = '{userid}';" timetables = query_select(connection, query) for i in timetables: if i[2] == table: tableid = i[0] query = f"DELETE FROM timetable WHERE id = '{tableid}';" query_delete(connection, query) return redirect('/timetable')
def delete_post(post_id): admin_usr = os.environ.get("ADMIN_USR") if session["username"] == admin_usr: Post.delete_post(_id=post_id) else: return apology("Sorry, only users can delete posts.") return redirect(url_for('index'))
def description(user, table, dayoftheweek, time): url = "/timetable/" + user + "/" + table + "/" + dayoftheweek + "/" + time if request.method == "GET": regex = re.search("^[a-zA-Z0-9_]*$", dayoftheweek) if not regex: return apology("Only alphanumeric and underscores are allowed", 403) regex = re.search("^[0-9]*$", time) if not regex: return apology("Only alphanumeric and underscores are allowed", 403) data = {'title': None, 'description': None} regex = re.search("^[a-zA-Z0-9_]*$", table) if not regex: return apology("Only alphanumeric and underscores are allowed", 403) userid = session["user_id"] query = f"SELECT id FROM timetable WHERE name = '{table}' AND usersid = '{userid}';" table_info = query_select(connection, query) userid = session["user_id"] query = f"SELECT * FROM timetable WHERE usersid = {userid};" timetables = query_select(connection, query) query = f"SELECT * FROM users WHERE id = '{userid}';" rows = query_select(connection, query) username = rows[0][1] for i in timetables: if i[2] == table: if user == username: query = f"SELECT title, description FROM items WHERE tableid = {table_info[0][0]} and daysofweek = '{dayoftheweek}' and time = {time};" raw_data = query_select(connection, query) data['title'] = raw_data[0][0] data['description'] = raw_data[0][1] return render_template("description.html", title=data['title'], description=data['description'], url=url) return apology("This table does not exist", 403) else: return redirect("/timetable/" + user + "/" + table)
def login(): """ Log user in """ # Forget any user_id session.clear() if request.method == "POST": if not request.form.get("username"): return apology("must provide username", 403) elif not request.form.get("password"): return apology("must provide password", 403) rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): return apology("invalid username and/or password", 403) session["user_id"] = rows[0]["id"] return redirect("/") else: return render_template("login.html")
def add(): """ Referenced https://stackoverflow.com/questions/4108341/generating-an-ascending-list-of-numbers-of-arbitrary-length-in-python """ """ Allows user to add a location """ if request.method == "POST": name = request.form.get("location") result1 = db.execute("INSERT OR IGNORE INTO key (location) VALUES(:location)", location=name) if not result1: return apology("could not insert into table") key = db.execute("SELECT id FROM key WHERE location = :location", location=name) result2 = db.execute("INSERT INTO locations (key, comments, noise, rating, atmosphere, crowdedness, activity, time, maps, user) VALUES(:key, :comments, :noise, :rating, :atmosphere, :crowdedness, :activity, :time, :maps, :user)", key=key[0]['id'], comments=request.form.get("comments"), noise=request.form.get("noise"), rating=request.form.get("rating"), atmosphere=request.form.get("atmosphere"), crowdedness=request.form.get("crowdedness"), activity=request.form.get("activity"), time=request.form.get("time"), maps=request.form.get("map"), user=session["user_id"]) if not result2: return apology("could not insert into table") return redirect("/") else: activities = ["studying alone", "studying with friends", "hanging out", "reading", "playing games", "sleeping"] times = list(range(1, 24)) return render_template("add.html", activities=activities, times=times)
def register(): """Register a new user""" if request.method == "GET": return render_template("register.html") else: # Prompting user for their informations username = request.form.get("username") password = request.form.get("password") cfm_pw = request.form.get("cfm_password") '''# Require users’ passwords to have at least 2 letters, numbers, and 1 symbol letters2 = False symbol1 = False count = 0 for i in password: if i.isalpha() == True: count += 1 if count == 2: letters2 = True break if set('[~!@#$%^&*()_+{}":;\']+$').intersection(password): symbol1 = True if letters2 == False: return apology("Sorry, your password requires at least 2 alphabets") if symbol1 == False: return apology("Sorry, your password requires at least 1 symbol")''' # Error checking and storing user's information if password != cfm_pw: return apology("Sorry, your password does not match your confirm password.") elif not username: return apology("Please enter a username.") elif not password or not cfm_pw: return apology("Please enter a password.") else: # Hashing the password pw_hash = generate_password_hash(password) try: db.execute("INSERT INTO users(username, hash) VALUES (:username, :hash)", username=username, hash=pw_hash) except RuntimeError: return apology("Sorry, your username has been used.") finally: flash('Registered Succesfully!') return render_template("login.html")
def login(): '''Login page''' session.clear() if request.method == "POST": # Ensure username was submitted if not request.form.get("user"): return apology("No username given", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("No password given", 403) user = request.form.get("user") password = request.form.get("password") # Query database for username conn = sql.connect('diabetesdata.db') cursor = conn.cursor() details = list( cursor.execute("SELECT * FROM session WHERE user = ?", (user, ))) user_list = [] for x in details: user_list.append([x[0], x[1], x[2]]) # Ensure username exists if len(user_list) != 1: return apology("No username found", 403) if password != user_list[0][2]: return apology("Incorrect password", 403) # Remember which user has logged in session["user_id"] = user_list[0] # Redirect user to home page return redirect("/") else: return render_template("login.html")
def login(): # """Log user in.""" # forget any user_id session.clear() # if user reached route via POST (as by submitting a form via POST) if request.method == "POST": # ensure username was submitted if not request.form.get("username"): return apology("must provide username") # ensure password was submitted elif not request.form.get("password"): return apology("must provide password") # query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) # ensure username exists and password is correct if len(rows) != 1 or not pwd_context.verify( request.form.get("password"), rows[0]["hash"]): return apology("invalid username and/or password") # remember which user has logged in session["user_id"] = rows[0]["user_id"] # redirect merchant user to their home page rows = db.execute( "SELECT is_merchant FROM users WHERE user_id = :user_id", user_id=session["user_id"]) if rows[0]["is_merchant"] == 1: return redirect(url_for("merchant")) if rows[0]["is_merchant"] == 0: return redirect(url_for("customer")) else: return redirect(url_for("index")) # else if user reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html")
def register(): """Register user""" # get username & password from form (POST) if request.method == "POST": # Check for username if not request.form.get("username"): return apology("must provide username", 403) # Check if valid username via DB rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) # Ensure username doesn't exists if len(rows) > 0: return apology("Sorry, that username is taken already", 403) #Check for password correctness if not request.form.get("password"): return apology("must provide password", 403) if not request.form.get("confirmation"): return apology("Please confirm your password", 403) if not request.form.get("password") == request.form.get( "confirmation"): return apology("passwords don't match", 403) # insert username and password into DB username = request.form.get("username") hash = generate_password_hash(request.form.get("password")) new_user = db.execute( "INSERT INTO users (username, hash) VALUES(:username, :hash)", username=username, hash=hash) # redirect to login page return redirect("/") else: return render_template("register.html")
def meeting(): if request.method == "POST": result = db.execute("INSERT INTO meetings (location, date, time, subject) VALUES(:location, :date, :time, :subject)", location=request.form.get("places"), date=request.form.get("date"), time=request.form.get("time"), subject=request.form.get("subject")) if not result: return apology("could not insert into table") return redirect("/meetingList") else: places = db.execute("SELECT location FROM key") return render_template("meeting.html", places=places)
def register(): """Register user""" if request.method == "POST": result_of_checks = is_name_provided() or is_password_provided() if result_of_checks != None: return result_of_checks if request.form.get("password") != request.form.get("confirmation"): return apology("password and confirmation must be the same") prim_key = db.execute( "INSERT INTO clients (name, hash) VALUES (:name, :hash)", name=request.form.get("name"), hash=generate_password_hash(request.form.get("password"))) if prim_key == None: return apology("Registration Error. Checkif name already exists.", 403) session["user_id"] = prim_key return redirect("/") else: return render_template("register.html")
def login(): session.clear() if request.method == "POST": rows = db.execute("SELECT * FROM users WHERE username = :username", username = request.form.get("username")) if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): return apology("Invalid username and/or password!", 400) session["user_id"] = rows[0]["id"] return redirect("/") else: return render_template("login.html")
def add_result(): if request.method == "POST": if not request.form.get("subject") or request.form.get("subject") is None: smsg = "Please select a subject" return render_template("addres.html", smsg=smsg) elif not request.form.get("exam_id"): emsg = "Please write the exam id!" return render_template("addres.html", emsg=emsg) elif not request.form.get("student_id"): stmsg = "Please write the student id!" return render_template("addres.html", stmsg=stmsg) elif not request.form.get("mark"): mmsg = "Please write the mark!" return render_template("addres.html", mmsg=mmsg) subject = request.form.get("subject") exam_id = request.form.get("exam_id") if not re.match(r"^\d{5}$", exam_id): emsg = "Please write the correct exam code!" return render_template("addres.html", emsg=emsg) student_id = request.form.get("student_id") row = db.execute("SELECT student_id FROM student WHERE student_id = :student_id", {"student_id": student_id}).fetchall() if row is None: stmsg = "Please enter the correct student id!" return render_template("addres.html", stmsg=stmsg) # validating the marks entered mark = float(request.form.get("mark")) if mark > 100 or mark < 0: mmsg = "Please write the correct mark!" return render_template("addres.html", mmsg=mmsg) row = db.execute("SELECT * FROM exam WHERE student_id = :sid AND subject = :subject AND exam_code = :exam_code", {"sid": student_id, "subject": subject, "exam_code": exam_id}).fetchone() if row is None: # insert the mark and the rest to exam table try: db.execute( "INSERT INTO exam(subject, exam_code, student_id, mark) VALUES (:subject, :examc, :sid, :mark)", {"subject": subject, "examc": exam_id, "sid": student_id, "mark": mark}) db.commit() except (InternalServerError, ValueError): return apology("Something went wrong!") else: stmsg = "You have already registered this student!" return render_template("addres.html", stmsg=stmsg) success = "Added Successfully!" return render_template("addres.html", success=success) else: return render_template("addres.html")
def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) username = request.form.get("username") query = f"SELECT * FROM users WHERE username = '******';" rows = query_select(connection, query) # Output: [(id,username,email,hashedpassword)] # Example Output: [(1, 'thompson', '*****@*****.**', 'pbkdf2:sha256:passwordbuthashed')] # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash( rows[0][3], request.form.get("password")): return apology("invalid username or password", 403) # Remember which user has logged in session["user_id"] = rows[0][0] # Redirect user to home page flash("Logged in") return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: # Forget any user_id session.clear() return render_template("login.html")
def register(): """Register user.""" if request.method == "GET": return render_template("register.html") if request.method == "POST": # ensure username was submitted if not request.form.get("username"): return apology("must provide username") # ensure password was submitted elif not request.form.get("password"): return apology("must provide password") # query database for username else: row_insertion = db.execute( "INSERT INTO 'users' (username, hash, is_merchant) VALUES (:username,:new_hash,:is_merchant)", username=request.form.get("username"), new_hash=pwd_context.hash(request.form.get("password")), is_merchant=request.form.get("is_merchant")) return redirect(url_for("login")) return apology("something is wrong")
def rate(): """ Allows user to rate a location """ if request.method == "POST": result = db.execute("INSERT INTO locations (name, comments, noise, rating, atmosphere, crowdedness, activity, time, maps, id) VALUES(:name, :comments, :noise, :rating, :atmosphere, :crowdedness, :activity, :time, :maps, :id)", name=request.form.get("location"), comments=request.form.get("comments"), noise=request.form.get("noise"), rating=request.form.get("rating"), atmosphere=request.form.get("atmosphere"), crowdedness=request.form.get("crowdedness"), activity=request.form.get("activity"), time=request.form.get("time"), maps=request.form.get("map"), id=session["user_id"]) if not result: return apology("could not insert into table") return redirect("/") else: activities = ["studying alone", "studying with friends", "hanging out", "reading", "playing games", "sleeping"] times = list(range(1, 24)) places = db.execute("SELECT name FROM locations") return render_template("rate.html", activities=activities, times=times, places=places)
def changepassword(): """Allow users to change their passwords""" if request.method == "GET": return render_template("changePW.html") else: # Prompting user to key in their old PW oldpassword = request.form.get("oldpassword") # Error checking if not oldpassword: return apology("Please enter a password.") # Query database for user hash password rows = db.execute("SELECT hash FROM users WHERE id = :userid",userid=session["user_id"]) # Ensure old password entered is correct if not check_password_hash(rows[0]["hash"], oldpassword): return apology("Invalid old password", 403) newpassword = request.form.get("newpassword") cfm_newpassword = request.form.get("cfm_newpassword") # Error checking if cfm_newpassword != newpassword: return apology("Sorry, your password does not match your confirm password.") elif not newpassword or not cfm_newpassword: return apology("Please enter a password.") # Hash the new password newpassword_hash = generate_password_hash(newpassword) # Update hash in SQL db.execute("UPDATE users SET hash=:hashed WHERE id=:userid", hashed=newpassword_hash, userid=session["user_id"]) # Return to homepage flash('Password Changed!') return redirect(url_for('index'))
def messages(): """ Stores the message and user information in a data table """ if request.method == "POST": recipient = db.execute("SELECT id FROM users WHERE username = :username", username=request.form.get("recipient")) result = db.execute("INSERT INTO messages (message, recipient, sender) VALUES(:message, :recipient, :sender)", message=request.form.get("text"), recipient=recipient[0]['id'], sender=session["user_id"]) if not result: return apology("could not insert into table") return redirect("/messages") else: recipient = db.execute("SELECT username FROM users") return render_template("messages.html", recipient=recipient)
def password(): """Re-register user""" if request.method == "POST": result_of_checks = is_name_provided() or is_password_provided() if result_of_checks != None: return result_of_checks if request.form.get("password") != request.form.get("confirmation"): return apology("password and confirmation must be the same") prim_key = db.execute( "UPDATE clients SET hash = :hash WHERE name=:name ", name=request.form.get("name"), hash=generate_password_hash(request.form.get("password"))) rows = db.execute("SELECT name FROM clients WHERE name=:name", name=request.form.get("name")) if len(rows) != 1: return apology("Registration Error. Checkif name already exists.", 403) session["user_id"] = prim_key return redirect("/login") else: return render_template("password.html")
def write(): if request.method == "POST": title = request.form.get("title") en_raw_text = request.form.get("content") user = User.get_user(session["username"]) new_post = Post(title, en_raw_text, user["username"], user["_id"]) check_result, message = new_post.valid_post() if check_result: new_post.insert_to_db() flash(message) return redirect(url_for('index')) else: return apology(message) else: return render_template("write.html")
def register(): if request.method == "POST": #ensure username input if not request.form.get("username"): return apology("must provide username", 400) elif not request.form.get("password"): return apology("must provide passwords", 400) elif len(request.form.get("password")) < 8: return apology("The password must contain at least 8 characters", 400) elif not request.form.get("password") == request.form.get( "confirmation"): return apology("Password do not match") Ucount = 0 for char in request.form.get("password"): if (char.isspace()): return apology("Password contains invalid characters") if (char.isupper()): Ucount += 1 if Ucount < 1: return apology( "Password must contain at least one uppercase letter") hash = generate_password_hash(request.form.get("password")) new_user_id = db.execute( "INSERT INTO users (username, hash) VALUES (:username, :hash)", username=request.form.get("username"), hash=hash) if not new_user_id: return apology("username taken", 400) session["user_id"] = new_user_id #display flash message flash("Registered!") return redirect(url_for("homepage")) else: return render_template("register.html")
def merchant_index(): """Display the main interface a change transaction if the user is a merchant""" rows = db.execute("SELECT is_merchant FROM users WHERE user_id = :user_id", user_id=session["user_id"]) if rows[0]["is_merchant"] == '2': return apology("sorry, you are not a merchant(jsut yet).") if request.method == "GET": return render_template("merchant_index.html") if request.method == "POST": customer_id = request.form.get("customer_id") amount = request.form.get("amount") merchant_id = session["user_id"] db.execute( "INSERT INTO 'records' (merchant_id,customer_id, amount) VALUES (:merchant_id, :customer_id, :amount)", merchant_id=merchant_id, customer_id=customer_id, amount=amount) return render_template("merchant_index.html")
def register(): if request.method == "POST": username = request.form.get("username") password = request.form.get("password") confirmation = request.form.get("confirmation") pwd_hash = generate_password_hash(password) user = User(username, pwd_hash) check_result, message = user.register_valid(confirmation) if check_result: user.insert_to_db() session["username"] = username flash(message) return redirect(url_for('index')) else: return apology(message) else: return render_template("register.html")
def customer_index(): rows = db.execute( "SELECT is_merchant, username FROM users WHERE user_id = :user_id", user_id=session["user_id"]) if rows[0]["is_merchant"] == '1': return apology("Sorry, you are not logged in as a customer") if request.method == "GET": # I need to put the requested information into a list of dictionary. username = rows[0]['username'] #new query from the database. rows = db.execute( "SELECT * FROM records WHERE customer_id = :customer_id", customer_id=session["user_id"]) total_money = 0 for row in rows: total_money += row["amount"] customer = {"username": username, "total_money": total_money} return render_template("customer_index.html", customer=customer) if request.method == "POST": pass