This commit is contained in:
Wolfgang Hottgenroth 2021-01-25 21:52:52 +01:00
commit b88dec12d3
Signed by: wn
GPG Key ID: E49AF3B9EF6DD469
9 changed files with 240 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
__pycache__/
ENV

50
Dockerfile Normal file
View File

@ -0,0 +1,50 @@
FROM python:latest
LABEL Maintainer="Wolfgang Hottgenroth wolfgang.hottgenroth@icloud.com"
LABEL ImageName="registry.hottis.de/wolutator/authservice"
ARG APP_DIR="/opt/app"
ARG CONF_DIR="${APP_DIR}/config"
ENV DB_HOST="172.16.10.18"
ENV DB_NAME="hausverwaltung"
ENV DB_USER="hausverwaltung-ui"
ENV DB_PASS="test123"
ENV JWT_ISSUER='de.hottis.hausverwaltung'
ENV JWT_SECRET='streng_geheim'
ENV JWT_LIFETIME_SECONDS=60
ENV JWT_ALGORITHM='HS256'
RUN \
apt update && \
apt install -y libmariadbclient-dev && \
pip3 install mariadb && \
pip3 install dateparser && \
pip3 install connexion && \
pip3 install connexion[swagger-ui] && \
pip3 install uwsgi && \
pip3 install flask-cors && \
pip3 install six && \
pip3 install python-jose[cryptography]
RUN \
mkdir -p ${APP_DIR} && \
mkdir -p ${CONF_DIR} && \
useradd -d ${APP_DIR} -u 1000 user
COPY *.py ${APP_DIR}/
COPY openapi.yaml ${APP_DIR}/
COPY server.ini ${CONF_DIR}/
USER 1000:1000
WORKDIR ${APP_DIR}
VOLUME ${CONF_DIR}
EXPOSE 5000
EXPOSE 9191
CMD [ "uwsgi", "./config/server.ini" ]

11
ENV.tmpl Normal file
View File

@ -0,0 +1,11 @@
# copy to ENV and adjust values
export DB_HOST="172.16.10.18"
export DB_USER="hausverwaltung-ui"
export DB_PASS="test123"
export DB_NAME="hausverwaltung"
export JWT_ISSUER='de.hottis.hausverwaltung'
export JWT_SECRET='streng_geheim'
export JWT_LIFETIME_SECONDS=60
export JWT_ALGORITHM='HS256'

76
auth.py Executable file
View File

@ -0,0 +1,76 @@
import time
import connexion
from jose import JWTError, jwt
import os
import mariadb
JWT_ISSUER = os.environ['JWT_ISSUER']
JWT_SECRET = os.environ['JWT_SECRET']
JWT_LIFETIME_SECONDS = int(os.environ['JWT_LIFETIME_SECONDS'])
JWT_ALGORITHM = os.environ['JWT_ALGORITHM']
DB_USER = os.environ["DB_USER"]
DB_PASS = os.environ["DB_PASS"]
DB_HOST = os.environ["DB_HOST"]
DB_NAME = os.environ["DB_NAME"]
def getUserEntryFromDB(login, password):
conn = None
cur = None
try:
conn = mariadb.connect(user = DB_USER, password = DB_PASS,
host = DB_HOST, database = DB_NAME)
conn.autocommit = False
cur = conn.cursor(dictionary=True)
cur.execute("SELECT id FROM users WHERE login = ? AND password = ?", [login, password])
userEntry = cur.next()
if not userEntry:
raise Exception("No user entry found")
invObj = cur.next()
if invObj:
raise Exception("Too many user entries found")
return userEntry
except mariadb.Error as err:
raise Exception("Error when connecting to database: {}".format(err))
finally:
if cur:
cur.close()
if conn:
conn.rollback()
conn.close()
def getUserEntry(login, password):
return getUserEntryFromDB(login, password)
def generateToken(login, password):
userEntry = getUserEntryFromDB(login, password)
userId = userEntry["id"]
timestamp = int(time.time())
payload = {
"iss": JWT_ISSUER,
"iat": int(timestamp),
"exp": int(timestamp + JWT_LIFETIME_SECONDS),
"sub": str(userId),
}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
def decodeToken(token):
try:
return jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
except JWTError as e:
return "Unauthorized ({})".format(str(e)), 401
def getSecret(user, token_info):
return '''
You are user_id {user} and the secret is 'wbevuec'.
Decoded token claims: {token_info}.
'''.format(user=user, token_info=token_info)

8
build.sh Executable file
View File

@ -0,0 +1,8 @@
#!/bin/bash
IMAGE_NAME="registry.hottis.de/wolutator/authservice"
VERSION=0.0.1
docker build -t ${IMAGE_NAME}:${VERSION} .
docker push ${IMAGE_NAME}:${VERSION}

53
openapi.yaml Normal file
View File

@ -0,0 +1,53 @@
openapi: 3.0.0
info:
title: AuthService
version: "0.1"
paths:
/auth/{login}:
post:
tags: [ "JWT" ]
summary: Return JWT token
operationId: auth.generateToken
parameters:
- name: login
description: Login
in: path
required: true
schema:
type: string
- name: password
description: Password
in: body
required: true
schema:
type: string
responses:
'200':
description: JWT token
content:
'text/plain':
schema:
type: string
/secret:
get:
tags: [ "JWT" ]
summary: Return secret string
operationId: auth.getSecret
responses:
'200':
description: secret response
content:
'text/plain':
schema:
type: string
security:
- jwt: ['secret']
components:
securitySchemes:
jwt:
type: http
scheme: bearer
bearerFormat: JWT
x-bearerInfoFunc: auth.decodeToken

22
run.sh Executable file
View File

@ -0,0 +1,22 @@
#!/bin/bash
. ENV
IMAGE_NAME="registry.hottis.de/hv/hv-service"
VERSION=0.0.1
docker run \
-d \
--rm \
--name "hv-service" \
-p 5000:5000 \
-e DB_HOST=$DB_HOST \
-e DB_USER=$DB_USER \
-e DB_PASS=$DB_PASS \
-e DB_NAME=$DB_NAME \
-e JWT_ISSUER=$JWT_ISSUER \
-e JWT_SECRET=$JWT_SECRET \
-e JWT_LIFETIME_SECONDS=$JWT_LIFETIME_SECONDS \
-e JWT_ALGORITHM=$JWT_ALGORITHM
${IMAGE_NAME}:${VERSION}

6
server.ini Normal file
View File

@ -0,0 +1,6 @@
[uwsgi]
http = :5000
wsgi-file = server.py
processes = 4
stats = :9191

12
server.py Normal file
View File

@ -0,0 +1,12 @@
import connexion
from flask_cors import CORS
# instantiate the webservice
app = connexion.App(__name__)
app.add_api('openapi.yaml')
# CORSify it - otherwise Angular won't accept it
CORS(app.app)
# provide the webservice application to uwsgi
application = app.app