initial commit

This commit is contained in:
2026-03-30 13:36:20 +02:00
commit 635b022b66
90 changed files with 17124 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# Linux start script should use lf
/gradlew text eol=lf
# These are Windows script files and should use crlf
*.bat text eol=crlf
+17
View File
@@ -0,0 +1,17 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build
# Ignore vscode metadata
.vscode
# Ingore pyhton cache
__pycache__
# Ignore macos
.DS_Store
# Ignore generated python code
src/python/account/
*.pyc
node_modules/
angular-app/.angular
+57
View File
@@ -0,0 +1,57 @@
# My App
A minimal full-stack web application using Docker, Gradle, FastAPI and Angular.
## Modules
- **service**: Python REST API using FastAPI, SQLAlchemy (SQLite) and JWT authentication. Runs in a Docker container.
- **webapp**: Angular 18 single-page application with Angular Material. Built via Node.js and Gradle.
- **app**: Combined Docker image that serves both the service and the webapp.
## Prerequisites
- Docker
- Java 17+ (for Gradle)
## Build
```bash
./gradlew build
```
This builds the service Docker image, the Angular webapp, and the combined app image.
## Development
Start the service in a Docker container with hot-reload:
```bash
./gradlew :service:serve
```
In a separate terminal, start the Angular dev server:
```bash
cd webapp && npm start
```
The webapp will be available at `http://localhost:4200` and proxies API requests to the service at `localhost:8000`.
## Run
Run the combined app image:
```bash
docker run --rm -p 8080:8000 inse-app:1.0.0 run
```
The app will be available at `http://localhost:8080/inse-webapp/`.
## Default Users
Defined in `service/src/data/users.json`:
| Username | Password | Role |
|-------------|-------------|-------------|
| superadmin | superadmin | SUPER_ADMIN |
| user | user | UNI_ADMIN |
+4
View File
@@ -0,0 +1,4 @@
ARG IMAGE=inse-service:latest
FROM $IMAGE
COPY [ "build/webapp", "/home/webapp" ]
+13
View File
@@ -0,0 +1,13 @@
# App
Combined Docker image that serves both the service and the webapp.
## Running
```bash
docker run --rm -p 8080:8000 inse-app:1.0.0 run
```
The app will be available at `http://localhost:8080/inse-webapp/`.
Configuration is done via environment variables (prefix `INSE_`). See `service/src/main/inse/config.py` for options.
+23
View File
@@ -0,0 +1,23 @@
plugins {
id 'base'
}
task copyWebapp(type: Copy) {
dependsOn ':webapp:build'
from '../webapp/dist/inse/browser'
into 'build/webapp'
}
task createImage(type: Exec) {
dependsOn ':service:build', copyWebapp
commandLine 'docker', 'build', '--platform', "${targetPlatform}", '--build-arg', "IMAGE=${imagePrefix}-service:${imageVersion}", '-t', "${imagePrefix}-app:${imageVersion}", '.'
}
task run(type: Exec) {
dependsOn createImage
commandLine 'docker', 'run', '--rm', '-e', 'INSE_AUTH_STANDALONE=true', '-p', '8080:8000', "${imagePrefix}-app:${imageVersion}", 'run'
}
build {
dependsOn createImage
}
+6
View File
@@ -0,0 +1,6 @@
ext {
imageName = 'inse'
imagePrefix = 'inse'
imageVersion = '1.0.0'
targetPlatform = 'linux/amd64'
}
+2
View File
@@ -0,0 +1,2 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+249
View File
@@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+23
View File
@@ -0,0 +1,23 @@
FROM python:3.12-slim-bookworm
RUN mkdir /test && \
mkdir /data && \
pip install --root-user-action=ignore --no-cache-dir --upgrade pip && \
pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-check \
"fastapi~=0.115.0" \
"SQLAlchemy~=2.0.0" \
"pyjwt~=2.8.0" \
"pydantic~=2.7.1" \
"pydantic-settings~=2.2.1" \
"PyYAML~=6.0.1" \
"cryptography~=42.0.0" \
"uvicorn~=0.29.0" \
"pytest~=8.1.0" \
"httpx~=0.27.0" \
"python-multipart~=0.0.19"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
EXPOSE 8000/tcp
VOLUME [ "/home", "/mnt", "/data" ]
ENTRYPOINT [ "/home/entrypoint.sh" ]
+17
View File
@@ -0,0 +1,17 @@
# Service
Python REST API using FastAPI, packaged as a Docker container. The build is automated using Gradle.
## Building
To build the container: `./gradlew :service:build`
## Development
To launch the service with hot-reload: `./gradlew :service:serve`
This mounts the source directory into the container and enables uvicorn hot-reloading. Press *ENTER* to stop.
## Testing
Run tests: `./gradlew :service:test`
+51
View File
@@ -0,0 +1,51 @@
plugins {
id 'base'
}
task createImage(type: Exec) {
commandLine 'docker', 'build', '--platform', "${targetPlatform}", '-t', "${imagePrefix}-service:${imageVersion}", '.'
}
task test(type: Exec) {
dependsOn createImage
commandLine 'docker', 'run', '--rm', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '--name', "${imageName}-service-test", "${imagePrefix}-service:${imageVersion}", 'test'
ignoreExitValue false
}
task runServeContainer(type: Exec) {
dependsOn createImage
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
}
task stopServeContainer(type: Exec) {
dependsOn runServeContainer
commandLine 'docker', 'stop', "${imageName}-service-serve"
}
task serve(type: Task) {
dependsOn runServeContainer
finalizedBy stopServeContainer
doLast {
ProcessBuilder processBuilder = new ProcessBuilder('docker', 'logs', '-f', "${imageName}-service-serve")
Process process = processBuilder.start();
Thread redirect = new Thread() {
public void run() {
BufferedReader r = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
while ((line = r.readLine()) != null) {
println(line);
}
}
};
redirect.start();
new Scanner(System.in).nextLine();
process.destroyForcibly();
int exitCode = process.waitFor();
redirect.join();
print("Exit code: " + exitCode);
}
}
build {
dependsOn createImage, test
}
+1
View File
@@ -0,0 +1 @@
*.db
+18
View File
@@ -0,0 +1,18 @@
{
"users": [
{
"account": 0,
"organization": 0,
"username": "superadmin",
"password": "superadmin",
"superadmin": true
},
{
"account": 1,
"organization": 1,
"username": "user",
"password": "user",
"superadmin": false
}
]
}
+4
View File
@@ -0,0 +1,4 @@
__pycache__
.openapi-generator-ignore
.pytest_cache
test.db
@@ -0,0 +1,39 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
docs/**
test/**
.openapi-generator/**
.github/**
.gitignore
.gitlab-ci.yml
git_push.sh
pyproject.toml
README.md
setup.cfg
setup.py
requirements.txt
test-requirements.txt
tox.ini
.travis.yml
account/py.typed
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
cd /home
if [ $# -eq 0 ]; then
uvicorn --host "0.0.0.0" --port "8000" inse.main:app --log-config log-config.yaml
else
if [ "$1" = "run" ]; then
shift
uvicorn --host "0.0.0.0" --port "8000" inse.main:app --log-config log-config.yaml "$@"
elif [ "$1" = "test" ]; then
shift
pytest "$@"
else
echo "Usage: entrypoint.sh [run|test] <parameters>"
echo
echo "run: Runs the app in a uvicorn web server."
echo "test: Runs tests using pytest."
fi
fi
View File
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the validation logic for
user names and passwords.
"""
import typing
import logging
from . import model
logger = logging.getLogger(__name__)
def _get_users() -> typing.List[model.User]:
''' Returns the list of users from the user configuration file. '''
try:
with open('../data/users.json') as file:
config = model.UserFile.model_validate_json(file.read())
return config.users
except Exception as e:
logger.error('Could not read user configuration file.', exc_info=e)
return []
def get_user(username: str) -> typing.Optional[model.User]:
''' Returns the user with the given username. '''
for user in _get_users():
if user.username == username:
return user
return None
def validate_user(username: str, password: str) -> typing.Optional[model.User]:
''' Validates the user with the given username and password. '''
user = get_user(username)
if user and user.password == password:
return user
return None
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data models for the standalone account sub-app.
"""
from pydantic import BaseModel
from pydantic import Field
from pydantic import StrictInt
from typing import List, Optional
class User(BaseModel):
''' An entry in the user configuration file. '''
username: str = Field(description="The username of the user.")
password: str = Field(description="The password of the user.")
account: StrictInt = Field(description="The account id of the user.")
organization: StrictInt = Field(description="The organization id of the user.")
superadmin: bool = Field(default=False, description="Indicates whether the user is a superadmin.")
class UserFile(BaseModel):
''' The data model for the file containing the user configuration. '''
users: List[User] = Field(default=[], description="The list of users.")
class AuthAccount(BaseModel):
i: int
l: str
o: int
class AuthScope(BaseModel):
t: str
a: AuthAccount
d: Optional[int] = None
r: List[str] = []
class IdentityGrant(BaseModel):
token_type: str
access_token: str
expires_in: int
scope: AuthScope
class AccessGrant(BaseModel):
token_type: str
access_token: str
expires_in: int
scope: AuthScope
refresh_token: str
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the security-related code.
"""
from typing import Optional
from typing import Dict
from typing import Literal
import jwt
import time
import logging
from .. import config
from .. import security
from . import model
logger = logging.getLogger(__name__)
def principal(id_token: str) -> Optional[security.Principal]:
''' Extracts the principal from the id token. '''
return security._extract_principal(id_token, config.settings.auth_secret, 'HS256', token_types=['ID', 'REFRESH'])
def id_token(user: model.User, exp: int) -> str:
''' Creates a new identity token for the specified user. '''
return _encode(_payload(user, 'ID', exp))
def access_token(user: model.User, exp: int) -> str:
''' Creates a new access token for the specified user. '''
return _encode(_payload(user, 'ACCESS', exp))
def refresh_token(user: model.User, exp: int) -> str:
''' Creates a new refresh token for the specified user. '''
return _encode(_payload(user, 'REFRESH', exp))
def _encode(payload: Dict[str, any]) -> str:
''' Creates a valid web token that encodes the contents with the symmetric key. '''
headers = {
"kid" : "sym",
}
return jwt.encode(payload, config.settings.auth_secret, algorithm="HS256", headers=headers)
def _payload(user: model.User, type: Literal['ID', 'ACCESS', 'REFRESH'], exp: int) -> str:
''' Creates the payload of the token for the specified user and token type. '''
now = int(time.time())
roles = [ 'SUPER_ADMIN' ] if user.superadmin else [ 'UNI_ADMIN' ]
payload = {
"iss" : "my-app",
"exp" : now + exp,
"iat" : now,
"nbf" : now,
"digitallpro" : {
"t" : type,
"a" : {
"i" : user.account,
"l" : user.username,
"o" : user.organization
},
"d" : None,
"r" : roles if type == 'ACCESS' else []
}
}
return payload
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Standalone account service that provides identity and access
token endpoints for authentication.
"""
import logging
import fastapi
import typing
from . import logic
from . import model
from . import security
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_403_FORBIDDEN
from starlette.status import HTTP_200_OK
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
logger = logging.getLogger(__name__)
app = fastapi.FastAPI(docs_url='/api',
title='My App Account Service',
version='1.0.0')
@app.post('/auth/id', responses={
HTTP_200_OK: {'model': model.IdentityGrant},
HTTP_400_BAD_REQUEST: {'model': None, 'description': 'Invalid request parameters.'},
HTTP_403_FORBIDDEN: {'model': None, 'description': 'Account login not successful.'},
HTTP_500_INTERNAL_SERVER_ERROR: {'model': None, 'description': 'Token generation failed.'}
})
async def get_identity_grant(username: typing.Annotated[str, fastapi.Form()], password: typing.Annotated[str, fastapi.Form()]):
user = logic.validate_user(username, password)
if user is None:
logger.info('Invalid login attempt (%s).', username)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
try:
exp = 12 * 60 * 60
token = security.id_token(user, exp=exp)
account = model.AuthAccount(i=user.account, l=user.username, o=user.organization)
scope = model.AuthScope(t='ID', a=account, d=None, r=[])
grant = model.IdentityGrant(token_type='bearer', access_token=token, expires_in=exp, scope=scope)
logger.info('Identity token generated (%s).', username)
return grant
except Exception as e:
logger.error('Token generation failed (%s).', username, exc_info=e)
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
@app.post('/auth/access', responses={
HTTP_200_OK: {'model': model.AccessGrant},
HTTP_400_BAD_REQUEST: {'model': None, 'description': 'Invalid request parameters.'},
HTTP_403_FORBIDDEN: {'model': None, 'description': 'Access not allowed.'},
HTTP_500_INTERNAL_SERVER_ERROR: {'model': None, 'description': 'Token generation failed.'}
})
async def get_access_grant(secret: typing.Annotated[str, fastapi.Form()], account: typing.Annotated[int, fastapi.Form()], organization: typing.Annotated[int, fastapi.Form()]):
principal = security.principal(secret)
if principal is None:
logger.info('Invalid access attempt without principal (%s).', account)
raise fastapi.HTTPException(status_code=HTTP_400_BAD_REQUEST)
user = logic.get_user(principal.account.login)
if user is None:
logger.info('Invalid access attempt without user (%s).', account)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
if user.organization != organization or user.account != account:
logger.info('Invalid personation attempt (%s).', account)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
try:
exp = 10 * 60
token = security.access_token(user, exp=exp)
refresh = security.refresh_token(user, exp=exp)
auth_account = model.AuthAccount(i=user.account, l=user.username, o=user.organization)
scope = model.AuthScope(t='ACCESS', a=auth_account, d=None, r=['SUPER_ADMIN'] if user.superadmin else ['UNI_ADMIN'])
grant = model.AccessGrant(token_type='bearer', access_token=token, expires_in=exp, scope=scope, refresh_token=refresh)
logger.info('Access token generated (%s).', user.username)
return grant
except Exception as e:
logger.error('Token generation failed (%s).', user.username, exc_info=e)
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the configuration properties
that can be adjusted via environment variables.
"""
import logging
from pydantic_settings import BaseSettings, SettingsConfigDict
logger = logging.getLogger(__name__)
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix='inse_')
# database config
database_url: str = 'sqlite:///../data/inse-sqlite.db'
database_debug: bool = False
database_init: bool = True
# authorization config
auth_disabled: bool = False
auth_standalone: bool = True
auth_secret: str = 'change-me-to-a-secure-secret-key'
settings = Settings()
logger.info(f"Database URL: {settings.database_url}.")
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the code to bootstrap the database
using our schema and sqlalchemy.
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from . import schema
from . import config
engine = create_engine(config.settings.database_url, echo=config.settings.database_debug)
if config.settings.database_init:
schema.Base.metadata.create_all(engine)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get():
''' Returns a database connection and closes it when done. '''
db = SessionLocal()
try:
yield db
finally:
db.close()
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the business logic for our
web service.
"""
from typing import List
from typing import TypeVar
from typing import Optional
from typing import Type
from sqlalchemy.orm import Session
from sqlalchemy import select
from sqlalchemy import delete
from sqlalchemy import insert
from sqlalchemy import update
from sqlalchemy import func
import logging
from . import schema
from . import model
logger = logging.getLogger(__name__)
S = TypeVar('S', bound=schema.Base)
M = TypeVar('M', bound=model.BaseModel)
def filter_none():
return True
def get_page(db: Session, schema_type: Type[S], model_type: Type[M], offset: int, limit: int, filter=filter_none) -> model.Page[M]:
result = model.Page[model_type]()
result.offset = offset
result.total = get_count(db, schema_type, filter)
result.size = limit
if result.total > result.offset:
result.elements = get_elements(db, schema_type, offset, limit, filter)
else:
result.elements = []
return result
def get_count(db: Session, schema_type: Type[S], filter=filter_none) -> int:
return db.scalar(select(func.count()).select_from(schema_type).where(filter))
def get_elements(db: Session, schema_type: Type[S], offset: int, limit: int, filter=filter_none) -> List[S]:
return db.scalars(select(schema_type).where(filter).offset(offset).limit(limit)).all()
def get_element(db: Session, schema_type: Type[S], element_id: int) -> Optional[S]:
return db.scalars(select(schema_type).where(schema_type.id == element_id).limit(1)).first()
def delete_element(db: Session, schema_type: Type[S], element_id: int):
element = get_element(db, schema_type, element_id)
db.delete(element)
def insert_element(db: Session, value: S) -> S:
db.add(value)
db.flush()
db.refresh(value)
return value
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the bootstrapping code
for fastapi that loads the service and the
webapp.
"""
import logging
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from . import config
from . import service
from . import webapp
from .account import service as account
logger = logging.getLogger(__name__)
### startup
app = FastAPI(redoc_url=None, docs_url=None)
app.mount("/inse-service", service.app)
app.mount("/inse-webapp", webapp.app)
app.mount("/inse-account", account.app)
@app.exception_handler(404)
async def redirect(_, __):
return RedirectResponse(url="/inse-webapp/")
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the model classes returned from
our api using pydantic.
"""
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from typing import List
from typing import TypeVar
from typing import Generic
T = TypeVar('T', bound=BaseModel)
class Entity(BaseModel):
id: int = Field(description="The id of the entity.")
class Item(Entity):
model_config = ConfigDict(from_attributes=True)
name: str = Field(description="The name of the item.")
description: str = Field(description="The description of the item.")
class ItemCreate(BaseModel):
name: str = Field(description="The name of the item.")
description: str = Field(description="The description of the item.")
class Page(BaseModel, Generic[T]):
elements: List[T] = Field(default=[], description="The elements of the page.")
offset: int = Field(default=0, description="The page offset in elements.")
total: int = Field(default=0, description="The total number of elements.")
size: int = Field(default=20, description="The page size in elements.")
class ItemPage(Page[Item]):
pass
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the schema for the database
used by the service using sql alchemy.
"""
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
class Base(DeclarativeBase):
''' Base class for all data models. '''
pass
class Item(Base):
''' Data model to represent an item. '''
__tablename__ = "item"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(200))
description: Mapped[str] = mapped_column(String(2000))
def __repr__(self) -> str:
return f"Item(id={self.id!r}, name={self.name!r})"
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the security-related code.
"""
from typing import Optional
from typing import List
from typing import Callable
from typing import Literal
from typing import Union
from starlette.status import HTTP_403_FORBIDDEN
from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi.security import HTTPAuthorizationCredentials
from fastapi import HTTPException
from pydantic import BaseModel
from pydantic import Field
from sqlalchemy.orm import Session
import jwt
import logging
from . import config
from . import database
class Account(BaseModel):
id: int = Field(description="The id of the account.")
login: Optional[str] = Field(description="The optional login of the account.")
organization: int = Field(description="The organization id of the account.")
class Principal(BaseModel):
account: Account = Field(description="The account of the principal.")
delegate: Optional[Account] = Field(default=None, description="The optional delegate of the principal.")
roles: List[str] = Field(description="The roles of the principal.")
logger = logging.getLogger(__name__)
bearer = HTTPBearer(bearerFormat="JWT", scheme_name="bearer", description="JSON Web Token provided via bearer authorization.", auto_error=False)
def principal(credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), db: Session = Depends(database.get)) -> Optional[Principal]:
if config.settings.auth_disabled:
account = Account(id=0, login="AUTH_DISABLED", organization=0)
return Principal(account=account, delegate=None, roles=[ 'SUPER_ADMIN' ])
if credentials is None or credentials.credentials is None:
return None
return _extract_principal(credentials.credentials, config.settings.auth_secret, 'HS256')
def _extract_principal(token: str, secret_key, algorithm: Literal['RS256', 'HS256'], token_types: List[Literal['ID', 'ACCESS', 'REFRESH']] = [ 'ACCESS' ]) -> Optional[Principal]:
try:
content = jwt.decode(token, secret_key, verify=True, issuer="my-app", algorithms=[ algorithm ], options={"require": [ "iss", "iat", "nbf", "exp", "digitallpro"]})
except jwt.exceptions.ExpiredSignatureError as e:
logger.info(f'Received expired token, ignoring content ({e}).')
return None
except Exception as e:
logger.info(f'Received invalid token content, ignoring content ({e}).')
return None
scope = content.get("digitallpro")
if scope is None:
return None
token_type = scope.get('t')
if token_type not in token_types:
logger.info(f'Received invalid token type, ignoring content (Type was {token_type})')
return None
a = scope.get('a', {})
account = Account(id=a.get('i', 0), login=a.get('l'), organization=a.get('o', 0))
delegate = None
d = scope.get('d')
if d is not None:
delegate = Account(id=d.get('i', 0), login=d.get('l'), organization=d.get('o', 0))
return Principal(account=account, delegate=delegate, roles=scope.get('r', []))
def roles_allowed(roles: List[str]|str) -> Callable[[Optional[Principal]], Principal]:
if isinstance(roles, str):
roles = [roles]
if len(roles) < 1:
raise ValueError("Must specify at least one role in roles_allowed.")
def verify_roles(principal: Optional[Principal] = Depends(principal)) -> Principal:
if principal is None:
logger.info("Rejecting call due to missing principal.")
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
for role in roles:
if role in principal.roles:
return principal
logger.info("Rejecting call due to missing roles.")
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
return verify_roles
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the rest api of the
service.
"""
import logging
from typing import Annotated
from fastapi import FastAPI
from fastapi import Depends
from fastapi import Path
from fastapi import Query
from fastapi import Body
from fastapi import Response
from fastapi.responses import RedirectResponse
from starlette.status import HTTP_404_NOT_FOUND
from starlette.status import HTTP_200_OK
from sqlalchemy.orm import Session
from . import model
from . import logic
from . import schema
from . import database
from . import security
from . import util
logger = logging.getLogger(__name__)
### startup
app = FastAPI(redoc_url=None,
docs_url='/api',
title='My App Service',
summary='My App Service API',
version='1.0.0')
@app.get("/", include_in_schema=False)
async def show_api():
return RedirectResponse("api")
### items
@app.get('/items',
operation_id='getItems',
response_model=model.ItemPage,
summary='Returns a page of items.',
tags=[ 'Items' ])
def get_items(page_offset: Annotated[int, Query(alias='pageOffset', description='The page offset.', ge=0)] = 0,
page_size: Annotated[int, Query(alias='pageSize', description='The page size.', ge=0, le=1000)] = 100,
db: Session = Depends(database.get),
principal: security.Principal = Depends(security.roles_allowed(['SUPER_ADMIN', 'UNI_ADMIN']))):
return logic.get_page(db, schema.Item, model.Item, page_offset, page_size)
@app.get('/items/{id}',
operation_id='getItem',
response_model=model.Item,
summary='Returns the item with the id.',
responses={ HTTP_404_NOT_FOUND: { 'model' : None }},
tags=[ 'Items' ])
def get_item(id: Annotated[int, Path(description='The item id.', ge=0)],
db: Session = Depends(database.get),
principal: security.Principal = Depends(security.roles_allowed(['SUPER_ADMIN', 'UNI_ADMIN']))):
return util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
@app.post('/items',
operation_id='addItem',
response_model=model.Item,
summary='Adds a new item.',
tags=[ 'Items' ])
def add_item(item: Annotated[model.ItemCreate, Body(description='The item to add.')],
db: Session = Depends(database.get),
principal: security.Principal = Depends(security.roles_allowed(['SUPER_ADMIN', 'UNI_ADMIN']))):
i = schema.Item()
i.name = item.name
i.description = item.description
try:
return logic.insert_element(db, i)
finally:
db.commit()
@app.put('/items/{id}',
operation_id='updateItem',
response_model=model.Item,
summary='Updates the item with the id.',
responses={ HTTP_404_NOT_FOUND: { 'model' : None }},
tags=[ 'Items' ])
def update_item(id: Annotated[int, Path(description='The item id.', ge=0)],
item: Annotated[model.ItemCreate, Body(description='The item data to update.')],
db: Session = Depends(database.get),
principal: security.Principal = Depends(security.roles_allowed(['SUPER_ADMIN', 'UNI_ADMIN']))):
i = util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
i.name = item.name
i.description = item.description
db.flush()
db.refresh(i)
try:
return i
finally:
db.commit()
@app.delete('/items/{id}',
operation_id='deleteItem',
summary='Deletes the item with the id.',
response_model=None,
responses={ HTTP_404_NOT_FOUND: { 'model' : None }},
tags=[ 'Items' ])
def delete_item(id: Annotated[int, Path(description='The item id.', ge=0)],
db: Session = Depends(database.get),
principal: security.Principal = Depends(security.roles_allowed(['SUPER_ADMIN', 'UNI_ADMIN']))):
util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
try:
logic.delete_element(db, schema.Item, id)
return Response(status_code=HTTP_200_OK)
finally:
db.commit()
+9
View File
@@ -0,0 +1,9 @@
from fastapi.testclient import TestClient
from inse.main import app
client = TestClient(app)
def test_redirect_root():
response = client.get("/", follow_redirects=False)
assert response.status_code == 307
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains utility functions
for the service implementation.
"""
from typing import Optional
from typing import TypeVar
from fastapi import HTTPException
from starlette.status import HTTP_404_NOT_FOUND
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
raise HTTPException(HTTP_404_NOT_FOUND)
else:
return value
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains a fastapi module that
serves the webapp.
"""
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
### startup
app = FastAPI(redoc_url=None, docs_url=None)
app.mount("/", StaticFiles(directory="webapp"))
@app.exception_handler(404)
async def redirect(_, __):
return FileResponse('webapp/index.html')
+39
View File
@@ -0,0 +1,39 @@
version: 1
disable_existing_loggers: False
formatters:
default:
# "()": uvicorn.logging.DefaultFormatter
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
access:
# "()": uvicorn.logging.AccessFormatter
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
default:
formatter: default
class: logging.StreamHandler
stream: ext://sys.stderr
access:
formatter: access
class: logging.StreamHandler
stream: ext://sys.stdout
loggers:
uvicorn.error:
level: INFO
handlers:
- default
propagate: no
uvicorn.access:
level: INFO
handlers:
- access
propagate: no
sqlalchemy.engine.Engine:
level: INFO
handlers:
- default
propagate: no
root:
level: DEBUG
handlers:
- default
propagate: no
+9
View File
@@ -0,0 +1,9 @@
<html>
<head>
<title>INSE Webapp</title>
</head>
<body>
<h1>INSE Webapp</h1>
<p>This page is a stub for the webapp that will be replaced.</p>
</body>
</html>
+4
View File
@@ -0,0 +1,4 @@
rootProject.name = 'inse'
include(':service')
include(':webapp')
include(':app')
+16
View File
@@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false
+45
View File
@@ -0,0 +1,45 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db
# Generated clients
src/api/
+11
View File
@@ -0,0 +1,11 @@
# Webapp
Angular 18 single-page application with Angular Material.
## Development
Run `npm start` for a dev server at `http://localhost:4200/`. The application will automatically reload on file changes.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
+110
View File
@@ -0,0 +1,110 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"inse": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"baseHref":"/inse-webapp/",
"outputPath": "dist/inse",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "1500kb",
"maximumError": "2mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "5kb",
"maximumError": "10kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"proxyConfig": "src/proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "inse:build:production"
},
"development": {
"buildTarget": "inse:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "inse:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
}
}
}
}
},
"cli": {
"analytics": false
}
}
+36
View File
@@ -0,0 +1,36 @@
plugins {
id "base"
id "com.github.node-gradle.node" version "7.0.2"
}
node {
download = true
version = "20.15.1"
npmVersion = "10.7.0"
}
task cleanNgBuild(type: Delete) {
delete files("${projectDir}/dist/inse")
}
task ngBuild(type: NodeTask) {
dependsOn 'npmInstall', cleanNgBuild
script = file('node_modules/@angular/cli/bin/ng.js')
args = ['build', '--configuration', 'production', '--source-map=false', '--base-href', '/inse-webapp/']
}
task serve(type: NodeTask) {
dependsOn 'npmInstall'
script = file('node_modules/@angular/cli/bin/ng.js')
args = ['serve', '--configuration', 'development', '--proxy-config', 'src/proxy.conf.json', '--open']
workingDir = projectDir
}
build {
dependsOn ngBuild
}
clean {
dependsOn cleanNgBuild
}
+13970
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
{
"name": "inse",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^18.0.1",
"@angular/cdk": "^18.0.1",
"@angular/common": "^18.0.1",
"@angular/compiler": "^18.0.1",
"@angular/core": "^18.0.1",
"@angular/forms": "^18.0.1",
"@angular/material": "^18.0.1",
"@angular/platform-browser": "^18.0.1",
"@angular/platform-browser-dynamic": "^18.0.1",
"@angular/router": "^18.0.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.0.2",
"@angular/cli": "^18.0.2",
"@angular/compiler-cli": "^18.0.1",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}
}
@@ -0,0 +1,40 @@
<div style="display: flex; flex-direction: column; height: 100svh; overflow: hidden;">
<mat-toolbar class="main">
<div>
<ng-content select="[indicator]"></ng-content>
</div>
<div style="flex: 1;" class="menu">
@if(mediaQuery.matches && (credentialService.authenticated | async)) {
<button mat-icon-button (click)="toggle()"><mat-icon>menu</mat-icon></button>
}
@else {
<a href="/inse-webapp/" style="color: white; text-decoration: none; font-weight: 600; font-size: 18px; letter-spacing: 0.03em;">My App</a>
}
</div>
<div style="display: flex; flex-direction: row;" class="menu">
<ng-content select="[menu]"></ng-content>
@if(credentialService.authenticated | async) {
<button mat-icon-button (click)="logout()" matTooltip="Abmelden"><mat-icon>logout</mat-icon></button>
}
@else {
<button mat-icon-button routerLink="/login" matTooltip="Anmelden"><mat-icon>login</mat-icon></button>
}
</div>
</mat-toolbar>
<div class="container">
<mat-drawer-container style="width: 100%; height: 100%;">
@if((credentialService.authenticated | async) && ((credentialService.superadmin | async) || (credentialService.universityadmin | async))) {
<mat-drawer class="drawer" #drawer [mode]="mediaQuery.matches ? 'over' : 'side'" [(opened)]="sideNavOpen">
<app-menu></app-menu>
</mat-drawer>
}
<mat-drawer-content>
<ng-content></ng-content>
</mat-drawer-content>
</mat-drawer-container>
</div>
<div class="footer-container" >
<div class="footer large">&copy; 2024 My App</div>
<div class="footer small">&copy; 2024 My App</div>
</div>
</div>
@@ -0,0 +1,69 @@
@use '@angular/material' as mat;
@import '../../m3-theme.scss';
.footer, .footer a {
font-size: 12px;
color: rgba(255, 255, 255, 0.85);
text-decoration: none;
letter-spacing: 0.02em;
}
.large {
display: block;
}
.small {
display: none;
}
.container {
height: calc(100svh - 84px);
overflow: auto;
background-color: #f4f6fb;
}
mat-toolbar.main {
background: linear-gradient(135deg, #1a3a6e 0%, #2259a8 60%, #4072c2 100%);
color: white;
@include mat.elevation(4);
z-index: 10;
}
.drawer {
width: 230px;
@include mat.elevation(3);
border-right: 1px solid rgba(0,0,0,0.06);
}
.footer-container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
height: 28px;
background: linear-gradient(135deg, #1a3a6e 0%, #2259a8 100%);
}
@media (prefers-color-scheme: dark) {
.container {
background-color: #1b1b1f;
}
mat-toolbar.main {
background: linear-gradient(135deg, #001849 0%, #002d6e 60%, #004290 100%);
}
.footer-container {
background: linear-gradient(135deg, #001849 0%, #002d6e 100%);
}
}
@media (max-width: 600px) {
.large {
display: none;
}
.small {
display: block;
}
.container {
height: calc(100svh - 76px);
}
}
@@ -0,0 +1,60 @@
import { ChangeDetectorRef, Component, Input, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatDrawer, MatSidenavModule } from '@angular/material/sidenav';
import { Router, RouterLink } from '@angular/router';
import { MediaMatcher } from '@angular/cdk/layout';
import { AppMenuComponent } from '../app-menu/app-menu.component';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CredentialService } from '../services/credential.service';
@Component({
selector: 'app-layout',
standalone: true,
imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, RouterLink, AppMenuComponent, MatTooltipModule],
templateUrl: './app-layout.component.html',
styleUrl: './app-layout.component.scss'
})
export class AppLayoutComponent implements OnInit, OnDestroy {
@ViewChild(MatDrawer, { static: false })
drawer?: MatDrawer;
mediaQuery: MediaQueryList;
mediaQueryListener: () => void;
sideNavOpen = false;
constructor(public credentialService: CredentialService, public router: Router,
public changeDetector: ChangeDetectorRef, media: MediaMatcher) {
this.mediaQuery = media.matchMedia('(max-width: 600px)');
this.mediaQueryListener = () => {
this.sideNavOpen = !this.mediaQuery.matches
changeDetector.detectChanges();
}
}
toggle() {
if (this.drawer) {
this.drawer.toggle();
}
}
ngOnInit() {
this.sideNavOpen = !this.mediaQuery.matches;
this.mediaQuery.addEventListener('change', this.mediaQueryListener);
}
ngOnDestroy(): void {
this.mediaQuery.removeEventListener('change', this.mediaQueryListener);
}
logout() {
this.credentialService.logoutAcount();
this.router.navigate(['/'])
}
}
@@ -0,0 +1,46 @@
<div class="container">
<form class="form" [formGroup]="loginForm">
<h3>Anmeldung</h3>
<p class="field">Um auf den Dienst zuzugreifen, musst Du Deine Anmeldedaten eingeben.</p>
<mat-form-field class="field">
<mat-label>Login</mat-label>
<input id="dp-login" matInput formControlName="login">
@if (loginForm.controls.login.hasError('required')) {
<mat-error>Fehler: <b>Login</b> erforderlich.</mat-error>
} @else if (loginForm.controls.login.hasError('minlength')) {
<mat-error>Fehler: <b>Login</b> ist unvollständig.</mat-error>
}
</mat-form-field>
<mat-form-field class="field">
<mat-label>Passwort</mat-label>
<input id="dp-password" matInput [type]="showPassword ? 'text':'password'" formControlName="password">
@if (showPassword) {
<mat-icon matSuffix (click)="showPassword = false">visibility</mat-icon>
} @else {
<mat-icon matSuffix (click)="showPassword = true">visibility_off</mat-icon>
}
@if (loginForm.controls.password.hasError('required')) {
<mat-error>Fehler: <b>Passwort</b> erforderlich.</mat-error>
} @else if (loginForm.controls.password.hasError('minlength')) {
<mat-error>Fehler: <b>Passwort</b> ist unvollständig.</mat-error>
}
</mat-form-field>
<button mat-raised-button class="button" (click)="login()" [disabled]="!loginForm.valid || (credentialService.validating | async)">
Anmelden
</button>
</form>
<p class="progress">
@if (credentialService.validating | async) {
<span><i>Anmeldung läuft,</i> bitte warte einen Moment.</span>
}
@else {
@if ((credentialService.authenticated | async) && !(credentialService.superadmin | async) && !(credentialService.universityadmin | async)) {
<span class="error">Fehler: <b>{{ credentialService.login.value }}</b> ist nicht berechtigt.</span>
}
}
</p>
</div>
@@ -0,0 +1,69 @@
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: linear-gradient(160deg, #f4f6fb 0%, #e8ecf7 100%);
}
.form {
display: flex;
flex-direction: column;
align-items: center;
background: white;
border: none;
border-radius: 12px;
box-shadow: 0 2px 12px rgba(26, 58, 110, 0.10), 0 1px 4px rgba(0,0,0,0.06);
gap: 20px;
padding: 36px 32px 28px;
}
.form h3 {
margin: 0 0 4px;
font-weight: 600;
color: #1a3a6e;
}
.button {
min-height: 48px;
min-width: 140px;
border-radius: 8px;
font-weight: 500;
letter-spacing: 0.02em;
}
.field {
width: 300px;
}
.progress {
padding-top: 5px;
width: 300px;
height: 2em;
text-align: center;
font-size: small;
color: #585f71;
}
.error {
color: #ba1a1a;
}
@media (prefers-color-scheme: dark) {
.container {
background: linear-gradient(160deg, #1b1b1f 0%, #252530 100%);
}
.form {
background: #303034;
box-shadow: 0 2px 12px rgba(0,0,0,0.3);
}
.form h3 {
color: #a4c4ff;
}
.progress {
color: #c1c8dc;
}
}
@@ -0,0 +1,68 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { CredentialService } from '../services/credential.service';
import { MatIconModule } from '@angular/material/icon';
import { CommonModule } from '@angular/common';
import { Subscription } from 'rxjs';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
@Component({
selector: 'app-app-login',
standalone: true,
imports: [ CommonModule, ReactiveFormsModule, MatFormFieldModule, MatInputModule, MatButtonModule, MatIconModule, MatSnackBarModule ],
templateUrl: './app-login.component.html',
styleUrl: './app-login.component.scss'
})
export class AppLoginComponent implements OnInit, OnDestroy {
loginForm = new FormGroup({
login: new FormControl<string>('', [ Validators.required, Validators.minLength(4) ]),
password: new FormControl<string>('', [ Validators.required, Validators.minLength(4) ])
});
showPassword = false;
subscription?: Subscription;
constructor(protected credentialService: CredentialService, protected router: Router, protected snackBar: MatSnackBar) { }
ngOnInit(): void {
this.subscription = this.credentialService.validating.subscribe((validating) => {
if (validating) {
this.loginForm.disable();
} else {
this.loginForm.enable();
this.checkEnter();
}
});
if (!this.credentialService.validating) {
this.checkEnter();
}
}
checkEnter(): void {
if (this.credentialService.authenticated.value) {
this.router.navigate(['/items']);
}
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
this.subscription = undefined;
}
}
login() {
let user = this.loginForm.controls.login.value;
let pass = this.loginForm.controls.password.value;
if (user && pass) {
this.credentialService.loginAccount(user, pass);
}
}
}
@@ -0,0 +1,7 @@
<mat-nav-list style="width: 199px; padding: 10px;">
<div matSubheader>Navigation</div>
<mat-list-item routerLink="/items" routerLinkActive="active">
<mat-icon matListItemIcon>list</mat-icon>
<div matListItemTitle>Elemente</div>
</mat-list-item>
</mat-nav-list>
@@ -0,0 +1,13 @@
@use '@angular/material' as mat;
@import '../../m3-theme.scss';
.active {
background-color: mat.get-theme-color($light-theme, primary-container);
border-radius: 8px;
}
@media (prefers-color-scheme: dark) {
.active {
background-color: mat.get-theme-color($dark-theme, primary-container);
}
}
@@ -0,0 +1,19 @@
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { CredentialService } from '../services/credential.service';
@Component({
selector: 'app-menu',
standalone: true,
imports: [ CommonModule, RouterLink, MatIconModule, MatListModule, RouterLinkActive ],
templateUrl: './app-menu.component.html',
styleUrl: './app-menu.component.scss'
})
export class AppMenuComponent {
constructor(public credentialService: CredentialService) { }
}
+3
View File
@@ -0,0 +1,3 @@
<app-layout>
<router-outlet></router-outlet>
</app-layout>
+35
View File
@@ -0,0 +1,35 @@
@use '@angular/material' as mat;
@use '../m3-theme' as m3;
mat-toolbar {
background-color: mat.get-theme-color(m3.$light-theme, primary);
@include mat.elevation(6);
z-index: 10;
}
mat-toolbar button, mat-toolbar span {
color: mat.get-theme-color(m3.$dark-theme, on-background);
}
.main-body {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.card-container {
margin-top: 20px;
display: flex;
}
.card {
width: 300px;
margin-right: 20px;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
+14
View File
@@ -0,0 +1,14 @@
import { Component} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { AppLayoutComponent } from './app-layout/app-layout.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, AppLayoutComponent ],
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
}
+29
View File
@@ -0,0 +1,29 @@
import { ApplicationConfig, LOCALE_ID } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import locale from '@angular/common/locales/de';
import { registerLocaleData } from '@angular/common';
import { authenticationInterceptor } from './interceptors/authentication.interceptor';
import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field';
import { MatPaginatorIntl } from '@angular/material/paginator';
import { PaginatorIntl } from './utils/paginatorIntl';
registerLocaleData(locale);
export const appConfig: ApplicationConfig = {
providers: [
{ provide: LOCALE_ID, useValue: 'de' },
{ provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {appearance: 'outline'}},
{ provide: MatPaginatorIntl, useClass: PaginatorIntl },
provideRouter(routes),
provideHttpClient(withInterceptors([authenticationInterceptor])),
provideAnimationsAsync(),
]
};
+18
View File
@@ -0,0 +1,18 @@
import { Routes } from '@angular/router';
import { userGuard } from './guards/user.guard';
export const routes: Routes = [
{
path: 'login',
loadComponent: () => import('./app-login/app-login.component').then(mod => mod.AppLoginComponent),
},
{
path: 'items',
canActivate: [ userGuard ],
loadComponent: () => import('./list-item/list-item.component').then(mod => mod.ListItemComponent),
},
{
path: '**',
redirectTo: 'login'
}
];
@@ -0,0 +1,6 @@
<h3 mat-dialog-title>Daten löschen</h3>
<mat-dialog-content>Bist Du sicher, dass Du die Daten löschen möchtest? Diesen Vorgang kannst Du nicht mehr rückgängig machen.</mat-dialog-content>
<mat-dialog-actions class="action">
<button mat-flat-button class="secondary-button" (click)="onCancelClick()">Abbrechen</button>
<button mat-flat-button class="primary-button" (click)="onConfirmClick()">Löschen</button>
</mat-dialog-actions>
@@ -0,0 +1,6 @@
.action {
button {
min-width: 150px;
}
}
@@ -0,0 +1,33 @@
import { Component, EventEmitter } from '@angular/core';
import {
MatDialogRef,
MatDialogActions,
MatDialogClose,
MatDialogTitle,
MatDialogContent,
} from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
@Component({
selector: 'app-confirmation-dialog',
standalone: true,
imports: [MatDialogActions, MatDialogClose, MatDialogContent, MatDialogTitle, MatButtonModule],
templateUrl: './confirmation-dialog.component.html',
styleUrl: './confirmation-dialog.component.scss'
})
export class ConfirmationDialogComponent {
confirmDelete = new EventEmitter<void>();
constructor(public dialogRef: MatDialogRef<ConfirmationDialogComponent>) { }
onCancelClick(): void {
this.dialogRef.close();
}
onConfirmClick(): void {
this.confirmDelete.emit();
this.dialogRef.close();
}
}
+23
View File
@@ -0,0 +1,23 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { CredentialService } from '../services/credential.service';
import { Observable, of, switchMap, takeWhile } from 'rxjs';
export const adminGuard: CanActivateFn = (route, state) => {
let credentialService = inject(CredentialService);
let router = inject(Router);
return new Observable(subscriber => {
credentialService.validating.pipe(takeWhile(validating => validating)).subscribe({
complete: () => {
if (!credentialService.superadmin.value) {
router.navigate(['/login']);
return subscriber.next(false);
} else {
return subscriber.next(true);
}
}
});
});
}
+21
View File
@@ -0,0 +1,21 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { CredentialService } from '../services/credential.service';
import { Observable, of, switchMap, takeWhile } from 'rxjs';
export const userGuard: CanActivateFn = (route, state) => {
let credentialService = inject(CredentialService);
let router = inject(Router);
return new Observable(subscriber => {
credentialService.validating.pipe(takeWhile(validating => validating)).subscribe({
complete: () => {
if (!credentialService.superadmin.value && !credentialService.universityadmin.value) {
router.navigate(['/login']);
return subscriber.next(false);
} else {
return subscriber.next(true);
}
}
});
});
};
@@ -0,0 +1,22 @@
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { CredentialService } from '../services/credential.service';
import { switchMap, throwError } from 'rxjs';
export const authenticationInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method == 'POST' && (req.url.endsWith('/auth/id') || req.url.endsWith('/auth/access'))) {
return next(req);
} else {
const credentialService = inject(CredentialService);
const tokenProvider = credentialService.getBearerToken();
return tokenProvider.pipe(
switchMap(response => {
if (response == undefined) {
return throwError(() => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }));
} else {
return next(req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + response)}));
}
}),
);
}
};
@@ -0,0 +1,58 @@
<div class="page">
<div class="form-section">
<h3>{{ editing ? 'Element bearbeiten' : 'Neues Element' }}</h3>
<form [formGroup]="itemForm" class="item-form">
<mat-form-field>
<mat-label>Name</mat-label>
<input matInput formControlName="name">
</mat-form-field>
<mat-form-field>
<mat-label>Beschreibung</mat-label>
<input matInput formControlName="description">
</mat-form-field>
<div class="form-actions">
<button mat-flat-button class="primary-button" (click)="save()" [disabled]="!itemForm.valid">
{{ editing ? 'Speichern' : 'Erstellen' }}
</button>
@if (editing) {
<button mat-flat-button class="secondary-button" (click)="cancelEdit()">Abbrechen</button>
}
</div>
</form>
</div>
<table mat-table [dataSource]="items" class="mat-elevation-z2">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef>ID</th>
<td mat-cell *matCellDef="let item">{{ item.id }}</td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let item">{{ item.name }}</td>
</ng-container>
<ng-container matColumnDef="description">
<th mat-header-cell *matHeaderCellDef>Beschreibung</th>
<td mat-cell *matCellDef="let item">{{ item.description }}</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let item">
<button mat-icon-button (click)="startEdit(item)" matTooltip="Bearbeiten">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button (click)="delete(item)" matTooltip="Löschen">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator
[length]="total"
[pageSize]="paginationService.selection"
[pageSizeOptions]="paginationService.options"
(page)="onPage($event)">
</mat-paginator>
</div>
@@ -0,0 +1,73 @@
.page {
padding: 28px 32px;
max-width: 960px;
margin: 0 auto;
}
.form-section {
margin-bottom: 24px;
background: white;
border-radius: 12px;
padding: 24px;
box-shadow: 0 1px 6px rgba(26, 58, 110, 0.08);
}
.form-section h3 {
margin: 0 0 16px;
font-weight: 600;
color: #1a3a6e;
}
.item-form {
display: flex;
flex-direction: row;
align-items: baseline;
gap: 12px;
flex-wrap: wrap;
}
.form-actions {
display: flex;
gap: 8px;
}
.form-actions button {
border-radius: 8px;
}
table {
width: 100%;
border-radius: 12px;
overflow: hidden;
}
::ng-deep .mat-mdc-header-row {
background-color: #eaf0ff;
}
mat-paginator {
margin-top: 8px;
border-radius: 0 0 12px 12px;
}
@media (prefers-color-scheme: dark) {
.form-section {
background: #303034;
box-shadow: 0 1px 6px rgba(0,0,0,0.2);
}
.form-section h3 {
color: #a4c4ff;
}
::ng-deep .mat-mdc-header-row {
background-color: #1b1b22;
}
}
@media (max-width: 600px) {
.page {
padding: 16px;
}
.item-form {
flex-direction: column;
}
}
@@ -0,0 +1,109 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatTableModule } from '@angular/material/table';
import { MatPaginator, MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { ApiService, Item } from '../services/api.service';
import { PaginationService } from '../services/pagination.service';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { createLoadError } from '../utils/errorHandler';
@Component({
selector: 'app-list-item',
standalone: true,
imports: [
CommonModule, MatTableModule, MatPaginatorModule, MatButtonModule,
MatIconModule, MatDialogModule, MatSnackBarModule, MatFormFieldModule,
MatInputModule, ReactiveFormsModule
],
templateUrl: './list-item.component.html',
styleUrl: './list-item.component.scss'
})
export class ListItemComponent implements OnInit {
displayedColumns: string[] = ['id', 'name', 'description', 'actions'];
items: Item[] = [];
total = 0;
editing: Item | null = null;
itemForm = new FormGroup({
name: new FormControl<string>('', [Validators.required, Validators.maxLength(200)]),
description: new FormControl<string>('', [Validators.maxLength(2000)])
});
constructor(
public apiService: ApiService,
public paginationService: PaginationService,
private dialog: MatDialog,
private snackBar: MatSnackBar
) {}
ngOnInit(): void {
this.load();
}
load() {
const offset = 0;
this.apiService.getItems(offset, this.paginationService.selection).subscribe({
next: (page) => {
this.items = page.elements;
this.total = page.total;
},
error: createLoadError(this.snackBar, () => this.load())
});
}
onPage(event: PageEvent) {
this.paginationService.selection = event.pageSize;
const offset = event.pageIndex * event.pageSize;
this.apiService.getItems(offset, event.pageSize).subscribe({
next: (page) => {
this.items = page.elements;
this.total = page.total;
},
error: createLoadError(this.snackBar, () => this.onPage(event))
});
}
startEdit(item: Item) {
this.editing = item;
this.itemForm.patchValue({ name: item.name, description: item.description });
}
cancelEdit() {
this.editing = null;
this.itemForm.reset();
}
save() {
if (!this.itemForm.valid) return;
const data = { name: this.itemForm.value.name!, description: this.itemForm.value.description ?? '' };
if (this.editing) {
this.apiService.updateItem(this.editing.id, data).subscribe({
next: () => { this.cancelEdit(); this.load(); },
error: createLoadError(this.snackBar)
});
} else {
this.apiService.createItem(data).subscribe({
next: () => { this.cancelEdit(); this.load(); },
error: createLoadError(this.snackBar)
});
}
}
delete(item: Item) {
const dialogRef = this.dialog.open(ConfirmationDialogComponent);
dialogRef.componentInstance.confirmDelete.subscribe(() => {
this.apiService.deleteItem(item.id).subscribe({
next: () => this.load(),
error: createLoadError(this.snackBar)
});
});
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'truncate',
standalone: true
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit: number): string {
if (!value) return '';
return value.length > limit ? value.substring(0, limit) + '...' : value;
}
}
+54
View File
@@ -0,0 +1,54 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Item {
id: number;
name: string;
description: string;
}
export interface ItemPage {
elements: Item[];
offset: number;
total: number;
size: number;
}
export interface ItemCreate {
name: string;
description: string;
}
@Injectable({
providedIn: 'root'
})
export class ApiService {
private readonly basePath = '/inse-service';
constructor(private http: HttpClient) {}
getItems(offset: number = 0, size: number = 10): Observable<ItemPage> {
const params = new HttpParams()
.set('offset', offset.toString())
.set('size', size.toString());
return this.http.get<ItemPage>(`${this.basePath}/items`, { params });
}
getItem(id: number): Observable<Item> {
return this.http.get<Item>(`${this.basePath}/items/${id}`);
}
createItem(item: ItemCreate): Observable<Item> {
return this.http.post<Item>(`${this.basePath}/items`, item);
}
updateItem(id: number, item: ItemCreate): Observable<Item> {
return this.http.put<Item>(`${this.basePath}/items/${id}`, item);
}
deleteItem(id: number): Observable<void> {
return this.http.delete<void>(`${this.basePath}/items/${id}`);
}
}
@@ -0,0 +1,182 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, takeWhile } from 'rxjs';
export interface AuthAccount {
i: number;
l: string;
o: number;
}
export interface AuthScope {
t: string;
a: AuthAccount;
d: number | null;
r: string[];
}
export interface IdentityGrant {
token_type: string;
access_token: string;
expires_in: number;
scope: AuthScope;
}
export interface AccessGrant {
token_type: string;
access_token: string;
expires_in: number;
scope: AuthScope;
refresh_token: string;
}
interface TimedIdentityGrant {
grant: IdentityGrant;
expiration: number;
}
interface TimedAccessGrant {
grant: AccessGrant;
expiration: number;
}
@Injectable({
providedIn: 'root'
})
export class CredentialService {
private static readonly KEY_GRANT = "grant";
public readonly validating = new BehaviorSubject<boolean>(false);
public readonly authenticated = new BehaviorSubject<boolean>(false);
public readonly superadmin = new BehaviorSubject<boolean>(false);
public readonly universityadmin = new BehaviorSubject<boolean>(false);
public readonly organization = new BehaviorSubject<number | undefined>(undefined);
public readonly login = new BehaviorSubject<string>("");
private readonly identityToken = new BehaviorSubject<TimedIdentityGrant | undefined>(undefined);
private readonly accessToken = new BehaviorSubject<TimedAccessGrant | undefined>(undefined);
private request = 0;
constructor(private http: HttpClient) {
this.accessToken.subscribe((token) => {
if (token) {
const r = token.grant.scope.r as string[];
this.superadmin.next(r.includes('SUPER_ADMIN'));
this.universityadmin.next(r.includes('UNI_ADMIN'));
this.login.next(token.grant.scope.a?.l ?? '');
} else {
this.superadmin.next(false);
this.universityadmin.next(false);
this.login.next("");
}
});
const data = localStorage.getItem(CredentialService.KEY_GRANT);
const id = data ? JSON.parse(data) as TimedIdentityGrant : undefined;
if (id && id.expiration && id.expiration >= Date.now()) {
this.identityToken.next(id);
this.validating.next(true);
setTimeout(() => this.refreshAccessToken(id), 0);
}
}
public loginAccount(login: string, password: string) {
const request = ++this.request;
const now = Date.now();
this.validating.next(true);
this.authenticated.next(false);
this.organization.next(undefined);
this.superadmin.next(false);
this.universityadmin.next(false);
this.identityToken.next(undefined);
this.accessToken.next(undefined);
const body = new URLSearchParams();
body.set('username', login);
body.set('password', password);
this.http.post<IdentityGrant>('/inse-account/auth/id', body.toString(), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).subscribe({
next: (result) => {
if (this.request != request) return;
const token = { grant: result, expiration: result.expires_in * 1000 + now };
this.identityToken.next(token);
localStorage.setItem(CredentialService.KEY_GRANT, JSON.stringify(token));
this.refreshAccessToken(token);
},
error: () => {
if (this.request != request) return;
this.validating.next(false);
}
});
}
public refreshAccessToken(identityToken: TimedIdentityGrant) {
const request = ++this.request;
const now = Date.now();
this.validating.next(true);
this.accessToken.next(undefined);
const uid = identityToken.grant.scope.a!.i;
const org = identityToken.grant.scope.a!.o;
const body = new URLSearchParams();
body.set('secret', identityToken.grant.access_token);
body.set('account', uid.toString());
body.set('organization', org.toString());
this.http.post<AccessGrant>('/inse-account/auth/access', body.toString(), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).subscribe({
next: (result) => {
if (this.request != request) return;
const token = { grant: result, expiration: result.expires_in * 1000 + now };
this.accessToken.next(token);
this.organization.next(result.scope.a!.o);
this.authenticated.next(true);
this.validating.next(false);
},
error: () => {
if (this.request != request) return;
this.identityToken.next(undefined);
this.organization.next(undefined);
this.authenticated.next(false);
this.superadmin.next(false);
this.universityadmin.next(false);
this.validating.next(false);
}
});
}
public logoutAcount() {
this.request += 1;
localStorage.removeItem(CredentialService.KEY_GRANT);
this.authenticated.next(false);
this.organization.next(undefined);
this.superadmin.next(false);
this.universityadmin.next(false);
this.identityToken.next(undefined);
this.accessToken.next(undefined);
this.validating.next(false);
}
public getBearerToken(): Observable<string | undefined> {
return new Observable<string | undefined>((observer) => {
if (this.validating.value) {
this.validating.pipe(takeWhile((validating) => validating)).subscribe({
complete: () => observer.next(this.accessToken.value ? this.accessToken.value.grant.access_token : undefined)
});
} else if (!this.accessToken.value) {
observer.next(undefined);
} else if (Date.now() < this.accessToken.value.expiration) {
observer.next(this.accessToken.value.grant.access_token);
} else {
this.refreshAccessToken(this.identityToken.value!);
this.validating.pipe(takeWhile((validating) => validating)).subscribe({
complete: () => observer.next(this.accessToken.value ? this.accessToken.value.grant.access_token : undefined)
});
}
});
}
}
@@ -0,0 +1,13 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PaginationService {
public readonly options = [1, 5, 10, 25, 100];
public selection = 10;
constructor() { }
}
+22
View File
@@ -0,0 +1,22 @@
import { HttpErrorResponse } from "@angular/common/http";
import { MatSnackBar } from "@angular/material/snack-bar";
export function createLoadError(snackBar: MatSnackBar, retry: (()=>void)|undefined = undefined, msg: string = 'Beim Laden der Seite ist ein Fehler aufgetreten'): (error: any) => void {
return (error: any) => {
let code = undefined;
if (error instanceof HttpErrorResponse) {
code = error.status;
}
var message = msg;
if (code) {
message += ' (Fehlercode: ' + code + ')';
}
if (retry) {
message += '. Prüfe Deine Internetverbindung und versuche es erneut.';
snackBar.open(message, 'Erneut versuchen').onAction().subscribe(() => retry());
} else {
message += '.';
snackBar.open(message);
}
}
}
+21
View File
@@ -0,0 +1,21 @@
import { Injectable } from "@angular/core";
import { MatPaginatorIntl } from "@angular/material/paginator";
@Injectable()
export class PaginatorIntl extends MatPaginatorIntl {
override itemsPerPageLabel = 'Einträge pro Seite';
override nextPageLabel = 'Nächste Seite';
override previousPageLabel = 'Vorherige Seite';
override getRangeLabel = (page: number, pageSize: number, length: number) => {
if (length === 0 || pageSize === 0) {
return '0 von ' + length;
}
length = Math.max(length, 0);
const startIndex = page * pageSize;
const endIndex = startIndex < length ?
Math.min(startIndex + pageSize, length) :
startIndex + pageSize;
return startIndex + 1 + ' - ' + endIndex + ' von ' + length;
};
}
View File
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>INSE App</title>
<base href="/inse-webapp/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body class="mat-typography mat-app-background">
<app-root></app-root>
</body>
</html>
+169
View File
@@ -0,0 +1,169 @@
// This file was generated by running 'ng generate @angular/material:m3-theme'.
// Proceed with caution if making changes to this file.
@use 'sass:map';
@use '@angular/material' as mat;
// Color palette: Indigo / Slate Blue
$_palettes: (
primary: (
0: #000000,
10: #001849,
20: #002d6e,
25: #00377f,
30: #004290,
35: #0f4d9b,
40: #2259a8,
50: #4072c2,
60: #5c8cde,
70: #7ba7fb,
80: #a4c4ff,
90: #d3e3ff,
95: #eaf0ff,
98: #f8f9ff,
99: #fdfbff,
100: #ffffff,
),
secondary: (
0: #000000,
10: #151c2c,
20: #2a3142,
25: #353c4d,
30: #414759,
35: #4c5365,
40: #585f71,
50: #71788a,
60: #8b92a5,
70: #a5acbf,
80: #c1c8dc,
90: #dde4f8,
95: #ecf0ff,
98: #f8f9ff,
99: #fdfbff,
100: #ffffff,
),
tertiary: (
0: #000000,
10: #251430,
20: #3b2947,
25: #463452,
30: #523f5e,
35: #5e4b6a,
40: #6a5777,
50: #847091,
60: #9e89ac,
70: #b9a3c7,
80: #d5bee3,
90: #f2daff,
95: #fbecff,
98: #fff7ff,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #1b1b1f,
20: #303034,
25: #3b3b3f,
30: #47474b,
35: #535356,
40: #5f5f62,
50: #78787b,
60: #929295,
70: #acacaf,
80: #c8c7cb,
90: #e4e2e6,
95: #f3f0f4,
98: #fbf8fd,
99: #fdfbff,
100: #ffffff,
4: #0e0e11,
6: #131316,
12: #1f1f23,
17: #2a2a2d,
22: #353538,
24: #39393c,
87: #dbd9de,
92: #eae7ec,
94: #efecf1,
96: #f5f2f7,
),
neutral-variant: (
0: #000000,
10: #1b1b22,
20: #303037,
25: #3b3b43,
30: #47464e,
35: #53525a,
40: #5f5e66,
50: #78777f,
60: #92919a,
70: #adaab4,
80: #c8c5d0,
90: #e5e1ec,
95: #f3effa,
98: #fbf8ff,
99: #fefbff,
100: #ffffff,
),
error: (
0: #000000,
10: #410002,
20: #690005,
25: #7e0007,
30: #93000a,
35: #a80710,
40: #ba1a1a,
50: #de3730,
60: #ff5449,
70: #ff897d,
80: #ffb4ab,
90: #ffdad6,
95: #ffedea,
98: #fff8f7,
99: #fffbff,
100: #ffffff,
),
);
$_rest: (
secondary: map.get($_palettes, secondary),
neutral: map.get($_palettes, neutral),
neutral-variant: map.get($_palettes, neutral-variant),
error: map.get($_palettes, error),
);
$_primary: map.merge(map.get($_palettes, primary), $_rest);
$_tertiary: map.merge(map.get($_palettes, tertiary), $_rest);
$_typography: (
brand-family: 'Montserrat',
plain-family: 'Open Sans',
);
$_density: (
scale: 0
);
$light-theme: mat.define-theme((
color: (
theme-type: light,
primary: $_primary,
tertiary: $_tertiary,
use-system-variables: false,
),
typography: $_typography,
density: $_density,
));
$dark-theme: mat.define-theme((
color: (
theme-type: dark,
primary: $_primary,
tertiary: $_tertiary,
use-system-variables: false,
),
typography: $_typography,
density: $_density,
));
+6
View File
@@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
+12
View File
@@ -0,0 +1,12 @@
{
"/inse-service/": {
"target": "http://127.0.0.1:8000",
"secure": false,
"changeOrigin": true
},
"/inse-account/": {
"target": "http://127.0.0.1:8000",
"secure": false,
"changeOrigin": true
}
}
+121
View File
@@ -0,0 +1,121 @@
// Custom Theming for Angular Material
// For more information: https://material.angular.io/guide/theming
@use '@angular/material' as mat;
@use 'm3-theme' as m3;
@include mat.core();
@font-face {
font-display: swap;
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
src: url('assets/fonts/montserrat-v26-latin-regular.woff2') format('woff2');
}
@font-face {
font-display: swap;
font-family: 'Montserrat';
font-style: italic;
font-weight: 400;
src: url('assets/fonts/montserrat-v26-latin-italic.woff2') format('woff2');
}
@font-face {
font-display: swap;
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: url('assets/fonts/open-sans-v40-latin-regular.woff2') format('woff2');
}
@font-face {
font-display: swap;
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
src: url('assets/fonts/open-sans-v40-latin-italic.woff2') format('woff2');
}
@font-face {
font-display: swap;
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url('assets/fonts/material-icons-v142-latin-regular.woff2') format('woff2');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
}
html {
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
height: 100%;
@include mat.all-component-themes(m3.$light-theme);
@include mat.typography-hierarchy(m3.$light-theme);
}
body {
height: 100%;
margin: 0;
}
.primary-button {
@include mat.button-color(m3.$light-theme, $color-variant: primary);
}
.secondary-button {
@include mat.button-color(m3.$light-theme, $color-variant: secondary);
}
.tertiary-button {
@include mat.button-color(m3.$light-theme, $color-variant: tertiary);
}
.primary-icon {
@include mat.icon-color(m3.$light-theme, $color-variant: primary);
}
.secondary-icon {
@include mat.icon-color(m3.$light-theme, $color-variant: secondary);
}
.tertiary-icon {
@include mat.icon-color(m3.$light-theme, $color-variant: tertiary);
}
@media (prefers-color-scheme: dark) {
html {
@include mat.all-component-colors(m3.$dark-theme);
}
.primary-button {
@include mat.button-color(m3.$dark-theme, $color-variant: primary);
}
.secondary-button {
@include mat.button-color(m3.$dark-theme, $color-variant: secondary);
}
.tertiary-button {
@include mat.button-color(m3.$dark-theme, $color-variant: tertiary);
}
.primary-icon {
@include mat.icon-color(m3.$dark-theme, $color-variant: primary);
}
.secondary-icon {
@include mat.icon-color(m3.$dark-theme, $color-variant: secondary);
}
.tertiary-icon {
@include mat.icon-color(m3.$dark-theme, $color-variant: tertiary);
}
}
.menu button {
--mdc-icon-button-disabled-icon-color: rgba(255,255,255,0.35);
--mdc-icon-button-icon-color: #ffffff;
}
+14
View File
@@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}
+32
View File
@@ -0,0 +1,32 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
+14
View File
@@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}