You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

117 lines
3.3 KiB

2 years ago
  1. #!/usr/bin/env python3
  2. from flask import Flask, render_template, session, request, abort, redirect, url_for
  3. from flask_sqlalchemy import SQLAlchemy
  4. import bcrypt
  5. db: SQLAlchemy = SQLAlchemy()
  6. app = Flask(__name__)
  7. app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
  8. app.secret_key = '98d31240f9fbe14c8083586db49c19c3a8d3f726'
  9. class Admin(db.Model):
  10. id = db.Column(db.Integer, primary_key=True)
  11. username = db.Column(db.String, unique=True, nullable=False)
  12. password = db.Column(db.String, nullable=False)
  13. query: db.Query
  14. @classmethod
  15. def generate_password(cls, pw: str):
  16. return bcrypt.hashpw(pw, bcrypt.gensalt(12))
  17. @classmethod
  18. def authenticate(cls, username: str, pw: str):
  19. user = Admin.query.filter_by(username=username).one_or_none()
  20. if user and bcrypt.checkpw(pw, user.password):
  21. session['admin'] = user.username
  22. return user
  23. else:
  24. return None
  25. @classmethod
  26. def exists(cls):
  27. user = Admin.query.one_or_none()
  28. return True if user else False
  29. @classmethod
  30. def authorize(cls):
  31. if not session.get('admin'):
  32. return redirect(url_for("admin_login"))
  33. # Error Handlers
  34. @app.errorhandler(404)
  35. def handler_404(msg):
  36. return render_template("errors/404.html")
  37. @app.errorhandler(403)
  38. def handler_403(msg):
  39. return render_template("errors/403.html")
  40. # Admin routes
  41. @app.route('/admin')
  42. def admin_root():
  43. if login := Admin.authorize():
  44. return login
  45. return render_template("admin.html", user=session.get("admin"))
  46. @app.route('/admin/create', methods=['GET', 'POST'])
  47. def admin_create():
  48. if Admin.exists():
  49. if login := Admin.authorize():
  50. return login
  51. if request.method == "GET":
  52. return render_template("register.html")
  53. else:
  54. username, pw = request.form.get('username'), request.form.get('password')
  55. if username is None or pw is None:
  56. return render_template("register.html", fail="Invalid Input.")
  57. elif db.session.execute(db.select(Admin).filter_by(username=username)).fetchone():
  58. return render_template("register.html", fail="Username already exists.")
  59. else:
  60. db.session.add(Admin(username=username, password=Admin.generate_password(pw)))
  61. db.session.commit()
  62. return render_template("register.html", success=True)
  63. @app.route('/admin/login', methods=['GET', 'POST'])
  64. def admin_login():
  65. if request.method == "POST":
  66. username, pw = request.form.get('username', ''), request.form.get('password', '')
  67. if Admin.authenticate(username, pw):
  68. return render_template("login.html", success=True)
  69. else:
  70. return render_template("login.html", fail="Could not authenticate.")
  71. else:
  72. return render_template("login.html")
  73. @app.route('/admin/logout', methods=['GET'])
  74. def admin_logout():
  75. session.pop('admin')
  76. return redirect(url_for('home'))
  77. @app.route("/")
  78. def home():
  79. if Admin.exists():
  80. return render_template("index.html")
  81. else:
  82. return redirect(url_for("admin_create"))
  83. @app.route("/search")
  84. def search():
  85. return "searching url"
  86. if __name__ == "__main__":
  87. db.init_app(app)
  88. with app.app_context():
  89. db.create_all()
  90. app.run(debug=True)