47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
|
|
from sqlalchemy import inspect, text
|
|
|
|
from ..extensions import db
|
|
from ..models import User
|
|
from .app_settings import ensure_app_settings
|
|
|
|
|
|
def ensure_schema_and_admins() -> None:
|
|
inspector = inspect(db.engine)
|
|
column_names = {column["name"] for column in inspector.get_columns("user")}
|
|
|
|
if "is_admin" not in column_names:
|
|
db.session.execute(text("ALTER TABLE user ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT 0"))
|
|
db.session.commit()
|
|
|
|
if "calendar_feed_token" not in column_names:
|
|
db.session.execute(text("ALTER TABLE user ADD COLUMN calendar_feed_token VARCHAR(255)"))
|
|
db.session.commit()
|
|
|
|
ensure_app_settings()
|
|
|
|
users_without_feed = User.query.filter(User.calendar_feed_token.is_(None)).all()
|
|
if users_without_feed:
|
|
for user in users_without_feed:
|
|
user.ensure_calendar_feed_token()
|
|
db.session.commit()
|
|
|
|
admin_exists = User.query.filter_by(is_admin=True).first()
|
|
if admin_exists:
|
|
return
|
|
|
|
preferred_admin_email = os.getenv("DEFAULT_ADMIN_EMAIL", "mail@hnz.io").lower().strip()
|
|
preferred_user = User.query.filter(User.email.ilike(preferred_admin_email)).first()
|
|
if preferred_user:
|
|
preferred_user.is_admin = True
|
|
db.session.commit()
|
|
return
|
|
|
|
first_user = User.query.order_by(User.id.asc()).first()
|
|
if first_user:
|
|
first_user.is_admin = True
|
|
db.session.commit()
|