accessToken werden nun in der datenbank gespeichert
lifetime kann auch neu gesetzt werden.
This commit is contained in:
parent
068abb43a2
commit
a70904ceac
|
@ -1,6 +1,7 @@
|
|||
from geruecht.model.accessToken import AccessToken
|
||||
import geruecht.controller as gc
|
||||
import geruecht.controller.mainController as mc
|
||||
import geruecht.controller.databaseController as dc
|
||||
from geruecht.model import BAR
|
||||
from datetime import datetime, timedelta
|
||||
import hashlib
|
||||
|
@ -10,6 +11,7 @@ from geruecht.logger import getDebugLogger
|
|||
debug = getDebugLogger()
|
||||
|
||||
mainController = mc.MainController()
|
||||
db = dc.DatabaseController()
|
||||
|
||||
class AccesTokenController(metaclass=Singleton):
|
||||
""" Control all createt AccesToken
|
||||
|
@ -30,7 +32,6 @@ class AccesTokenController(metaclass=Singleton):
|
|||
"""
|
||||
debug.info("init accesstoken controller")
|
||||
self.lifetime = gc.accConfig
|
||||
self.tokenList = []
|
||||
|
||||
def checkBar(self, 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.
|
||||
"""
|
||||
debug.info("check token {{ {} }} is valid")
|
||||
for accToken in self.tokenList:
|
||||
for accToken in db.getAccessTokens():
|
||||
debug.debug("accesstoken is {}".format(accToken))
|
||||
endTime = accToken.timestamp + timedelta(seconds=accToken.lifetime)
|
||||
now = datetime.now()
|
||||
|
@ -69,19 +70,16 @@ class AccesTokenController(metaclass=Singleton):
|
|||
debug.debug("check if accestoken {{ {} }} has group {{ {} }}".format(accToken, group))
|
||||
if self.isSameGroup(accToken, group):
|
||||
accToken.updateTimestamp()
|
||||
db.updateAccessToken(accToken)
|
||||
debug.debug("found accesstoken {{ {} }} with token: {{ {} }} and group: {{ {} }}".format(accToken, token, group))
|
||||
return accToken
|
||||
else:
|
||||
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))
|
||||
return False
|
||||
|
||||
def deleteAccessToken(self, accToken):
|
||||
debug.info("delete accesstoken {{ {} }}".format(accToken))
|
||||
self.tokenList.remove(accToken)
|
||||
|
||||
def createAccesToken(self, user, ldap_conn):
|
||||
def createAccesToken(self, user):
|
||||
""" Create an AccessToken
|
||||
|
||||
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())
|
||||
token = hashlib.md5((now + user.dn).encode('utf-8')).hexdigest()
|
||||
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))
|
||||
self.tokenList.append(accToken)
|
||||
return token
|
||||
|
||||
def isSameGroup(self, accToken, groups):
|
||||
|
@ -117,3 +114,7 @@ class AccesTokenController(metaclass=Singleton):
|
|||
for group in groups:
|
||||
if group in accToken.user.group: return True
|
||||
return False
|
||||
|
||||
def updateAccessToken(self, accToken):
|
||||
accToken.updateTimestamp()
|
||||
return db.updateAccessToken(accToken)
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
from ..mainController import Singleton
|
||||
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
|
||||
import traceback
|
||||
from MySQLdb._exceptions import IntegrityError
|
||||
|
@ -13,6 +13,7 @@ class DatabaseController(dbUserController.Base,
|
|||
dbJobKindController.Base,
|
||||
dbJobInviteController.Base,
|
||||
dbJobRequesController.Base,
|
||||
dbAccessTokenController.Base,
|
||||
metaclass=Singleton):
|
||||
'''
|
||||
DatabaesController
|
||||
|
|
|
@ -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))
|
|
@ -153,8 +153,7 @@ class Base:
|
|||
debug.debug("user is {{ {} }}".format(user))
|
||||
user.password = password
|
||||
ldap.login(username, password)
|
||||
ldap_conn = ldap.bind(user, password)
|
||||
return user, ldap_conn
|
||||
return user
|
||||
except PermissionDenied as err:
|
||||
debug.debug("permission is denied", exc_info=True)
|
||||
raise err
|
|
@ -15,9 +15,8 @@ class AccessToken():
|
|||
timestamp = None
|
||||
user = 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
|
||||
|
||||
No more to say.
|
||||
|
@ -28,11 +27,11 @@ class AccessToken():
|
|||
timestamp: Default current time, but can set to an other datetime-Object.
|
||||
"""
|
||||
debug.debug("init accesstoken")
|
||||
self.id = id
|
||||
self.user = user
|
||||
self.timestamp = timestamp
|
||||
self.lifetime = lifetime
|
||||
self.token = token
|
||||
self.ldap_conn = ldap_conn
|
||||
self.lock_bar = False
|
||||
debug.debug("accesstoken is {{ {} }}".format(self))
|
||||
|
||||
|
|
|
@ -132,7 +132,8 @@ def _saveLifeTime(**kwargs):
|
|||
lifetime, accToken))
|
||||
accToken.lifetime = lifetime
|
||||
debug.info("update accesstoken timestamp")
|
||||
accToken.updateTimestamp()
|
||||
accToken = accesTokenController.updateAccessToken(accToken)
|
||||
accToken = accesTokenController.validateAccessToken(accToken.token, [USER, EXTERN])
|
||||
retVal = {"value": accToken.lifetime,
|
||||
"group": accToken.user.toJSON()['group']}
|
||||
debug.info(
|
||||
|
@ -178,10 +179,9 @@ def _login():
|
|||
debug.debug("username is {{ {} }}".format(username))
|
||||
try:
|
||||
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))
|
||||
user.password = password
|
||||
token = accesTokenController.createAccesToken(user, ldap_conn)
|
||||
token = accesTokenController.createAccesToken(user)
|
||||
debug.debug("accesstoken is {{ {} }}".format(token))
|
||||
debug.info("validate accesstoken")
|
||||
dic = accesTokenController.validateAccessToken(
|
||||
|
@ -194,6 +194,6 @@ def _login():
|
|||
except PermissionDenied as err:
|
||||
debug.warning("permission denied exception in logout", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 401
|
||||
except Exception:
|
||||
except Exception as err:
|
||||
debug.warning("exception in logout.", exc_info=True)
|
||||
return jsonify({"error": "permission denied"}), 401
|
||||
|
|
Loading…
Reference in New Issue