Skip to content
Snippets Groups Projects
Commit 1f7f0c5a authored by Jan Hartig's avatar Jan Hartig
Browse files

Fix json error response

parent 284acae3
No related branches found
No related tags found
1 merge request!25Fix json error response
### venv template
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
.Python
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
.venv
pip-selfcheck.json
### PyCharm template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
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/
.webassets-cache
# 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
.env
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/
......@@ -4,49 +4,48 @@ import json
from base64 import urlsafe_b64encode
from time import time
from urllib.parse import quote
from wonderwords import RandomWord
import aiofiles
from aiofiles import open
from sanic import Sanic, Request
from sanic.exceptions import Unauthorized, InvalidUsage
from sanic.response import redirect
from sanic.response import json as json_response
from sanic.response import redirect
from wonderwords import RandomWord
app = Sanic(__name__)
r = RandomWord()
''' Config ###
""" Config ###
Set via environment variable
SANIC_JITSI_PUBLIC_URL: vc.ptb.de
SANIC_JITSI_APP_ID
SANIC_JITSI_APP_SECRET: Jitsi App Secret
SANIC_TOKEN_VALID_FOR: Time in seconds generated personal room JWT will be valid for
SANIC_ROOMS_VALID_FOR: Time in days generated room JWT will be valid for
'''
"""
# Static token header string
header = json.dumps({
"typ": "JWT",
"alg": "HS256"
}, separators=(',', ':')).encode("utf-8")
header = json.dumps({"typ": "JWT", "alg": "HS256"}, separators=(",", ":")).encode(
"utf-8"
)
ROOMS_VALID_FOR_S = app.config.ROOMS_VALID_FOR * 24 * 60 * 60 # d, h, m -> s
@app.post('/unlockroom')
@app.post("/unlockroom")
async def unlock_room(request: Request):
check_auth(request)
try:
room = request.json["room"]
if len(room) == 0:
if len(room) < 2:
return InvalidUsage
serial2room = await get_serial2room()
for entry in serial2room.values():
if room.lower() == entry["room"].lower():
return {"error": "Raum nicht freischaltbar."}
return json_response({"error": "Raum nicht freischaltbar."})
except KeyError:
room = get_random_room()
......@@ -57,11 +56,13 @@ async def unlock_room(request: Request):
# Generate jwt
jwt = gen_jwt(room, ROOMS_VALID_FOR_S)
# redirect to room
return json_response({"room": room, "jwt": jwt, "valid_for": app.config.ROOMS_VALID_FOR})
# return room details
return json_response(
{"room": room, "jwt": jwt, "valid_for": app.config.ROOMS_VALID_FOR}
)
@app.route('/cert2room')
@app.route("/cert2room")
async def cert2room(request: Request):
dn = check_auth(request)
serial = request.headers.get("SSL-Client-Serial")
......@@ -109,21 +110,18 @@ def check_auth(request: Request) -> dict:
def get_random_room() -> str:
adjectives = r.random_words(2, include_parts_of_speech=["adjectives"])
nouns = r.random_words(2, include_parts_of_speech=["nouns"])
return f"{adjectives[0].capitalize()}{nouns[0].capitalize()}{adjectives[1].capitalize()}{nouns[1].capitalize()}"
return f"{r.word(include_parts_of_speech=['adjectives'])}{r.word(include_parts_of_speech=['nouns'])}"
async def get_serial2room():
# Get user data by certificate serial number
try:
async with aiofiles.open("/data/serial2room.json", "r") as f:
async with open("/data/serial2room.json", "r") as f:
serial2room = json.loads(await f.read())
except FileNotFoundError:
# dev: try environment variable for file
async with aiofiles.open(app.config.SERIAL2ROOM_FILE, "r") as f:
async with open(app.config.SERIAL2ROOM_FILE, "r") as f:
serial2room = json.loads(await f.read())
return serial2room
......@@ -131,16 +129,19 @@ async def get_serial2room():
def gen_jwt(room: str, valid_for: int) -> str:
now = int(time())
claims = json.dumps({
"context": {}, # Setting name and email here leads to auth failure
"iss": app.config.JITSI_APP_ID,
"sub": app.config.JITSI_PUBLIC_URL,
"iat": now,
"nbf": now,
"exp": now + valid_for,
"aud": 'DFNClientCert',
"room": room,
}, separators=(',', ':')).encode("utf-8")
claims = json.dumps(
{
"context": {}, # Setting name and email here leads to auth failure
"iss": app.config.JITSI_APP_ID,
"sub": app.config.JITSI_PUBLIC_URL,
"iat": now,
"nbf": now,
"exp": now + valid_for,
"aud": "DFNClientCert",
"room": room,
},
separators=(",", ":"),
).encode("utf-8")
# Build token as bytestring
msg = urlsafe_b64encode(header) + b"." + urlsafe_b64encode(claims)
......@@ -159,5 +160,5 @@ def gen_jwt(room: str, valid_for: int) -> str:
return "{}.{}".format(msg.decode("utf-8"), signature.decode("utf-8"))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, fast=True, access_log=True)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, fast=True, access_log=True)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment