login.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # This is only a module to make the login process faster and easier. Don't care about it unless you also wants a simple login for your app
  2. import hashlib as hl
  3. from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
  4. def initLogin(app, db):
  5. # Create the User clasis
  6. class User(UserMixin, db.Model):
  7. id = db.Column(db.Integer, primary_key=True)
  8. username = db.Column(db.Text, unique=True)
  9. password = db.Column(db.Text)
  10. def __init__(self, username, password):
  11. self.username = username
  12. self.password = password
  13. # Configure login
  14. login_manager = LoginManager()
  15. login_manager.init_app(app)
  16. @login_manager.user_loader
  17. def load_user(user_id):
  18. return User.query.get(int(user_id))
  19. return User
  20. def loginUser(username, password, User):
  21. # Hash the username and the password
  22. #username = hl.md5(bytes(username, 'utf-8')).hexdigest()
  23. password = hl.md5(bytes(password, 'utf-8')).hexdigest()
  24. # Check if it exists
  25. user = User.query.filter_by(username=username, password=password).first_or_404()
  26. login_user(user)
  27. return True
  28. def createUser(username, password, db, User):
  29. # hash the username and the password
  30. #username = hl.md5(bytes(username, 'utf-8')).hexdigest() # Comment this is you want a clear username
  31. password = hl.md5(bytes(password, 'utf-8')).hexdigest()
  32. # Send them to db
  33. user = User(username, password)
  34. db.session.add(user)
  35. db.session.commit()
  36. # Login the user
  37. login_user(user)
  38. # return success
  39. return True
  40. def getUsername():
  41. return current_user.username
  42. # To restrict a page to a user just add @login_required
  43. # To logout just do logout_user()
  44. # To get the current username do current_user.username