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 %} + {{ title }} - WPI ACM + {% else %} + WPI Association for Computing Machinery + {% endif %} + + + + {% block styles %} + + {{ bootstrap.load_css() }} + {% endblock %} + + {% endblock %} + + + + {% block navbar %}{% endblock %} + + +
+
+ {{ render_messages(container=False, dismissible=True, dismiss_animate=True) }} +
+ + {% block app_content %}{% endblock %} + +
+ + {% block scripts %} + + {{ bootstrap.load_js() }} + {% endblock %} + + + diff --git a/acmsite/templates/index.html b/acmsite/templates/index.html new file mode 100644 index 0000000..1d419a3 --- /dev/null +++ b/acmsite/templates/index.html @@ -0,0 +1,5 @@ +{% extends 'layout.html' %} + +{% block app_content %} + +{% endblock app_content %} diff --git a/acmsite/templates/layout.html b/acmsite/templates/layout.html new file mode 100644 index 0000000..cbdfd06 --- /dev/null +++ b/acmsite/templates/layout.html @@ -0,0 +1,72 @@ +{% extends 'bootstrap-base.html' %} + +{% block html_attribs %} lang="en"{% endblock %} + +{% block title %}{% if title %}{{ title }} - WPI ACM{% else %}WPI Association for Computing Machinery{%endif %}{% endblock %} + +{% block head %} +{{super()}} + +{% endblock %} + +{% block navbar %} + +{% block header %} + +{% endblock header %} +{% endblock %} diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..0e04844 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 0000000..ec9d45c --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..4c97092 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..2c01563 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/236945763c86_.py b/migrations/versions/236945763c86_.py new file mode 100644 index 0000000..1f5db83 --- /dev/null +++ b/migrations/versions/236945763c86_.py @@ -0,0 +1,48 @@ +"""empty message + +Revision ID: 236945763c86 +Revises: +Create Date: 2024-02-28 17:51:45.350666 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '236945763c86' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('acm_users', + sa.Column('id', sa.String(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('password', sa.String(), nullable=False), + sa.Column('first_name', sa.String(), nullable=False), + sa.Column('last_name', sa.String(), nullable=False), + sa.Column('created', sa.DateTime(), nullable=False), + sa.Column('last_login', sa.DateTime(), nullable=False), + sa.Column('active', sa.Boolean(), nullable=False), + sa.Column('is_admin', sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('email') + ) + op.create_table('pw_reset_request', + sa.Column('id', sa.String(), nullable=False), + sa.Column('user_id', sa.String(), nullable=False), + sa.Column('expires', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['acm_users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('pw_reset_request') + op.drop_table('acm_users') + # ### end Alembic commands ### diff --git a/migrations/versions/7cdd046a2abf_make_password_nullable.py b/migrations/versions/7cdd046a2abf_make_password_nullable.py new file mode 100644 index 0000000..02e086b --- /dev/null +++ b/migrations/versions/7cdd046a2abf_make_password_nullable.py @@ -0,0 +1,36 @@ +"""make password nullable + +Revision ID: 7cdd046a2abf +Revises: 236945763c86 +Create Date: 2024-03-03 17:38:32.319173 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7cdd046a2abf' +down_revision = '236945763c86' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('acm_users', schema=None) as batch_op: + batch_op.alter_column('email', + existing_type=sa.VARCHAR(), + nullable=True) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('acm_users', schema=None) as batch_op: + batch_op.alter_column('email', + existing_type=sa.VARCHAR(), + nullable=False) + + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..075aaac --- /dev/null +++ b/requirements.txt @@ -0,0 +1,28 @@ +alembic==1.13.1 +Authlib==1.3.0 +Bootstrap-Flask==2.3.3 +certifi==2024.2.2 +cffi==1.16.0 +charset-normalizer==3.3.2 +click==8.1.7 +cryptography==42.0.5 +Flask==2.2.2 +Flask-FontAwesome==0.1.5 +Flask-Login==0.6.3 +Flask-Migrate==4.0.5 +Flask-SQLAlchemy==3.0.3 +greenlet==3.0.3 +idna==3.6 +itsdangerous==2.1.2 +Jinja2==3.1.3 +Mako==1.3.2 +MarkupSafe==2.1.5 +psycopg2==2.9.9 +pycparser==2.21 +requests==2.31.0 +SQLAlchemy==2.0.27 +typing_extensions==4.10.0 +ulid==1.1 +urllib3==2.2.1 +Werkzeug==2.3.7 +WTForms==3.1.2 diff --git a/wsgi.py b/wsgi.py new file mode 100644 index 0000000..83817c5 --- /dev/null +++ b/wsgi.py @@ -0,0 +1,3 @@ +from acmsite import create_app + +application = create_app()