3

This is the message I am getting on my login form validation:

session: <SecureCookieSession {}>
request.form: ImmutableMultiDict([('eventid', ''), ('csrf_token', 'ImI1N2EwYjFjZmIxZDI4YjQ3ZTIxM2VmNGNkOGQzZTEzYzBiM2U4MzEi.DsNqRA.sw618M5laiwyElfOJ9mAIAAOXig'), ('password', 'admin'), ('username', 'admin'), ('submit', 'Sign In')])
INFO:flask_wtf.csrf:The CSRF tokens do not match.
127.0.0.1 - - [06/Nov/2018 19:18:57] "POST / HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [06/Nov/2018 19:18:57] "POST / HTTP/1.1" 200 -

I print the form data and the session, and it appears, that the session is empty.

I understand, that the session must have the token but it is missing and I do not know what I need to do to have the required data in the session. I followed this tutorial and it seems, it all must be set automatically.

Previously I did not use flask_wtf and it all was working fine. I checked all available questions about not matching tokens or missing tokens but I was not able to fix my problem using their suggestions.

Here are my files:

__init__.py

#!/usr/bin/env python3

import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

from config import Config


app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)

# register blueprints
from app.auth import auth
app.register_blueprint(auth.bp)

The view: auth.py

from flask import (
    Blueprint,
    flash,
    g,
    redirect,
    render_template,
    request,
    session,
    url_for,
)
from werkzeug.security import check_password_hash, generate_password_hash

from app import db
from app.auth.forms import LoginForm
from app.models import User


bp = Blueprint('auth', __name__)


@bp.route('/', methods=('GET', 'POST'))
@bp.route('/login/', methods=('GET', 'POST'))
def login():
    print('session:', session)
    form = LoginForm()
    print('request.form:', request.form)
    if form.validate_on_submit():
        print('Form is valid')
        eventid = form.eventid.data
        username = form.username.data
        password = form.password.data
        # validate login
        user = User.query.filter_by(username=username.lower()).first()
        error = None
        if not user or not check_password_hash(user.password, password):
            error = 'Incorrect username-password combination.'

        if not error:
            session.clear()
            session['user_id'] = user.id
            return redirect(url_for('performance.index'))

        flash(error)

    return render_template('auth/login.html', title='Sign In', form=form)

The form: forms.py

from flask_wtf import FlaskForm
from wtforms import (
    BooleanField,
    PasswordField,
    StringField,
    SubmitField,
)
from wtforms.validators import DataRequired


class LoginForm(FlaskForm):
    eventid = StringField('Event ID')
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Sign In')

The template: login.html

{% extends 'base.html' %}

{% block header %}
<h3>{% block title %}{{ title }}{% endblock %}</h3>
{% endblock %}

{% block content %}
    <form action="" method="post">
        <div class="form-group">
            <label class="col-sm-12" for="username">
                {{ form.username.label }}
            </label>
            {{ form.username() }}
        </div>
        <div class="form-group">
            <label class="col-sm-12" for="password">
                {{ form.password.label }}
            </label>
            {{ form.password() }}
        </div>
        <div class="form-group">
            <label class="col-sm-12" for="eventid">
                {{ form.eventid.label }}
            </label>
            {{ form.eventid() }}
        </div>
        <div class="form-group">
            {{ form.submit }}
        </div>
        {{ form.hidden_tag() }}
    </form>
{% endblock %}

The config: config.py

import os


class Config:
    instance_path = '/some/path/to/instance/'
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    DATABASE = os.path.join(instance_path, 'app.sqlite')
    SQLALCHEMY_DATABASE_URI = ('sqlite:///' + os.path.join(instance_path,
                                                           'app.sqlite'))
    SQLALCHEMY_TRACK_MODIFICATIONS = False

I have tried all the propositions, I was able to find: - I have set the hidden_tag() in the template; - I have set the SECRETE_KEY in the config; - I have tried changing from FlaskForms to Forms; - other solutions.

None of them did not help. I am sitting with it for three evenings already. Any suggestion would be good.

UPDATE

If I do not use Blueprint, i.e. if I use @app.route(...) instead of @bp.route(...) in my auth.py, I am able to login, although the session is still empty. So, now I do not understand the problem with the blueprint.

1 Answers1

0

I think you skipped this part from tutorial:

The form.hidden_tag() template argument generates a hidden field that includes a token that is used to protect the form against CSRF attacks. All you need to do to have the form protected is include this hidden field and have the SECRET_KEY variable defined in the Flask configuration. If you take care of these two things, Flask-WTF does the rest for you.

So in your config file, you should have secret key set

import os

class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'

If that doesn't work somehow, in your login.html, try to add at the beginning of a form csrf_token like so:

<form action="" method="post">
        {{ form.csrf_token }}
        <div class="form-group">
            <label class="col-sm-12" for="username">
                {{ form.username.label }}
     .....
Dinko Pehar
  • 5,454
  • 4
  • 23
  • 57
  • 2
    thank you for the answer, but I have tried all of those already - it does not change the result. –  Nov 07 '18 at 20:53