when I use basic authenticate of user login with name and plaintext password, user is logged in correctly.
Password is correctly hashed during registration. When I store hashed password and try to authenticate it, program gives error:
AttributeError: type object 'User' has no attribute 'query'
Could you please tell me, what is wrong? I suspect that checking function can't find hashed password from SQLAlchemy database. Thank you.
When I use :
query = s.query(User).filter(User.username.in_([POST_USERNAME]))
I get:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with User.password has an attribute 'split'
engine = create_engine('sqlite:///tutorial.db', echo=True)
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = 'XXXXX'
def hash_password(password):
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String(64))
password = Column(String(120))
email = Column(String(64))
def __init__(self, username, password, email):
self.username = username
self.password = password
self.email = email
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
Base.metadata.create_all(engine)
@app.route("/")
def index():
return render_template('index.html')
@app.route('/login', methods=['POST'])
def do_admin_login():
POST_USERNAME = str(request.form['username'])
POST_PASSWORD = str(request.form['password'])
Session = sessionmaker(bind=engine)
s = Session()
user = User.query.filter_by(username=POST_USERNAME).first()
if check_password(User.password, POST_PASSWORD) == True:
session['logged_in'] = True
else:
flash('wrong password!')
return index()