Is this a proper/secure way to log someone in? Is this a proper/secure way to log someone in? flask flask

Is this a proper/secure way to log someone in?


That's absolutely the way to do it. The client side cookie allows you to uniquely identify a user. You just have to make sure the cookie is sufficiently randomized, otherwise someone could spoof it.

If your cookie for me was uid=hailey that would be bad because I could easily edit that to be uid=ach1lles and get your admin access. Instead, you want to do something sufficiently random, like a base64 of a sha2 hash of my username and the current time and the headline of yesterday's NYT or something crazy like that. You would want to add this as a database table, and then check it when I make a request.

Also, don't store the password as text, consider something like bcrypt. :)


Your second SELECT query exposes a security risk. Someone can log in as any user simply by knowing the password of any one user.

Imagine you have the following users (ignoring that the passwords are plaintext):

username | password---------+---------Jack     | abc123-------------------Jill     | def456

Let's say someone attempts to log in with "Jack" as the username and "def456" as the password.

Your first SELECT

c = g.db.execute("SELECT username from users where username = (?)", [form.username.data])

is going to return the record for Jack. This causes you to execute your second SELECT

c = g.db.execute("SELECT password from users where password = (?)", [form.password.data])

This is going to return the record for Jill. While this is a different user, you only check for a record returned from the query, not the same record as the first query. The user will be logged in as Jack even though they got Jack's password wrong.

Ideally you want to perform only one query, based on username, and compare the submitted password to the one in the database.

c = g.db.execute("SELECT username, password from users where username = (?)", [form.username.data])user = c.fetchone()# don't forget to apply your hashing algorithm to form.password.dataif user and user[1] == form.password.data:      session['username'] = form.username.data    session['logged_in'] = True    flash('You were logged in')    return redirect(url_for('account'))

All that said, I can't recommend libraries like Flask-Login and Flask-Security enough. Authentication is hard to get right. Leverage the community to make it easier.