I have a RegisterForm
and LoginForm
made with Flask and hashed with sha256. The RegisterForm
works, but the login page is not returning anything. I stay in the same login page, the only difference is the url returns this:
HTTP/1.1[0m" 304 -INFO:werkzeug:127.0.0.1 - - [27/Nov/2021 04:56:29] "GET /?username=alex29&password=12345&submit=Login HTTP/1.1" 200 -
And the url change to this:
http://localhost:5000/?username=alex29&password=12345&submit=Login
from flask import Flask, render_template, url_for, redirect, session, flash, request from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Length, ValidationError from flask_bcrypt import Bcrypt from werkzeug.security import generate_password_hash, check_password_hash from flask_wtf.csrf import CSRFProtect from werkzeug.urls import url_parse import sqlite3 app = Flask (__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///gestdoc.db' app.config['SECRET_KEY'] = 'thisisasecretkey' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) USER_LOGIN_URL = '/login' USER_ENABLE_USERNAME = True csrf = CSRFProtect(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' @login_manager.user_loader def load_user(id_user): return User.query.get(int(id_user)) class User(db.Model, UserMixin): id_user = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), nullable=False, unique=True) password = db.Column(db.String(80), nullable=False) authenticated = db.Column(db.Boolean, default=False) def set_password(self, password): self.password = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password, password) def is_active(self): return True def is_authenticated(self): return True def is_anonymous(self): return True class employee(db.Model): id_employee = db.Column(db.CHAR(100), primary_key=True) name = db.Column(db.TEXT(100), nullable=False) surname = db.Column(db.TEXT(100), nullable=False) class RegisterForm(FlaskForm): username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Usuario"}) password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "ContraseƱa"}) submit = SubmitField("Register") def validate_username(self, username): user = User.query.filter_by(username=username.data).first() if user is not None: raise ValidationError('Este usuario ya existe. Use otro.') class EmployeeForm(FlaskForm): id_employee = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "DNI"}) name = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "NOMBRE"}) surname = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "APELLIDOS"}) submit = SubmitField("Guardar") def validate_employee(self, employee): check_id_employee = User.query.filter_by(employee=id_employee.data).first() if check_id_employee: raise ValidationError('Este empleado ya existe.') class LoginForm(FlaskForm): username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"}) password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Password"}) submit = SubmitField('Login') @app.route('/', methods=['GET','POST']) def login(): form = LoginForm(meta={'csrf': False}) if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user: if check_password(user.password, form.password.data): login_user(user) flash("Log In") return redirect(url_for('admin')) else: flash('Invalid password') else: flash('usuario no existe') return render_template('login.html', form=form) @app.route('/admin', methods=['GET','POST']) @login_required def showemployee(): con = sqlite3.connect('gestdoc.db') cur = con.cursor() cur.execute('SELECT * from employee') employee = cur.fetchall() con.close() return render_template('admin.html', employee=employee) @app.route('/register', methods=['GET','POST']) def register(): form = RegisterForm() if form.validate_on_submit(): user = User(username=form.username.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Usuario registrado') return redirect(url_for('login')) return render_template('register.html', form=form) import logging logging.basicConfig(filename = "sample.log", level = logging.DEBUG,filemode = "w+" ) logging.debug('debug') logging.info('info') logging.warning('warning') logging.error('error') logging.critical('critical') if __name__ == '__main__': app.run(debug=True)
Thank you for the help
Advertisement
Answer
I think you forgot to change the login form method to “post”
Here you can find an example of how to set the needed form attributes.