add-frames (#1)

Adds a iframe view for apps in the dashboard. Makes it usable for our setup.

Co-authored-by: Philipp Rothmann <philipprothmann@posteo.de>
Co-authored-by: viehlieb <pf@pragma-shift.net>
Reviewed-on: #1
This commit is contained in:
philipp 2022-11-02 10:25:43 +01:00
parent 696ffba9fe
commit dea8773ff6
63 changed files with 1408 additions and 896 deletions

9
backend/.env.sample Normal file
View file

@ -0,0 +1,9 @@
HYDRA_CLIENT_ID=
HYDRA_CLIENT_SECRET=
HYDRA_AUTHORIZATION_BASE_URL="https://sso.example.org/application/o/authorize/"
HYDRA_PUBLIC_URL="https://sso.example.org/application/o/"
TOKEN_URL="https://sso.example.org/application/o/token/"
REDIRECT_URL="https://example.org/login-callback"
SECRET_KEY=
LOAD_INCLUSTER_CONFIG=false
DATABASE_URL=sqlite:///database.db

1
backend/.gitignore vendored
View file

@ -8,3 +8,4 @@ __pycache__
.envrc
.direnv
run_app.local.sh
*.db

View file

@ -15,11 +15,11 @@ ADD requirements.txt .
# pip install the local requirements.txt
RUN pip install -r requirements.txt
# now copy all the files in this directory to /code
# now copy all the files in this directory to /app
ADD . .
# Listen to port 80 at runtime
EXPOSE 5000
# Define our command to be run when launching the container
CMD ["gunicorn", "app:app", "-b", "0.0.0.0:5000", "--workers", "4", "--reload", "--capture-output", "--enable-stdio-inheritance", "--log-level", "DEBUG"]
ENTRYPOINT [ "/app/entrypoint.sh" ]

14
backend/Makefile Normal file
View file

@ -0,0 +1,14 @@
build:
docker build -t dashboard-backend .
docker tag dashboard-backend yksflip/dashboard-backend:latest
clean:
rm database.db
flask db upgrade
demo:
flask cli app create nextcloud Dateiablage "https://cloud.dev.local-it.cloud"
flask cli app create vikunja Projekte "https://vikunja.dev.local-it.cloud"
run:
flask run

View file

@ -0,0 +1,32 @@
"""Everything to do with Apps"""
from database import db
from .models import App
class LITApp(App):
"""
"""
def get_url(self):
return self.url
def to_dict(self):
"""
represent this object as a dict, compatible for JSON output
"""
return {"id": self.id,
"name": self.name,
"slug": self.slug,
"external": self.external,
"status": self.get_status(),
"url": self.get_url()}
def get_status(self):
"""Returns an AppStatus object that describes the current cluster state"""
return {
"installed": "",
"ready": "",
"message": "",
}

View file

@ -1 +1 @@
from .auth import *
from .lit_auth import *

View file

@ -30,38 +30,39 @@ def hydra_callback():
token = HydraOauth.get_token(state, code)
user_info = HydraOauth.get_user_info()
# Match Kratos identity with Hydra
identities = KratosApi.get("/identities")
identity = None
for i in identities.json():
if i["traits"]["email"] == user_info["email"]:
identity = i
# identities = KratosApi.get("/identities")
# identity = None
# for i in identities.json():
# if i["traits"]["email"] == user_info["email"]:
# identity = i
access_token = create_access_token(
identity=token, expires_delta=timedelta(days=365), additional_claims={"user_id": identity["id"]}
identity=token, expires_delta=timedelta(days=365),
#additional_claims={"user_id": identity["id"]}
)
apps = App.query.all()
app_roles = []
for app in apps:
tmp_app_role = AppRole.query.filter_by(
user_id=identity["id"], app_id=app.id
).first()
app_roles.append(
{
"name": app.slug,
"role_id": tmp_app_role.role_id if tmp_app_role else None,
}
)
# apps = App.query.all()
# app_roles = []
# for app in apps:
# tmp_app_role = AppRole.query.filter_by(
# user_id=identity["id"], app_id=app.id
# ).first()
# app_roles.append(
# {
# "name": app.slug,
# "role_id": tmp_app_role.role_id if tmp_app_role else None,
# }
# )
return jsonify(
{
"accessToken": access_token,
"userInfo": {
"id": identity["id"],
"id": user_info["email"],
"email": user_info["email"],
"name": user_info["name"],
"preferredUsername": user_info["preferred_username"],
"app_roles": app_roles,
# "app_roles": app_roles,
},
}
)

View file

@ -0,0 +1,63 @@
from multiprocessing import current_process
from flask import jsonify, request
from flask_jwt_extended import create_access_token
from flask_cors import cross_origin
from datetime import timedelta
from areas import api_v1
from areas.apps import App, AppRole
from config import *
from helpers import HydraOauth, BadRequest
@api_v1.route("/login", methods=["POST"])
@cross_origin()
def login():
authorization_url = HydraOauth.authorize()
return jsonify({"authorizationUrl": authorization_url})
@api_v1.route("/hydra/callback")
@cross_origin()
def hydra_callback():
state = request.args.get("state")
code = request.args.get("code")
if state == None:
raise BadRequest("Missing state query param")
if code == None:
raise BadRequest("Missing code query param")
token = HydraOauth.get_token(state, code)
user_info = HydraOauth.get_user_info()
access_token = create_access_token(
identity=token, expires_delta=timedelta(days=365),
#additional_claims={"user_id": identity["id"]}
)
# apps = App.query.all()
# app_roles = []
# for app in apps:
# tmp_app_role = AppRole.query.filter_by(
# user_id=identity["id"], app_id=app.id
# ).first()
# app_roles.append(
# {
# "name": app.slug,
# "role_id": tmp_app_role.role_id if tmp_app_role else None,
# }
# )
return jsonify(
{
"accessToken": access_token,
"userInfo": {
"id": user_info["email"],
"email": user_info["email"],
"name": user_info["name"],
"preferredUsername": user_info["preferred_username"],
# "app_roles": app_roles,
},
}
)

View file

@ -1,10 +1,19 @@
import os
SECRET_KEY = os.environ.get("SECRET_KEY")
def env_file(key: str):
file_env = os.environ.get(f"{key}_FILE")
if file_env and os.path.exists(file_env):
return open(file_env).read().rstrip('\n')
return os.environ.get(key)
SECRET_KEY = env_file("SECRET_KEY")
HYDRA_CLIENT_ID = os.environ.get("HYDRA_CLIENT_ID")
HYDRA_CLIENT_SECRET = os.environ.get("HYDRA_CLIENT_SECRET")
HYDRA_CLIENT_SECRET = env_file("HYDRA_CLIENT_SECRET")
HYDRA_AUTHORIZATION_BASE_URL = os.environ.get("HYDRA_AUTHORIZATION_BASE_URL")
TOKEN_URL = os.environ.get("TOKEN_URL")
REDIRECT_URL = os.environ.get("REDIRECT_URL")
LOGIN_PANEL_URL = os.environ.get("LOGIN_PANEL_URL")

6
backend/entrypoint.sh Executable file
View file

@ -0,0 +1,6 @@
#!/bin/sh
set -eu
env
flask db upgrade
gunicorn app:app -b 0.0.0.0:5000 --workers "$(nproc)" --reload --capture-output --enable-stdio-inheritance --log-level DEBUG

View file

@ -9,7 +9,7 @@ class HydraOauth:
@staticmethod
def authorize():
try:
hydra = OAuth2Session(HYDRA_CLIENT_ID)
hydra = OAuth2Session(HYDRA_CLIENT_ID, redirect_uri=REDIRECT_URL)
authorization_url, state = hydra.authorization_url(
HYDRA_AUTHORIZATION_BASE_URL
)

View file

@ -20,11 +20,11 @@ from config import LOAD_INCLUSTER_CONFIG
#
# By default this loads whatever we define in the `KUBECONFIG` env variable,
# otherwise loads the config from default locations, similar to what kubectl
# does.
if LOAD_INCLUSTER_CONFIG:
config.load_incluster_config()
else:
config.load_kube_config()
# # does.
# if LOAD_INCLUSTER_CONFIG:
# config.load_incluster_config()
# else:
# config.load_kube_config()
def create_variables_secret(app_slug, variables_filepath):
"""Checks if a variables secret for app_name already exists, generates it if necessary.

View file

@ -1,46 +0,0 @@
"""empty message
Revision ID: 27761560bbcb
Revises:
Create Date: 2021-12-21 06:07:14.857940
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "27761560bbcb"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"app",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.String(length=64), nullable=True),
sa.Column("slug", sa.String(length=64), nullable=True),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("slug"),
)
op.create_table(
"app_role",
sa.Column("user_id", sa.String(length=64), nullable=False),
sa.Column("app_id", sa.Integer(), nullable=False),
sa.Column("role", sa.String(length=64), nullable=True),
sa.ForeignKeyConstraint(
["app_id"],
["app.id"],
),
sa.PrimaryKeyConstraint("user_id", "app_id"),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("app_role")
op.drop_table("app")
# ### end Alembic commands ###

View file

@ -1,25 +0,0 @@
"""add-velero-as-app
Revision ID: 3fa0c38ea1ac
Revises: e08df0bef76f
Create Date: 2022-10-13 09:40:44.290319
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3fa0c38ea1ac'
down_revision = 'e08df0bef76f'
branch_labels = None
depends_on = None
def upgrade():
# Add monitoring app
op.execute(f'INSERT IGNORE INTO app (`name`, `slug`) VALUES ("Velero","velero")')
def downgrade():
pass

View file

@ -1,48 +0,0 @@
"""convert role column to table
Revision ID: 5f462d2d9d25
Revises: 27761560bbcb
Create Date: 2022-04-13 15:00:27.182898
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = "5f462d2d9d25"
down_revision = "27761560bbcb"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
role_table = op.create_table(
"role",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.String(length=64), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.add_column("app_role", sa.Column("role_id", sa.Integer(), nullable=True))
op.create_foreign_key(None, "app_role", "role", ["role_id"], ["id"])
# ### end Alembic commands ###
# Insert default role "admin" as ID 1
op.execute(sa.insert(role_table).values(id=1,name="admin"))
# Set role_id 1 to all current "admin" users
op.execute("UPDATE app_role SET role_id = 1 WHERE role = 'admin'")
# Drop old column
op.drop_column("app_role", "role")
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"app_role", sa.Column("role", mysql.VARCHAR(length=64), nullable=True)
)
op.drop_constraint(None, "app_role", type_="foreignkey")
op.drop_column("app_role", "role_id")
op.drop_table("role")
# ### end Alembic commands ###

View file

@ -1,76 +0,0 @@
"""update apps and add 'user' and 'no access' role
Revision ID: b514cca2d47b
Revises: 5f462d2d9d25
Create Date: 2022-06-08 17:24:51.305129
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b514cca2d47b'
down_revision = '5f462d2d9d25'
branch_labels = None
depends_on = None
def upgrade():
# ### end Alembic commands ###
# Check and update app table in DB
apps = {
"dashboard": "Dashboard",
"wekan": "Wekan",
"wordpress": "WordPress",
"nextcloud": "Nextcloud",
"zulip": "Zulip"
}
# app table
app_table = sa.table('app', sa.column('id', sa.Integer), sa.column(
'name', sa.String), sa.column('slug', sa.String))
existing_apps = op.get_bind().execute(app_table.select()).fetchall()
existing_app_slugs = [app['slug'] for app in existing_apps]
for app_slug in apps.keys():
if app_slug in existing_app_slugs:
op.execute(f'UPDATE app SET `name` = "{apps.get(app_slug)}" WHERE slug = "{app_slug}"')
else:
op.execute(f'INSERT INTO app (`name`, slug) VALUES ("{apps.get(app_slug)}","{app_slug}")')
# Fetch all apps including newly created
existing_apps = op.get_bind().execute(app_table.select()).fetchall()
# Insert role "user" as ID 2
op.execute("INSERT INTO `role` (id, `name`) VALUES (2, 'user')")
# Insert role "no access" as ID 3
op.execute("INSERT INTO `role` (id, `name`) VALUES (3, 'no access')")
# Set role_id 2 to all current "user" users which by have NULL role ID
op.execute("UPDATE app_role SET role_id = 2 WHERE role_id IS NULL")
# Add 'no access' role for all users that don't have any roles for specific apps
app_roles_table = sa.table('app_role', sa.column('user_id', sa.String), sa.column(
'app_id', sa.Integer), sa.column('role_id', sa.Integer))
app_ids = [app['id'] for app in existing_apps]
app_roles = op.get_bind().execute(app_roles_table.select()).fetchall()
user_ids = set([app_role['user_id'] for app_role in app_roles])
for user_id in user_ids:
existing_user_app_ids = [x['app_id'] for x in list(filter(lambda role: role['user_id'] == user_id, app_roles))]
missing_user_app_ids = [x for x in app_ids if x not in existing_user_app_ids]
if len(missing_user_app_ids) > 0:
values = [{'user_id': user_id, 'app_id': app_id, 'role_id': 3} for app_id in missing_user_app_ids]
op.bulk_insert(app_roles_table, values)
def downgrade():
# Revert all users role_id to NULL where role is 'user'
op.execute("UPDATE app_role SET role_id = NULL WHERE role_id = 2")
# Delete role 'user' from roles
op.execute("DELETE FROM `role` WHERE id = 2")
# Delete all user app roles where role is 'no access' with role_id 3
op.execute("DELETE FROM app_role WHERE role_id = 3")
# Delete role 'no access' from roles
op.execute("DELETE FROM `role` WHERE id = 3")

View file

@ -0,0 +1,51 @@
"""empty message
Revision ID: d70b750a1297
Revises:
Create Date: 2022-10-25 11:32:27.303354
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd70b750a1297'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('app',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=True),
sa.Column('slug', sa.String(length=64), nullable=True),
sa.Column('external', sa.Boolean(), server_default='0', nullable=False),
sa.Column('url', sa.String(length=128), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('slug')
)
op.create_table('role',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('app_role',
sa.Column('user_id', sa.String(length=64), nullable=False),
sa.Column('app_id', sa.Integer(), nullable=False),
sa.Column('role_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['app_id'], ['app.id'], ),
sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
sa.PrimaryKeyConstraint('user_id', 'app_id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('app_role')
op.drop_table('role')
op.drop_table('app')
# ### end Alembic commands ###

View file

@ -1,33 +0,0 @@
"""Add fields for external apps
Revision ID: e08df0bef76f
Revises: b514cca2d47b
Create Date: 2022-09-23 16:38:06.557307
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e08df0bef76f'
down_revision = 'b514cca2d47b'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('app', sa.Column('external', sa.Boolean(), server_default='0', nullable=False))
op.add_column('app', sa.Column('url', sa.String(length=128), nullable=True))
# ### end Alembic commands ###
# Add monitoring app
op.execute(f'INSERT IGNORE INTO app (`name`, `slug`) VALUES ("Monitoring","monitoring")')
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('app', 'url')
op.drop_column('app', 'external')
# ### end Alembic commands ###