Commit f0d7d0b4 authored by manuel's avatar manuel

added users, extracted jwt secret, protected endpoints

parent 1988488c
...@@ -4,6 +4,7 @@ import network_constants ...@@ -4,6 +4,7 @@ import network_constants
import requests import requests
import json import json
from typing import Dict, List from typing import Dict, List
import logging
class TokenStash: class TokenStash:
''' '''
...@@ -82,7 +83,8 @@ def _verify(token:str, roles:List[str]=[]): ...@@ -82,7 +83,8 @@ def _verify(token:str, roles:List[str]=[]):
token_info = decodeToken(token, roles=roles) token_info = decodeToken(token, roles=roles)
return token_info return token_info
except Exception as e: except Exception as e:
print("ERROR DURING TOKEN VALIDATION: "+str(e)) LOGGER = logging.getLogger(__name__)
LOGGER.error("Token invalid: "+str(e))
return None return None
......
...@@ -109,6 +109,8 @@ paths: ...@@ -109,6 +109,8 @@ paths:
'400': '400':
description: wrong username or password description: wrong username or password
post: post:
security:
- JwtAdmin: []
operationId: "routes.user.add" operationId: "routes.user.add"
tags: tags:
- "User" - "User"
......
...@@ -6,7 +6,6 @@ import jwt ...@@ -6,7 +6,6 @@ import jwt
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Dict from typing import Dict
SIGNING_KEY = "yteNrMy6142WKwp8fKfrHkS5nlFpxtHgOXJh1ZPsOrV_gTcsO9eMY7aB7HUzRbTRO9dmZhCl3FdPtuvMe3K8aBA_wc2MmHRo8IkUIGmvUJGsAxKFClN_6oNW5fEvoeVKiL1krA-qjWbR_em-WksePgPoTsySW7QbKdi4f7cwuyK2_JZ2fQj9hDKlfJ2GzMXkKiWcfyCTr30yC6BviAFeRDD_Bpvg6znsrXr53Tq66hnwDwQ6QU7aHVu-bERblKZTYuvkSxsov6yRMEVWQoiuBITsQtIOcgSWK4Dy3BjSbqoIcKw3WG-s3wx1lTen19QbEu8vJC64e0iGeGDWT6vbtg"
TOKEN_VALIDITY_IN_DAYS = 1 TOKEN_VALIDITY_IN_DAYS = 1
def verifyTokenRegular(token, required_scopes) -> Dict: def verifyTokenRegular(token, required_scopes) -> Dict:
...@@ -42,6 +41,12 @@ class TokenService: ...@@ -42,6 +41,12 @@ class TokenService:
user.last_login = str(datetime.now()) user.last_login = str(datetime.now())
UserService.update(user) UserService.update(user)
@staticmethod
def read_secret() -> str:
with open('/srv/articonf/jwt_secret.txt', 'r') as file:
secret = file.read().replace('\n', '')
return secret
@staticmethod @staticmethod
def generate_token(user: User) -> str: def generate_token(user: User) -> str:
''' '''
...@@ -50,6 +55,8 @@ class TokenService: ...@@ -50,6 +55,8 @@ class TokenService:
- created_at - created_at
- valid_until - valid_until
''' '''
created_at = datetime.now() created_at = datetime.now()
valid_until = created_at + timedelta(days=1) valid_until = created_at + timedelta(days=1)
return jwt.encode( return jwt.encode(
...@@ -58,7 +65,8 @@ class TokenService: ...@@ -58,7 +65,8 @@ class TokenService:
'created_at': str(created_at), 'created_at': str(created_at),
'valid_until': str(valid_until), 'valid_until': str(valid_until),
}, },
SIGNING_KEY, algorithm='HS256' TokenService.read_secret(),
algorithm='HS256'
).decode("utf-8") ).decode("utf-8")
@staticmethod @staticmethod
...@@ -80,7 +88,11 @@ class TokenService: ...@@ -80,7 +88,11 @@ class TokenService:
token = token[7:] token = token[7:]
try: try:
payload = jwt.decode(token, SIGNING_KEY, algorithms=['HS256']) payload = jwt.decode(
token,
TokenService.read_secret(),
algorithms=['HS256']
)
except: except:
raise ValueError('Invalid JWT token (decoding failed)') raise ValueError('Invalid JWT token (decoding failed)')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment