Hi I am having trouble getting my login to work. I have set up a database and done login page with a form. I added a username and password to the database but the page seems to still not be logging in.
I think something to do with the Validate. It keeps saying 'Invalid Credentials. Please try again.'even though the username and password are correct.
completion = validate(username, password)
if completion == False:
error = 'Invalid Credentials. Please try again.'
else:
return redirect(url_for('dashboard'))
Thanks in Advance:)
I new to Python and Flask. PS I cant use any other libraries eg sqlalchemy
from flask import Flask, render_template, redirect, url_for, request, g
import sqlite3
import hashlib
app = Flask(__name__)
# To convert the user input password as MD5
def check_password(hashed_password, user_password):
return hashed_password == hashlib.md5(user_password.encode()).hexdigest()
# Takes the inputed username and passwords as arguments, and compare them against the users table
def validate(username, password):
con = sqlite3.connect('var/data.db')
completion = False
with con:
cur = con.cursor()
cur.execute("SELECT * FROM Users")
rows = cur.fetchall()
for row in rows:
dbUser = row[1]
dbPass = row[2]
if dbUser == username:
completion = check_password(dbPass, password)
return completion
def init_db():
with app.app_context():
con = sqlite3.connect('var/data.db')
with app.open_resource('var/schema.sql', mode='r') as f:
con.cursor().executescript(f.read())
con.commit()
#The Homepage Route
@app.route("/")
def index():
return render_template('index.html', title='Home')
#The Login Route
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
completion = validate(username, password)
if completion == False:
error = 'Invalid Credentials. Please try again.'
else:
return redirect(url_for('dashboard'))
return render_template('login.html', error=error)
#The Dashboard Route
@app.route('/dashboard')
def dashboard():
#return "You have successfully logged in"
return render_template('dashboard.html', title='Dashboard')
#The Adds to the List
@app.route('/add', methods=['GET','POST'])
def add():
if not session.get('username'):
abort(401)
db = get_db()
db.execute('INSERT INTO Bucketlist (title,day,desc) VALUES(?,?,?)',
[request.form['title'], request.form['day'], request.form['desc']])
db.commit()
flash('Your wish has been added to your list')
return redirect(url_for('dashboard'))
#The Removes from the List
@app.route('/remove', methods=['GET'])
def remove():
delete = request.args.get('bucket_id', '')
print delete
db = get_db()
db.execute('DELETE FROM Bucketlist WHERE title=?', [delete])
db.commit()
cur = db.execute("select * from Bucketlist")
row = cur.fetchall()
flash('Your wish has been removed from your list')
return render_template("dashboard.html",row=row)
#Logs Out The User from Their Account
@app.route('/logout')
def logout():
session.pop('username', None)
flash('You Have Successful Loged Out')
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
{% extends "base.html" %}
{% block content %}
<div class="container">
<h1>Sign In to View Your WounderList</h1>
<h2 class="form-text">Create Your Account Here!</h2>
<form action="/login" method="post">
<input type="text" placeholder="Username" name="username" value="{{
request.form.username }}">
<input type="password" placeholder="Password" name="password" value="{{
request.form.password }}">
<input class="btn btn-default" type="submit" value="Login">
</form>
{% if error %}
<p class="error"><strong>Error:</strong> {{ error }}
{% endif %}
</div>
{% endblock %}
DROP TABLE if EXISTS Users;
DROP TABLE if EXISTS Bucketlist;
CREATE TABLE Users (
user_id INTEGER PRIMARY KEY,
username VARCHAR(16) NOT NULL UNIQUE,
password VARCHAR(16) NOT NULL
);
CREATE TABLE Bucketlist (
bucket_id INTEGER NOT NULL,
title VARCHAR(32) NOT NULL,
day DATE NOT NULL,
desc VARCHAR(256) NOT NULL,
user_id INTEGER,
PRIMARY KEY (bucket_id),
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
First you should know that you are not really making a "login", you are just checking a password. A login requires managing a session after the user logs in and the password is accepted.
I suspect the issue is with your password hashing so for testing purposes you should try your code without the hash. See if you can validate a plain text password first.
Secondly, it is a much better idea to just use a Flask library made for this specific purpose like Flask-Login
, but I suppose you are a student or something.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.