Anton Melnikov
Anton Melnikov

Reputation: 1058

Simple auth method for a Flask application?

I work on my simple blogging system written in Python, Flask and SQLite, and I've created a simple authorization system for it. There is no need for anything fancy, so it's just a matter of sending login and password through a form and setting a flag in Flask's session. I wanted to know how things like this are done, so I didn't use any modules.

I'm wondering if this method is correct and secure just enough.

# from auth module
@auth.route('/login', methods=['POST'])
def login():
    """Login as blog admin."""

    # Successeful login conditions
    user_is_valid = request.form['user'] == current_app.config['USER']
    password_is_valid = request.form['password'] == current_app.config['PASSWORD']
    trap_is_empty = not request.form['trap']

    # Login user if credentials are correct
    if user_is_valid and password_is_valid and trap_is_empty:
        session['is_admin'] = True
        return redirect(url_for('admin.posts_page'))
    else:
        return render_template('auth.html')


# from admin module
@admin.before_request
def before_request():
    """ Before any request check admin flag, redirect to the main page if there is none. """
    if not session.get('is_admin'):
        return redirect(url_for('blog.index_page'))
    proj.db.connect()

Upvotes: 1

Views: 519

Answers (1)

Tux
Tux

Reputation: 1916

It honestly looks fine for just a basic authentication system. The bad part is storing the credentials in the config.

If you want to get all cool and fancy, you can use itsdangerous to generate hashes and salts of passwords and store them in your sqlite database.

Typically, you'd have a table with id, username, password, and a boolean flag like "is_admin" or something that you can check when you authenticate.

So, it's fine for some playing around, but I wouldn't recommend anything like this in production.

Upvotes: 1

Related Questions