test_login.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import bcrypt
  2. import myloginpath
  3. import pymysql
  4. def test_login(username, password):
  5. conf = myloginpath.parse('app_auth')
  6. conn = pymysql.connect(
  7. host=conf.get('host', '127.0.0.1'),
  8. user=conf.get('user'),
  9. password=conf.get('password'),
  10. database='food_db',
  11. cursorclass=pymysql.cursors.DictCursor
  12. )
  13. with conn.cursor() as cursor:
  14. cursor.execute("SELECT password_hash FROM users WHERE username = %s LIMIT 1", (username,))
  15. result = cursor.fetchone()
  16. conn.close()
  17. if result:
  18. return bcrypt.checkpw(password.encode('utf-8'), result['password_hash'].encode('utf-8'))
  19. return False
  20. # Try registering a user and testing it
  21. def register_and_test():
  22. conf = myloginpath.parse('app_auth')
  23. conn = pymysql.connect(
  24. host=conf.get('host', '127.0.0.1'),
  25. user=conf.get('user'),
  26. password=conf.get('password'),
  27. database='food_db',
  28. cursorclass=pymysql.cursors.DictCursor
  29. )
  30. username = "test_bot"
  31. password = "bot_password"
  32. hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  33. try:
  34. with conn.cursor() as cursor:
  35. cursor.execute("INSERT INTO users (username, password_hash, email) VALUES (%s, %s, %s)", (username, hashed, 'bot@bot.com'))
  36. conn.commit()
  37. except Exception as e:
  38. print("Insert failed:", e)
  39. conn.close()
  40. print("Login successful?", test_login(username, password))
  41. if __name__ == "__main__":
  42. register_and_test()