From c59211c22538de33b5b0a70e2672c01945b8999b Mon Sep 17 00:00:00 2001 From: Cara Salter Date: Sun, 3 Mar 2024 17:52:34 -0500 Subject: [PATCH] Scaffold out authentication --- .gitignore | 266 ++++++++++++++++++ Makefile | 39 +++ acmsite/__init__.py | 49 ++++ acmsite/auth/__init__.py | 53 ++++ acmsite/main/__init__.py | 7 + acmsite/models.py | 31 ++ acmsite/static/img/logo.png | Bin 0 -> 9252 bytes acmsite/templates/bootstrap-base.html | 43 +++ acmsite/templates/index.html | 5 + acmsite/templates/layout.html | 72 +++++ migrations/README | 1 + migrations/alembic.ini | 50 ++++ migrations/env.py | 113 ++++++++ migrations/script.py.mako | 24 ++ migrations/versions/236945763c86_.py | 48 ++++ .../7cdd046a2abf_make_password_nullable.py | 36 +++ requirements.txt | 28 ++ wsgi.py | 3 + 18 files changed, 868 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 acmsite/__init__.py create mode 100644 acmsite/auth/__init__.py create mode 100644 acmsite/main/__init__.py create mode 100644 acmsite/models.py create mode 100644 acmsite/static/img/logo.png create mode 100644 acmsite/templates/bootstrap-base.html create mode 100644 acmsite/templates/index.html create mode 100644 acmsite/templates/layout.html create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/236945763c86_.py create mode 100644 migrations/versions/7cdd046a2abf_make_password_nullable.py create mode 100644 requirements.txt create mode 100644 wsgi.py 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 0000000000000000000000000000000000000000..fd86645a84e4bbac329c9de1a1f568cd7c3e7558 GIT binary patch literal 9252 zcmV+fK?T`CHi4#_-n*-}+Lzpyh`8^M$jr{QDzmDxy0R*7oO|?8(UFl6pZxxo zd++ZG>TTTiZ_f<6fv*F8;KqMFwIx`8Dq}aL{s_iy-+pG$CE<$_z9Qjs629^6X9m6X zCo^^v^+!;;{p-^MF5qh5Uw|}BQQ&sq=6^e_HB^5}b+D!aD(Z06!J2UUUr+VBfUAWN z#h}W-C8fL_xcPsd-d2aJ4%XQ1U(!$&S1O7rmxP=DPaUp0SmQxOc~BLY#X4N|sIUlB zeG`ES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AjnWOIo{y$m{9%Yb0>sr;eFNAgv|H; z=Sve(u3YC@(B!tUwAsyZ^BY*w z;HD?9Iw@T1?_}1j|2*T47hG6-Th}678KwH`EP!fOft3xHlr;rcCZ#Z2pqh1H0i5x( z7hJM-lq;iDPyN&EfofKQRYP#iTBv3%SOBN}>;)Hc#ya#FNBybKpB$cz&wo}IZ#nI! z&%1zYfg5HJTp6W$dX_>p>%mIF<&>6k%>=kIwG?JER8Zpy(sJ6jik{c(XT$x!4&wugM@LYeU zb+A(Hq#s&v!Gz$-DAfyB*P*I|RRGtsPLP$tRfnn$*7)tjA3j})a%G@;@#@p+P}QCH z((T2oPm5vg<2Rl|Ux%u$Se3UEe)yCV$u%kE@)d(hz)de+b9x=BI#?CL^@FFJPykm( zsa~o>RR?Q|;8N>Q)xnxdxLjC;-~7N0FI{tbsQy&OZvP)(=S`T2K@(#D0000 + + + {% 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()