update token validatition

no second thread to validate for token ... only on access it will be validate
This commit is contained in:
Tim Gröger 2019-12-28 11:31:45 +01:00
parent a052add057
commit 5b37e3d15b
5 changed files with 54 additions and 115 deletions

View File

@ -61,22 +61,14 @@ def getLDAPController():
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from .controller.accesTokenController import AccesTokenController
# from flask_login import LoginManager
LOGGER.info("Build APP")
app = Flask(__name__)
CORS(app)
# app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
#db = SQLAlchemy(app)
accesTokenController = AccesTokenController("GERUECHT")
accesTokenController.start()
# login_manager = LoginManager(app)
# login_manager.login_view = 'login'
# login_manager.login_message_category = 'info'

View File

@ -1,7 +1,5 @@
from flask import Blueprint, request, jsonify
from geruecht import BAR, db, ldapController as ldap
from geruecht.routes import verifyAccessToken
from geruecht.model.user import User
from geruecht import BAR, db, ldapController as ldap, accesTokenController
from datetime import datetime
baruser = Blueprint("baruser", __name__)
@ -19,10 +17,10 @@ def _bar():
print(request.headers)
token = request.headers.get("Token")
print(token)
accToken = verifyAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, BAR)
dic = {}
if accToken is not None:
if accToken:
users = db.getAllUser()
for user in users:
geruecht = None
@ -56,9 +54,9 @@ def _baradd():
"""
token = request.headers.get("Token")
print(token)
accToken = verifyAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, BAR)
if accToken is not None:
if accToken:
data = request.get_json()
userID = data['userId']
amount = int(data['amount'])
@ -89,10 +87,10 @@ def _getUsers():
"""
token = request.headers.get("Token")
print(token)
accToken = verifyAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, BAR)
retVal = {}
if accToken is not None:
if accToken:
retVal = ldap.getAllUser()
return jsonify(retVal)
return jsonify({"error": "permission denied"}), 401
@ -101,9 +99,9 @@ def _getUsers():
def _search():
token = request.headers.get("Token")
print(token)
accToken = verifyAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, BAR)
if accToken is not None:
if accToken:
data = request.get_json()
searchString = data['searchString']

View File

@ -1,14 +1,12 @@
from geruecht.model.accessToken import AccessToken
from geruecht.controller import LOGGER
from datetime import datetime
import time
from threading import Thread
from datetime import datetime, timedelta
import hashlib
import logging
from logging.handlers import WatchedFileHandler
from geruecht import Singleton
class AccesTokenController(Thread, metaclass=Singleton):
class AccesTokenController(metaclass=Singleton):
""" Control all createt AccesToken
This Class create, delete, find and manage AccesToken.
@ -19,7 +17,7 @@ class AccesTokenController(Thread, metaclass=Singleton):
"""
instance = None
tokenList = None
lifetime = 60
lifetime = 1800
def __init__(self, arg):
""" Initialize AccessTokenController
@ -39,31 +37,39 @@ class AccesTokenController(Thread, metaclass=Singleton):
self.LOGGER.setLevel(logging.DEBUG)
self.LOGGER.addHandler(logFileHandler)
self.LOGGER.propagate = False
LOGGER.debug("Initialize Threading")
Thread.__init__(self)
self.tokenList = []
def findAccesToken(self, token):
""" Find a Token in current AccessTokens
def validateAccessToken(self, token, group):
""" Verify Accestoken
Iterate throw all availables AccesTokens and retrieve one, if they are the same.
Verify an Accestoken and Group so if the User has permission or not.
Retrieves the accestoken if valid else retrieves False
Args:
token: Token to find
token: Token to verify.
group: Group like 'moneymaster', 'gastro', 'user' or 'bar'
Returns:
An AccessToken if found or None if not found.
An the AccesToken for this given Token or False.
"""
LOGGER.info("Search for Token: {}".format(token))
LOGGER.debug("Iterate through List of current Tokens")
LOGGER.info("Verify AccessToken with token: {} and group: {}".format(token, group))
for accToken in self.tokenList:
LOGGER.debug("Check if AccessToken {} has Token {}".format(accToken, token))
LOGGER.debug("Check is token {} same as in AccessToken {}".format(token, accToken))
if accToken == token:
LOGGER.info("Find AccessToken {} with Token {}".format(accToken, token))
return accToken
LOGGER.info("no AccesToken found with Token {}".format(token))
return None
LOGGER.debug("AccessToken is {}".format(accToken))
endTime = accToken.timestamp + timedelta(seconds=self.lifetime)
now = datetime.now()
LOGGER.debug("Check if AccessToken's Endtime {} is bigger then now {}".format(endTime, now))
if now <= endTime:
LOGGER.debug("Check if AccesToken {} has same group {}".format(accToken, group))
if self.isSameGroup(accToken, group):
accToken.updateTimestamp()
LOGGER.info("Found AccessToken {} with token: {} and group: {}".format(accToken, token, group))
return accToken
else:
LOGGER.debug("AccessToken {} is no longer valid and will removed".format(accToken))
self.tokenList.remove(accToken)
LOGGER.info("Found no valid AccessToken with token: {} and group: {}".format(token, group))
return False
def createAccesToken(self, user):
""" Create an AccessToken
@ -79,7 +85,7 @@ class AccesTokenController(Thread, metaclass=Singleton):
LOGGER.info("Create AccessToken")
now = datetime.ctime(datetime.now())
token = hashlib.md5((now + user.dn).encode('utf-8')).hexdigest()
accToken = AccessToken(user, token)
accToken = AccessToken(user, token, datetime.now())
LOGGER.debug("Add AccessToken {} to current Tokens".format(accToken))
self.tokenList.append(accToken)
LOGGER.info("Finished create AccessToken {} with Token {}".format(accToken, token))
@ -100,26 +106,3 @@ class AccesTokenController(Thread, metaclass=Singleton):
print("controll if", accToken, "hase group", group)
LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, group))
return True if group in accToken.user.group else False
def run(self):
""" Starting Controll-Thread
Verify that the AccesToken are not out of date. If one AccessToken out of date it will be deletet from tokenList.
"""
valid_time=7200
LOGGER.info("Start Thread for verification that the AccessToken are not out of date.")
while True:
self.LOGGER.debug("Name: {}".format(self.getName()))
self.LOGGER.debug("Start to iterate through List of current Tokens")
for accToken in self.tokenList:
self.LOGGER.debug("Check if AccessToken {} is out of date".format(accToken))
if (datetime.now() - accToken.timestamp).seconds > valid_time:
print("delete", accToken)
self.LOGGER.info("Delete AccessToken {} from List of current Tokens".format(accToken))
self.tokenList.remove(accToken)
else:
self.LOGGER.debug("AccessToken {} is up to date. {} seconds left".format(accToken, valid_time - (datetime.now() - accToken.timestamp).seconds))
self.LOGGER.debug("List of current Tokens: {}".format(self.tokenList))
self.LOGGER.info("Wait 10 Seconds")
time.sleep(10)

View File

@ -1,8 +1,7 @@
from flask import Blueprint, request, jsonify
from geruecht.finanzer import LOGGER
from datetime import datetime
from geruecht import MONEY, db
from geruecht.routes import verifyAccessToken
from geruecht import MONEY, db, accesTokenController
finanzer = Blueprint("finanzer", __name__)
@ -20,8 +19,8 @@ def _getFinanzer():
LOGGER.info("Get main for Finanzer")
token = request.headers.get("Token")
LOGGER.debug("Verify AccessToken with Token {}".format(token))
accToken = verifyAccessToken(token, MONEY)
if accToken is not None:
accToken = accesTokenController.validateAccessToken(token, MONEY)
if accToken:
LOGGER.debug("Get all Useres")
users = db.getAllUser()
dic = {}
@ -49,10 +48,10 @@ def _getFinanzerYear():
LOGGER.info("Get all Geruechte from User.")
token = request.headers.get("Token")
LOGGER.debug("Verify AccessToken with Token {}".format(token))
accToken = verifyAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, MONEY)
dic = {}
if accToken is not None:
if accToken:
data = request.get_json()
LOGGER.debug("Get data {}".format(data))
userID = data['userId']
@ -85,9 +84,9 @@ def _addAmount():
LOGGER.info("Add Amount")
token = request.headers.get("Token")
LOGGER.debug("Verify AccessToken with Token {}".format(token))
accToken = verifyAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, MONEY)
if accToken is not None:
if accToken:
data = request.get_json()
LOGGER.debug("Get data {}".format(data))
userID = data['userId']
@ -129,9 +128,9 @@ def _addCredit():
LOGGER.info("Add Amount")
token = request.headers.get("Token")
LOGGER.debug("Verify AccessToken with Token {}".format(token))
accToken = verifyAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, MONEY)
if accToken is not None:
if accToken:
data = request.get_json()
print(data)

View File

@ -6,44 +6,20 @@ from flask import request, jsonify
def login(user, password):
return user.login(password)
def verifyAccessToken(token, group):
""" Verify Accestoken
Verify an Accestoken and Group so if the User has permission or not.
Retrieves the accestoken if valid else retrieves None
Args:
token: Token to verify.
group: Group like 'moneymaster', 'gastro', 'user' or 'bar'
Returns:
An the AccesToken for this given Token or None.
"""
LOGGER.info("Verify AccessToken with token: {} and group: {}".format(token, group))
accToken = accesTokenController.findAccesToken(token)
LOGGER.debug("AccessToken is {}".format(accToken))
if accToken is not None:
LOGGER.debug("Check if AccesToken {} has same group {}".format(accToken, group))
if accesTokenController.isSameGroup(accToken, group):
accToken.updateTimestamp()
LOGGER.info("Found AccessToken {} with token: {} and group: {}".format(accToken, token, group))
return accToken
LOGGER.info("No AccessToken with token: {} and group: {} found".format(token, group))
return None
@app.route("/valid")
def _valid():
token = request.headers.get("Token")
accToken = verifyAccessToken(token, MONEY)
if accToken is not None:
accToken = accesTokenController.validateAccessToken(token, MONEY)
if accToken:
return jsonify(accToken.user.toJSON())
accToken = verifyAccessToken(token, BAR)
if accToken is not None:
accToken = accesTokenController.validateAccessToken(token, BAR)
if accToken:
return jsonify(accToken.user.toJSON())
accToken = verifyAccessToken(token, GASTRO)
if accToken is not None:
accToken = accesTokenController.validateAccessToken(token, GASTRO)
if accToken:
return jsonify(accToken.user.toJSON())
accToken = verifyAccessToken(token, USER)
if accToken is not None:
accToken = accesTokenController.validateAccessToken(token, USER)
if accToken:
return jsonify(accToken.user.toJSON())
return jsonify({"error": "permission denied"}), 401
@ -96,12 +72,3 @@ def _login():
return jsonify({"error": "wrong password"}), 401
LOGGER.info("User {} does not exist.".format(username))
return jsonify({"error": "wrong username"}), 402
@app.route("/getFinanzer")
def getFinanzer():
users = User.query.all()
dic = {}
for user in users:
dic[user.userID] = user.toJSON()
print(dic)
return jsonify(dic)