accessToken werden nun in der datenbank gespeichert

lifetime kann auch neu gesetzt werden.
This commit is contained in:
Tim Gröger 2020-06-04 23:03:39 +02:00
parent 068abb43a2
commit a70904ceac
6 changed files with 89 additions and 21 deletions

View File

@ -1,6 +1,7 @@
from geruecht.model.accessToken import AccessToken from geruecht.model.accessToken import AccessToken
import geruecht.controller as gc import geruecht.controller as gc
import geruecht.controller.mainController as mc import geruecht.controller.mainController as mc
import geruecht.controller.databaseController as dc
from geruecht.model import BAR from geruecht.model import BAR
from datetime import datetime, timedelta from datetime import datetime, timedelta
import hashlib import hashlib
@ -10,6 +11,7 @@ from geruecht.logger import getDebugLogger
debug = getDebugLogger() debug = getDebugLogger()
mainController = mc.MainController() mainController = mc.MainController()
db = dc.DatabaseController()
class AccesTokenController(metaclass=Singleton): class AccesTokenController(metaclass=Singleton):
""" Control all createt AccesToken """ Control all createt AccesToken
@ -30,7 +32,6 @@ class AccesTokenController(metaclass=Singleton):
""" """
debug.info("init accesstoken controller") debug.info("init accesstoken controller")
self.lifetime = gc.accConfig self.lifetime = gc.accConfig
self.tokenList = []
def checkBar(self, user): def checkBar(self, user):
debug.info("check if user {{ {} }} is baruser".format(user)) debug.info("check if user {{ {} }} is baruser".format(user))
@ -57,7 +58,7 @@ class AccesTokenController(metaclass=Singleton):
An the AccesToken for this given Token or False. An the AccesToken for this given Token or False.
""" """
debug.info("check token {{ {} }} is valid") debug.info("check token {{ {} }} is valid")
for accToken in self.tokenList: for accToken in db.getAccessTokens():
debug.debug("accesstoken is {}".format(accToken)) debug.debug("accesstoken is {}".format(accToken))
endTime = accToken.timestamp + timedelta(seconds=accToken.lifetime) endTime = accToken.timestamp + timedelta(seconds=accToken.lifetime)
now = datetime.now() now = datetime.now()
@ -69,19 +70,16 @@ class AccesTokenController(metaclass=Singleton):
debug.debug("check if accestoken {{ {} }} has group {{ {} }}".format(accToken, group)) debug.debug("check if accestoken {{ {} }} has group {{ {} }}".format(accToken, group))
if self.isSameGroup(accToken, group): if self.isSameGroup(accToken, group):
accToken.updateTimestamp() accToken.updateTimestamp()
db.updateAccessToken(accToken)
debug.debug("found accesstoken {{ {} }} with token: {{ {} }} and group: {{ {} }}".format(accToken, token, group)) debug.debug("found accesstoken {{ {} }} with token: {{ {} }} and group: {{ {} }}".format(accToken, token, group))
return accToken return accToken
else: else:
debug.debug("accesstoken is {{ {} }} out of date".format(accToken)) debug.debug("accesstoken is {{ {} }} out of date".format(accToken))
self.deleteAccessToken(accToken) db.deleteAccessToken(accToken)
debug.debug("no valid accesstoken with token: {{ {} }} and group: {{ {} }}".format(token, group)) debug.debug("no valid accesstoken with token: {{ {} }} and group: {{ {} }}".format(token, group))
return False return False
def deleteAccessToken(self, accToken): def createAccesToken(self, user):
debug.info("delete accesstoken {{ {} }}".format(accToken))
self.tokenList.remove(accToken)
def createAccesToken(self, user, ldap_conn):
""" Create an AccessToken """ Create an AccessToken
Create an AccessToken for an User and add it to the tokenList. Create an AccessToken for an User and add it to the tokenList.
@ -96,9 +94,8 @@ class AccesTokenController(metaclass=Singleton):
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()
self.checkBar(user) self.checkBar(user)
accToken = AccessToken(user, token, ldap_conn, self.lifetime, datetime.now()) accToken = db.createAccessToken(user, token, self.lifetime, datetime.now(), lock_bar=False)
debug.debug("accesstoken is {{ {} }}".format(accToken)) debug.debug("accesstoken is {{ {} }}".format(accToken))
self.tokenList.append(accToken)
return token return token
def isSameGroup(self, accToken, groups): def isSameGroup(self, accToken, groups):
@ -117,3 +114,7 @@ class AccesTokenController(metaclass=Singleton):
for group in groups: for group in groups:
if group in accToken.user.group: return True if group in accToken.user.group: return True
return False return False
def updateAccessToken(self, accToken):
accToken.updateTimestamp()
return db.updateAccessToken(accToken)

View File

@ -1,6 +1,6 @@
from ..mainController import Singleton from ..mainController import Singleton
from geruecht import db from geruecht import db
from ..databaseController import dbUserController, dbCreditListController, dbJobKindController, dbPricelistController, dbWorkerController, dbWorkgroupController, dbJobInviteController, dbJobRequesController from ..databaseController import dbUserController, dbCreditListController, dbJobKindController, dbPricelistController, dbWorkerController, dbWorkgroupController, dbJobInviteController, dbJobRequesController, dbAccessTokenController
from geruecht.exceptions import DatabaseExecption from geruecht.exceptions import DatabaseExecption
import traceback import traceback
from MySQLdb._exceptions import IntegrityError from MySQLdb._exceptions import IntegrityError
@ -13,6 +13,7 @@ class DatabaseController(dbUserController.Base,
dbJobKindController.Base, dbJobKindController.Base,
dbJobInviteController.Base, dbJobInviteController.Base,
dbJobRequesController.Base, dbJobRequesController.Base,
dbAccessTokenController.Base,
metaclass=Singleton): metaclass=Singleton):
''' '''
DatabaesController DatabaesController

View File

@ -0,0 +1,68 @@
import traceback
from geruecht.exceptions import DatabaseExecption
from geruecht.model.accessToken import AccessToken
class Base:
def getAccessToken(self, item):
try:
cursor = self.db.connection.cursor()
if type(item) == str:
sql = "select * from session where token='{}'".format(item)
elif type(item) == int:
sql = 'select * from session where id={}'.format(item)
else:
raise DatabaseExecption("item as no type int or str. name={}, type={}".format(item, type(item)))
cursor.execute(sql)
session = cursor.fetchone()
retVal = AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'], session['timestamp']) if session != None else None
return retVal
except Exception as err:
traceback.print_exc()
self.db.connection.rollback()
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
def getAccessTokens(self):
try:
cursor = self.db.connection.cursor()
cursor.execute("select * from session")
sessions = cursor.fetchall()
retVal = [AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'], session['timestamp']) for session in sessions]
return retVal
except Exception as err:
traceback.print_exc()
self.db.connection.rollback()
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
def createAccessToken(self, user, token, lifetime, timestamp, lock_bar):
try:
cursor = self.db.connection.cursor()
cursor.execute("insert into session (user, timestamp, lock_bar, token, lifetime) VALUES ({}, '{}', {}, '{}', {})".format(user.id, timestamp, lock_bar, token, lifetime))
self.db.connection.commit()
return self.getAccessToken(token)
except Exception as err:
traceback.print_exc()
self.db.connection.rollback()
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
def updateAccessToken(self, accToken):
try:
cursor = self.db.connection.cursor()
cursor.execute("update session set timestamp='{}', lock_bar={}, lifetime={} where id={}".format(accToken.timestamp, accToken.lock_bar, accToken.lifetime, accToken.id))
self.db.connection.commit()
return self.getAccessToken(accToken.id)
except Exception as err:
traceback.print_exc()
self.db.connection.rollback()
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
def deleteAccessToken(self, accToken):
try:
cursor = self.db.connection.cursor()
cursor.execute("delete from session where id={}".format(accToken.id))
self.db.connection.commit()
except Exception as err:
traceback.print_exc()
self.db.connection.rollback()
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))

View File

@ -153,8 +153,7 @@ class Base:
debug.debug("user is {{ {} }}".format(user)) debug.debug("user is {{ {} }}".format(user))
user.password = password user.password = password
ldap.login(username, password) ldap.login(username, password)
ldap_conn = ldap.bind(user, password) return user
return user, ldap_conn
except PermissionDenied as err: except PermissionDenied as err:
debug.debug("permission is denied", exc_info=True) debug.debug("permission is denied", exc_info=True)
raise err raise err

View File

@ -15,9 +15,8 @@ class AccessToken():
timestamp = None timestamp = None
user = None user = None
token = None token = None
ldap_conn = None
def __init__(self, user, token, ldap_conn, lifetime, timestamp=datetime.now()): def __init__(self, id, user, token, lifetime, timestamp=datetime.now()):
""" Initialize Class AccessToken """ Initialize Class AccessToken
No more to say. No more to say.
@ -28,11 +27,11 @@ class AccessToken():
timestamp: Default current time, but can set to an other datetime-Object. timestamp: Default current time, but can set to an other datetime-Object.
""" """
debug.debug("init accesstoken") debug.debug("init accesstoken")
self.id = id
self.user = user self.user = user
self.timestamp = timestamp self.timestamp = timestamp
self.lifetime = lifetime self.lifetime = lifetime
self.token = token self.token = token
self.ldap_conn = ldap_conn
self.lock_bar = False self.lock_bar = False
debug.debug("accesstoken is {{ {} }}".format(self)) debug.debug("accesstoken is {{ {} }}".format(self))

View File

@ -132,7 +132,8 @@ def _saveLifeTime(**kwargs):
lifetime, accToken)) lifetime, accToken))
accToken.lifetime = lifetime accToken.lifetime = lifetime
debug.info("update accesstoken timestamp") debug.info("update accesstoken timestamp")
accToken.updateTimestamp() accToken = accesTokenController.updateAccessToken(accToken)
accToken = accesTokenController.validateAccessToken(accToken.token, [USER, EXTERN])
retVal = {"value": accToken.lifetime, retVal = {"value": accToken.lifetime,
"group": accToken.user.toJSON()['group']} "group": accToken.user.toJSON()['group']}
debug.info( debug.info(
@ -178,10 +179,9 @@ def _login():
debug.debug("username is {{ {} }}".format(username)) debug.debug("username is {{ {} }}".format(username))
try: try:
debug.info("search {{ {} }} in database".format(username)) debug.info("search {{ {} }} in database".format(username))
user, ldap_conn = mainController.loginUser(username, password) user = mainController.loginUser(username, password)
debug.debug("user is {{ {} }}".format(user)) debug.debug("user is {{ {} }}".format(user))
user.password = password token = accesTokenController.createAccesToken(user)
token = accesTokenController.createAccesToken(user, ldap_conn)
debug.debug("accesstoken is {{ {} }}".format(token)) debug.debug("accesstoken is {{ {} }}".format(token))
debug.info("validate accesstoken") debug.info("validate accesstoken")
dic = accesTokenController.validateAccessToken( dic = accesTokenController.validateAccessToken(
@ -194,6 +194,6 @@ def _login():
except PermissionDenied as err: except PermissionDenied as err:
debug.warning("permission denied exception in logout", exc_info=True) debug.warning("permission denied exception in logout", exc_info=True)
return jsonify({"error": str(err)}), 401 return jsonify({"error": str(err)}), 401
except Exception: except Exception as err:
debug.warning("exception in logout.", exc_info=True) debug.warning("exception in logout.", exc_info=True)
return jsonify({"error": "permission denied"}), 401 return jsonify({"error": "permission denied"}), 401