diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..01d8029 --- /dev/null +++ b/.gitignore @@ -0,0 +1,266 @@ +# Created by https://www.toptal.com/developers/gitignore/api/python,flask +# Edit at https://www.toptal.com/developers/gitignore?templates=python,flask + +### Flask ### +instance/* +!instance/.gitignore +.webassets-cache +.env + +### Flask.Python Stack ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python ### +# Byte-compiled / optimized / DLL files + +# C extensions + +# Distribution / packaging + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. + +# Installer logs + +# Unit test / coverage reports + +# Translations + +# Django stuff: + +# Flask stuff: + +# Scrapy stuff: + +# Sphinx documentation + +# PyBuilder + +# Jupyter Notebook + +# IPython + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm + +# Celery stuff + +# SageMath parsed files + +# Environments + +# Spyder project settings + +# Rope project settings + +# mkdocs documentation + +# mypy + +# Pyre type checker + +# pytype static type analyzer + +# Cython debug symbols + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +# End of https://www.toptal.com/developers/gitignore/api/python,flask + +# Configuration file +acmsite/config.py +.env diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2cefaa7 --- /dev/null +++ b/Makefile @@ -0,0 +1,39 @@ +SHELL := /bin/bash +all: clean + +# Clean up temp files +#------------------------------------------------------------------ +clean: + @echo "Cleaning up temp files" + @find . -name '*~' -ls -delete + @find . -name '*.bak' -ls -delete + @echo "Cleaning up __pycache__ directories" + @find . -name __pycache__ -type d -not -path "./.venv/*" -ls -exec rm -r {} + + @echo "Cleaning up logfiles" + @find ./logs -name '*.log*' -ls -delete + @echo "Cleaning up flask_session" + @find . -name flask_session -type d -not -path "./.venv/*" -ls -exec rm -r {} + + +init_env: + python3 -m venv .venv + source .venv/bin/activate && pip3 install --upgrade pip + source .venv/bin/activate && pip3 install -r requirements.txt txt + +upgrade_env: + source .venv/bin/activate && pip3 install --upgrade -r requirements.txt + +make_migrations: + source .venv/bin/activate && flask db migrate + +run_migrations: + source .venv/bin/activate && flask db upgrade + +daemon: + @echo "--- STARTING UWSGI DAEMON ---" + @echo "" + @echo "" + source .venv/bin/activate && flask run + @echo "" + @echo "" + @echo "--- STARTING UWSGI DAEMON ---" + diff --git a/acmsite/__init__.py b/acmsite/__init__.py new file mode 100644 index 0000000..1e03b66 --- /dev/null +++ b/acmsite/__init__.py @@ -0,0 +1,49 @@ +from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +from flask_login import LoginManager +from flask_bootstrap import Bootstrap5 +from flask_fontawesome import FontAwesome + +from authlib.integrations.flask_client import OAuth + +db = SQLAlchemy() +migrate = Migrate() +login = LoginManager() +bootstrap = Bootstrap5() +font_awesome = FontAwesome() +oauth = OAuth() + +def create_app(): + app = Flask(__name__) + + app.config.from_pyfile('config.py') + + db.init_app(app) + migrate.init_app(app, db) + login.init_app(app) + bootstrap.init_app(app) + font_awesome.init_app(app) + oauth.init_app(app) + + # register Microsoft Graph sign-in + tenant = app.config["AZURE_TENANT_ID"] + AZURE_CLIENT_ID = app.config["AZURE_CLIENT_ID"] + oauth.register( + name='azure', + authorize_url=f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize", + access_token_url=f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token", + api_base_url="https://graph.microsoft.com/v1.0/", + client_kwargs={"scope": "user.read"} + ) + + from .models import User + + from .main import bp as main_bp + app.register_blueprint(main_bp) + + from .auth import bp as auth_bp + app.register_blueprint(auth_bp) + + + return app diff --git a/acmsite/auth/__init__.py b/acmsite/auth/__init__.py new file mode 100644 index 0000000..8c2f816 --- /dev/null +++ b/acmsite/auth/__init__.py @@ -0,0 +1,53 @@ +import datetime +from flask import Blueprint, redirect, render_template, url_for +import ulid +import flask_login + +from acmsite.models import User +from acmsite import db + +bp = Blueprint('auth', __name__, url_prefix='/auth') + +from acmsite import oauth + + +@bp.route('/login') +def login(): + return oauth.azure.authorize_redirect(url_for('auth.oauth2_callback', + _external=True)) + +@bp.route('/register') +def register(): + return render_template('auth/register.html') + +@bp.route("/oauth2") +def oauth2_callback(): + token = oauth.azure.authorize_access_token() + resp = oauth.azure.get('me') + resp.raise_for_status() + profile = resp.json() + print(profile) + u = User.query.filter_by(email=profile['mail']).first() + if u is None: + u = User( + id=ulid.ulid(), + password='', + email=profile['mail'], + first_name=profile['givenName'], + last_name=profile['surname'], + created=datetime.datetime.now(), + last_login=datetime.datetime.now() + ) + db.session.add(u) + db.session.commit() + else: + # Returning user + u.last_login = datetime.datetime.now() + db.session.commit() + flask_login.login_user(u) + return redirect('/') + +@bp.route('/logout') +def logout(): + flask_login.logout_user() + return redirect(url_for('main.homepage')) diff --git a/acmsite/main/__init__.py b/acmsite/main/__init__.py new file mode 100644 index 0000000..52f99d2 --- /dev/null +++ b/acmsite/main/__init__.py @@ -0,0 +1,7 @@ +from flask import Blueprint, render_template + +bp = Blueprint('main', __name__) + +@bp.route("/") +def homepage(): + return render_template("index.html") \ No newline at end of file diff --git a/acmsite/models.py b/acmsite/models.py new file mode 100644 index 0000000..c260dec --- /dev/null +++ b/acmsite/models.py @@ -0,0 +1,31 @@ +from flask import flash, redirect, url_for +from flask_login import UserMixin +from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, null +from . import db +from . import login + +class User(db.Model, UserMixin): + __tablename__ = "acm_users" + id = Column(String, primary_key=True) + email = Column(String, unique=True, nullable=True) + password = Column(String, nullable=False) + first_name = Column(String, nullable=False) + last_name = Column(String, nullable=False) + created = Column(DateTime, nullable=False) + last_login = Column(DateTime, nullable=False) + active = Column(Boolean, nullable=False, default=True) + is_admin = Column(Boolean, nullable=False, default=False) + +@login.user_loader +def user_loader(user_id): + return User.query.filter_by(id=user_id).first() + +@login.unauthorized_handler +def unauth(): + flash("Please log in first!") + return redirect("/") + +class PwResetRequest(db.Model): + id = Column(String, primary_key=True) + user_id = Column(String, ForeignKey('acm_users.id'), nullable=False) + expires = Column(DateTime, nullable=False) diff --git a/acmsite/static/img/logo.png b/acmsite/static/img/logo.png new file mode 100644 index 0000000..fd86645 Binary files /dev/null and b/acmsite/static/img/logo.png differ diff --git a/acmsite/templates/bootstrap-base.html b/acmsite/templates/bootstrap-base.html new file mode 100644 index 0000000..fd542cc --- /dev/null +++ b/acmsite/templates/bootstrap-base.html @@ -0,0 +1,43 @@ +{% from 'bootstrap5/nav.html' import render_nav_item %} +{% from 'bootstrap5/utils.html' import render_messages %} + + + +
+ {% block head %} + {% if title %} +