update token validatition
no second thread to validate for token ... only on access it will be validate
This commit is contained in:
parent
a052add057
commit
5b37e3d15b
|
@ -61,22 +61,14 @@ def getLDAPController():
|
||||||
|
|
||||||
|
|
||||||
from flask import Flask
|
from flask import Flask
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
|
||||||
from flask_cors import CORS
|
from flask_cors import CORS
|
||||||
from .controller.accesTokenController import AccesTokenController
|
from .controller.accesTokenController import AccesTokenController
|
||||||
|
|
||||||
# from flask_login import LoginManager
|
|
||||||
LOGGER.info("Build APP")
|
LOGGER.info("Build APP")
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
CORS(app)
|
CORS(app)
|
||||||
# app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
|
# app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
|
||||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
|
|
||||||
#db = SQLAlchemy(app)
|
|
||||||
accesTokenController = AccesTokenController("GERUECHT")
|
accesTokenController = AccesTokenController("GERUECHT")
|
||||||
accesTokenController.start()
|
|
||||||
# login_manager = LoginManager(app)
|
|
||||||
# login_manager.login_view = 'login'
|
|
||||||
# login_manager.login_message_category = 'info'
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,5 @@
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
from geruecht import BAR, db, ldapController as ldap
|
from geruecht import BAR, db, ldapController as ldap, accesTokenController
|
||||||
from geruecht.routes import verifyAccessToken
|
|
||||||
from geruecht.model.user import User
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
baruser = Blueprint("baruser", __name__)
|
baruser = Blueprint("baruser", __name__)
|
||||||
|
@ -19,10 +17,10 @@ def _bar():
|
||||||
print(request.headers)
|
print(request.headers)
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
print(token)
|
print(token)
|
||||||
accToken = verifyAccessToken(token, BAR)
|
accToken = accesTokenController.validateAccessToken(token, BAR)
|
||||||
|
|
||||||
dic = {}
|
dic = {}
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
users = db.getAllUser()
|
users = db.getAllUser()
|
||||||
for user in users:
|
for user in users:
|
||||||
geruecht = None
|
geruecht = None
|
||||||
|
@ -56,9 +54,9 @@ def _baradd():
|
||||||
"""
|
"""
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
print(token)
|
print(token)
|
||||||
accToken = verifyAccessToken(token, BAR)
|
accToken = accesTokenController.validateAccessToken(token, BAR)
|
||||||
|
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
userID = data['userId']
|
userID = data['userId']
|
||||||
amount = int(data['amount'])
|
amount = int(data['amount'])
|
||||||
|
@ -89,10 +87,10 @@ def _getUsers():
|
||||||
"""
|
"""
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
print(token)
|
print(token)
|
||||||
accToken = verifyAccessToken(token, BAR)
|
accToken = accesTokenController.validateAccessToken(token, BAR)
|
||||||
|
|
||||||
retVal = {}
|
retVal = {}
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
retVal = ldap.getAllUser()
|
retVal = ldap.getAllUser()
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
return jsonify({"error": "permission denied"}), 401
|
||||||
|
@ -101,9 +99,9 @@ def _getUsers():
|
||||||
def _search():
|
def _search():
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
print(token)
|
print(token)
|
||||||
accToken = verifyAccessToken(token, BAR)
|
accToken = accesTokenController.validateAccessToken(token, BAR)
|
||||||
|
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
|
||||||
searchString = data['searchString']
|
searchString = data['searchString']
|
||||||
|
|
|
@ -1,14 +1,12 @@
|
||||||
from geruecht.model.accessToken import AccessToken
|
from geruecht.model.accessToken import AccessToken
|
||||||
from geruecht.controller import LOGGER
|
from geruecht.controller import LOGGER
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
import time
|
|
||||||
from threading import Thread
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import logging
|
import logging
|
||||||
from logging.handlers import WatchedFileHandler
|
from logging.handlers import WatchedFileHandler
|
||||||
from geruecht import Singleton
|
from geruecht import Singleton
|
||||||
|
|
||||||
class AccesTokenController(Thread, metaclass=Singleton):
|
class AccesTokenController(metaclass=Singleton):
|
||||||
""" Control all createt AccesToken
|
""" Control all createt AccesToken
|
||||||
|
|
||||||
This Class create, delete, find and manage AccesToken.
|
This Class create, delete, find and manage AccesToken.
|
||||||
|
@ -19,7 +17,7 @@ class AccesTokenController(Thread, metaclass=Singleton):
|
||||||
"""
|
"""
|
||||||
instance = None
|
instance = None
|
||||||
tokenList = None
|
tokenList = None
|
||||||
lifetime = 60
|
lifetime = 1800
|
||||||
|
|
||||||
def __init__(self, arg):
|
def __init__(self, arg):
|
||||||
""" Initialize AccessTokenController
|
""" Initialize AccessTokenController
|
||||||
|
@ -39,31 +37,39 @@ class AccesTokenController(Thread, metaclass=Singleton):
|
||||||
self.LOGGER.setLevel(logging.DEBUG)
|
self.LOGGER.setLevel(logging.DEBUG)
|
||||||
self.LOGGER.addHandler(logFileHandler)
|
self.LOGGER.addHandler(logFileHandler)
|
||||||
self.LOGGER.propagate = False
|
self.LOGGER.propagate = False
|
||||||
|
|
||||||
LOGGER.debug("Initialize Threading")
|
|
||||||
Thread.__init__(self)
|
|
||||||
self.tokenList = []
|
self.tokenList = []
|
||||||
|
|
||||||
def findAccesToken(self, token):
|
def validateAccessToken(self, token, group):
|
||||||
""" Find a Token in current AccessTokens
|
""" 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:
|
Args:
|
||||||
token: Token to find
|
token: Token to verify.
|
||||||
|
group: Group like 'moneymaster', 'gastro', 'user' or 'bar'
|
||||||
Returns:
|
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.info("Verify AccessToken with token: {} and group: {}".format(token, group))
|
||||||
LOGGER.debug("Iterate through List of current Tokens")
|
|
||||||
for accToken in self.tokenList:
|
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:
|
if accToken == token:
|
||||||
LOGGER.info("Find AccessToken {} with Token {}".format(accToken, token))
|
LOGGER.debug("AccessToken is {}".format(accToken))
|
||||||
return accToken
|
endTime = accToken.timestamp + timedelta(seconds=self.lifetime)
|
||||||
LOGGER.info("no AccesToken found with Token {}".format(token))
|
now = datetime.now()
|
||||||
return None
|
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):
|
def createAccesToken(self, user):
|
||||||
""" Create an AccessToken
|
""" Create an AccessToken
|
||||||
|
@ -79,7 +85,7 @@ class AccesTokenController(Thread, metaclass=Singleton):
|
||||||
LOGGER.info("Create AccessToken")
|
LOGGER.info("Create AccessToken")
|
||||||
now = datetime.ctime(datetime.now())
|
now = datetime.ctime(datetime.now())
|
||||||
token = hashlib.md5((now + user.dn).encode('utf-8')).hexdigest()
|
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))
|
LOGGER.debug("Add AccessToken {} to current Tokens".format(accToken))
|
||||||
self.tokenList.append(accToken)
|
self.tokenList.append(accToken)
|
||||||
LOGGER.info("Finished create AccessToken {} with Token {}".format(accToken, token))
|
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)
|
print("controll if", accToken, "hase group", group)
|
||||||
LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, group))
|
LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, group))
|
||||||
return True if group in accToken.user.group else False
|
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)
|
|
||||||
|
|
|
@ -1,8 +1,7 @@
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
from geruecht.finanzer import LOGGER
|
from geruecht.finanzer import LOGGER
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from geruecht import MONEY, db
|
from geruecht import MONEY, db, accesTokenController
|
||||||
from geruecht.routes import verifyAccessToken
|
|
||||||
|
|
||||||
finanzer = Blueprint("finanzer", __name__)
|
finanzer = Blueprint("finanzer", __name__)
|
||||||
|
|
||||||
|
@ -20,8 +19,8 @@ def _getFinanzer():
|
||||||
LOGGER.info("Get main for Finanzer")
|
LOGGER.info("Get main for Finanzer")
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
LOGGER.debug("Verify AccessToken with Token {}".format(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:
|
||||||
LOGGER.debug("Get all Useres")
|
LOGGER.debug("Get all Useres")
|
||||||
users = db.getAllUser()
|
users = db.getAllUser()
|
||||||
dic = {}
|
dic = {}
|
||||||
|
@ -49,10 +48,10 @@ def _getFinanzerYear():
|
||||||
LOGGER.info("Get all Geruechte from User.")
|
LOGGER.info("Get all Geruechte from User.")
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
LOGGER.debug("Verify AccessToken with Token {}".format(token))
|
LOGGER.debug("Verify AccessToken with Token {}".format(token))
|
||||||
accToken = verifyAccessToken(token, MONEY)
|
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
||||||
|
|
||||||
dic = {}
|
dic = {}
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
LOGGER.debug("Get data {}".format(data))
|
LOGGER.debug("Get data {}".format(data))
|
||||||
userID = data['userId']
|
userID = data['userId']
|
||||||
|
@ -85,9 +84,9 @@ def _addAmount():
|
||||||
LOGGER.info("Add Amount")
|
LOGGER.info("Add Amount")
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
LOGGER.debug("Verify AccessToken with Token {}".format(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()
|
data = request.get_json()
|
||||||
LOGGER.debug("Get data {}".format(data))
|
LOGGER.debug("Get data {}".format(data))
|
||||||
userID = data['userId']
|
userID = data['userId']
|
||||||
|
@ -129,9 +128,9 @@ def _addCredit():
|
||||||
LOGGER.info("Add Amount")
|
LOGGER.info("Add Amount")
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
LOGGER.debug("Verify AccessToken with Token {}".format(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()
|
data = request.get_json()
|
||||||
print(data)
|
print(data)
|
||||||
|
|
|
@ -6,44 +6,20 @@ from flask import request, jsonify
|
||||||
def login(user, password):
|
def login(user, password):
|
||||||
return user.login(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")
|
@app.route("/valid")
|
||||||
def _valid():
|
def _valid():
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
accToken = verifyAccessToken(token, MONEY)
|
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
return jsonify(accToken.user.toJSON())
|
return jsonify(accToken.user.toJSON())
|
||||||
accToken = verifyAccessToken(token, BAR)
|
accToken = accesTokenController.validateAccessToken(token, BAR)
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
return jsonify(accToken.user.toJSON())
|
return jsonify(accToken.user.toJSON())
|
||||||
accToken = verifyAccessToken(token, GASTRO)
|
accToken = accesTokenController.validateAccessToken(token, GASTRO)
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
return jsonify(accToken.user.toJSON())
|
return jsonify(accToken.user.toJSON())
|
||||||
accToken = verifyAccessToken(token, USER)
|
accToken = accesTokenController.validateAccessToken(token, USER)
|
||||||
if accToken is not None:
|
if accToken:
|
||||||
return jsonify(accToken.user.toJSON())
|
return jsonify(accToken.user.toJSON())
|
||||||
return jsonify({"error": "permission denied"}), 401
|
return jsonify({"error": "permission denied"}), 401
|
||||||
|
|
||||||
|
@ -96,12 +72,3 @@ def _login():
|
||||||
return jsonify({"error": "wrong password"}), 401
|
return jsonify({"error": "wrong password"}), 401
|
||||||
LOGGER.info("User {} does not exist.".format(username))
|
LOGGER.info("User {} does not exist.".format(username))
|
||||||
return jsonify({"error": "wrong username"}), 402
|
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)
|
|
||||||
|
|
Loading…
Reference in New Issue