Scaffold out authentication
This commit is contained in:
parent
46569c3da1
commit
c59211c225
18 changed files with 868 additions and 0 deletions
266
.gitignore
vendored
Normal file
266
.gitignore
vendored
Normal file
|
@ -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
|
39
Makefile
Normal file
39
Makefile
Normal file
|
@ -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 ---"
|
||||
|
49
acmsite/__init__.py
Normal file
49
acmsite/__init__.py
Normal file
|
@ -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
|
53
acmsite/auth/__init__.py
Normal file
53
acmsite/auth/__init__.py
Normal file
|
@ -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'))
|
7
acmsite/main/__init__.py
Normal file
7
acmsite/main/__init__.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
from flask import Blueprint, render_template
|
||||
|
||||
bp = Blueprint('main', __name__)
|
||||
|
||||
@bp.route("/")
|
||||
def homepage():
|
||||
return render_template("index.html")
|
31
acmsite/models.py
Normal file
31
acmsite/models.py
Normal file
|
@ -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)
|
BIN
acmsite/static/img/logo.png
Normal file
BIN
acmsite/static/img/logo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 9 KiB |
43
acmsite/templates/bootstrap-base.html
Normal file
43
acmsite/templates/bootstrap-base.html
Normal file
|
@ -0,0 +1,43 @@
|
|||
{% from 'bootstrap5/nav.html' import render_nav_item %}
|
||||
{% from 'bootstrap5/utils.html' import render_messages %}
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
{% block head %}
|
||||
{% if title %}
|
||||
<title>{{ title }} - WPI ACM</title>
|
||||
{% else %}
|
||||
<title>WPI Association for Computing Machinery</title>
|
||||
{% endif %}
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
|
||||
{% block styles %}
|
||||
<!-- Bootstrap CSS -->
|
||||
{{ bootstrap.load_css() }}
|
||||
{% endblock %}
|
||||
|
||||
{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
<!-- Your page content -->
|
||||
{% block navbar %}{% endblock %}
|
||||
|
||||
<!-- Your page content -->
|
||||
<div class="container">
|
||||
<div id="outerAlerts">
|
||||
{{ render_messages(container=False, dismissible=True, dismiss_animate=True) }}
|
||||
</div>
|
||||
|
||||
{% block app_content %}{% endblock %}
|
||||
|
||||
</div>
|
||||
|
||||
{% block scripts %}
|
||||
<!-- Optional JavaScript -->
|
||||
{{ bootstrap.load_js() }}
|
||||
{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
|
5
acmsite/templates/index.html
Normal file
5
acmsite/templates/index.html
Normal file
|
@ -0,0 +1,5 @@
|
|||
{% extends 'layout.html' %}
|
||||
|
||||
{% block app_content %}
|
||||
|
||||
{% endblock app_content %}
|
72
acmsite/templates/layout.html
Normal file
72
acmsite/templates/layout.html
Normal file
|
@ -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 %}
|
||||
<nav class="navbar mb-4 navbar-expand-lg">
|
||||
<div class="container-fluid">
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
|
||||
data-bs-target="#navbarSupportedContent"
|
||||
aria-controls="navbarSupportedContent"
|
||||
aria-expanded="true"
|
||||
aria-label="Toggle
|
||||
navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="navbar-header">
|
||||
<a class="navbar-brand" href="{{ url_for('main.homepage') }}">
|
||||
<img src="{{url_for('static', filename='img/logo.png')}}"
|
||||
alt="Logo" width="35" height="35" class="d-inline-block
|
||||
align-text-middle mx-2">WPI ACM</a>
|
||||
</div>
|
||||
<div class="collapse navbar-collapse" id="navbarSupportedContent">
|
||||
<ul class="nav navbar-nav me-auto mb-2 mb-lg-0">
|
||||
{{ render_nav_item('main.homepage', 'Home')}}
|
||||
{{ render_nav_item('main.homepage', 'Events')}}
|
||||
{{ render_nav_item('main.homepage', 'Join Us!')}}
|
||||
</ul>
|
||||
<ul class="nav navbar-nav">
|
||||
{% if current_user.is_authenticated %}
|
||||
{{ render_nav_item('main.homepage', 'Dashboard') }}
|
||||
{% if current_user.is_admin %}
|
||||
{{ render_nav_item('main.homepage', 'Admin Dash') }}
|
||||
{% endif %}
|
||||
{{ render_nav_item('auth.logout', 'Logout') }}
|
||||
{% else %}
|
||||
{{ render_nav_item('auth.login', 'Login with WPI') }}
|
||||
{% endif %}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
{% block header %}
|
||||
<div id="baseCarousel" class="carousel slide" data-bs-ride="ride">
|
||||
<div class="carousel-inner">
|
||||
<div class="carousel-item active">
|
||||
<img src="..." class="d-block w-100" alt="...">
|
||||
</div>
|
||||
<div class="carousel-item">
|
||||
<img src="..." class="d-block w-100" alt="...">
|
||||
</div>
|
||||
<div class="carousel-item">
|
||||
<img src="..." class="d-block w-100" alt="...">
|
||||
</div>
|
||||
</div>
|
||||
<button class="carousel-control-prev" type="button" data-bs-target="#baseCarousel" data-bs-slide="prev">
|
||||
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
|
||||
<span class="visually-hidden">Previous</span>
|
||||
</button>
|
||||
<button class="carousel-control-next" type="button" data-bs-target="#baseCarousel" data-bs-slide="next">
|
||||
<span class="carousel-control-next-icon" aria-hidden="true"></span>
|
||||
<span class="visually-hidden">Next</span>
|
||||
</button>
|
||||
</div>
|
||||
{% endblock header %}
|
||||
{% endblock %}
|
1
migrations/README
Normal file
1
migrations/README
Normal file
|
@ -0,0 +1 @@
|
|||
Single-database configuration for Flask.
|
50
migrations/alembic.ini
Normal file
50
migrations/alembic.ini
Normal file
|
@ -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
|
113
migrations/env.py
Normal file
113
migrations/env.py
Normal file
|
@ -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()
|
24
migrations/script.py.mako
Normal file
24
migrations/script.py.mako
Normal file
|
@ -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"}
|
48
migrations/versions/236945763c86_.py
Normal file
48
migrations/versions/236945763c86_.py
Normal file
|
@ -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 ###
|
36
migrations/versions/7cdd046a2abf_make_password_nullable.py
Normal file
36
migrations/versions/7cdd046a2abf_make_password_nullable.py
Normal file
|
@ -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 ###
|
28
requirements.txt
Normal file
28
requirements.txt
Normal file
|
@ -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
|
3
wsgi.py
Normal file
3
wsgi.py
Normal file
|
@ -0,0 +1,3 @@
|
|||
from acmsite import create_app
|
||||
|
||||
application = create_app()
|
Loading…
Add table
Reference in a new issue