Commit f0d7d0b4 authored by manuel's avatar manuel

added users, extracted jwt secret, protected endpoints

parent 1988488c
......@@ -4,6 +4,7 @@ import network_constants
import requests
import json
from typing import Dict, List
import logging
class TokenStash:
'''
......@@ -82,7 +83,8 @@ def _verify(token:str, roles:List[str]=[]):
token_info = decodeToken(token, roles=roles)
return token_info
except Exception as e:
print("ERROR DURING TOKEN VALIDATION: "+str(e))
LOGGER = logging.getLogger(__name__)
LOGGER.error("Token invalid: "+str(e))
return None
......@@ -90,4 +92,4 @@ def verifyTokenRegular(token, required_scopes):
return _verify(token)
def verifyTokenAdmin(token, required_scopes):
return _verify(token, roles=["a"])
\ No newline at end of file
return _verify(token, roles=["a"])
......@@ -109,6 +109,8 @@ paths:
'400':
description: wrong username or password
post:
security:
- JwtAdmin: []
operationId: "routes.user.add"
tags:
- "User"
......@@ -246,4 +248,4 @@ definitions:
type: "string"
Metadata:
type: "string"
\ No newline at end of file
......@@ -85,4 +85,4 @@ def all():
users = UserService._repository.all()
return str(users)
\ No newline at end of file
return str(users)
......@@ -6,7 +6,6 @@ import jwt
from datetime import datetime, timedelta
from typing import Dict
SIGNING_KEY = "yteNrMy6142WKwp8fKfrHkS5nlFpxtHgOXJh1ZPsOrV_gTcsO9eMY7aB7HUzRbTRO9dmZhCl3FdPtuvMe3K8aBA_wc2MmHRo8IkUIGmvUJGsAxKFClN_6oNW5fEvoeVKiL1krA-qjWbR_em-WksePgPoTsySW7QbKdi4f7cwuyK2_JZ2fQj9hDKlfJ2GzMXkKiWcfyCTr30yC6BviAFeRDD_Bpvg6znsrXr53Tq66hnwDwQ6QU7aHVu-bERblKZTYuvkSxsov6yRMEVWQoiuBITsQtIOcgSWK4Dy3BjSbqoIcKw3WG-s3wx1lTen19QbEu8vJC64e0iGeGDWT6vbtg"
TOKEN_VALIDITY_IN_DAYS = 1
def verifyTokenRegular(token, required_scopes) -> Dict:
......@@ -42,6 +41,12 @@ class TokenService:
user.last_login = str(datetime.now())
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
def generate_token(user: User) -> str:
'''
......@@ -50,6 +55,8 @@ class TokenService:
- created_at
- valid_until
'''
created_at = datetime.now()
valid_until = created_at + timedelta(days=1)
return jwt.encode(
......@@ -58,7 +65,8 @@ class TokenService:
'created_at': str(created_at),
'valid_until': str(valid_until),
},
SIGNING_KEY, algorithm='HS256'
TokenService.read_secret(),
algorithm='HS256'
).decode("utf-8")
@staticmethod
......@@ -80,7 +88,11 @@ class TokenService:
token = token[7:]
try:
payload = jwt.decode(token, SIGNING_KEY, algorithms=['HS256'])
payload = jwt.decode(
token,
TokenService.read_secret(),
algorithms=['HS256']
)
except:
raise ValueError('Invalid JWT token (decoding failed)')
......@@ -98,4 +110,4 @@ class TokenService:
if now <= token_created_at or now >= valid_until:
raise ValueError('Invalid JWT token (token expired)')
return user
\ No newline at end of file
return user
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