user kann seine accessToken abrufen und löschen
This commit is contained in:
parent
a70904ceac
commit
c957195ffb
|
@ -79,7 +79,7 @@ class AccesTokenController(metaclass=Singleton):
|
||||||
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 createAccesToken(self, user):
|
def createAccesToken(self, user, user_agent=None):
|
||||||
""" 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.
|
||||||
|
@ -94,7 +94,7 @@ 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 = db.createAccessToken(user, token, self.lifetime, datetime.now(), lock_bar=False)
|
accToken = db.createAccessToken(user, token, self.lifetime, datetime.now(), lock_bar=False, user_agent=user_agent)
|
||||||
debug.debug("accesstoken is {{ {} }}".format(accToken))
|
debug.debug("accesstoken is {{ {} }}".format(accToken))
|
||||||
return token
|
return token
|
||||||
|
|
||||||
|
@ -115,6 +115,12 @@ class AccesTokenController(metaclass=Singleton):
|
||||||
if group in accToken.user.group: return True
|
if group in accToken.user.group: return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def getAccessTokensFromUser(self, user):
|
||||||
|
return db.getAccessTokensFromUser(user)
|
||||||
|
|
||||||
|
def deleteAccessToken(self, accToken):
|
||||||
|
db.deleteAccessToken(accToken)
|
||||||
|
|
||||||
def updateAccessToken(self, accToken):
|
def updateAccessToken(self, accToken):
|
||||||
accToken.updateTimestamp()
|
accToken.updateTimestamp()
|
||||||
return db.updateAccessToken(accToken)
|
return db.updateAccessToken(accToken)
|
||||||
|
|
|
@ -16,29 +16,43 @@ class Base:
|
||||||
raise DatabaseExecption("item as no type int or str. name={}, type={}".format(item, type(item)))
|
raise DatabaseExecption("item as no type int or str. name={}, type={}".format(item, type(item)))
|
||||||
cursor.execute(sql)
|
cursor.execute(sql)
|
||||||
session = cursor.fetchone()
|
session = cursor.fetchone()
|
||||||
retVal = AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'], session['timestamp']) if session != None else None
|
retVal = AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'], session['timestamp'], browser=session['browser'], platform=session['platform']) if session != None else None
|
||||||
return retVal
|
return retVal
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
self.db.connection.rollback()
|
self.db.connection.rollback()
|
||||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||||
|
|
||||||
def getAccessTokens(self):
|
def getAccessTokensFromUser(self, user):
|
||||||
try:
|
try:
|
||||||
cursor = self.db.connection.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
cursor.execute("select * from session")
|
cursor.execute("select * from session where user={}".format(user.id))
|
||||||
sessions = cursor.fetchall()
|
sessions = cursor.fetchall()
|
||||||
retVal = [AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'], session['timestamp']) for session in sessions]
|
retVal = [
|
||||||
|
AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'],
|
||||||
|
session['timestamp'], browser=session['browser'], platform=session['platform']) for session in sessions]
|
||||||
return retVal
|
return retVal
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
self.db.connection.rollback()
|
self.db.connection.rollback()
|
||||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||||
|
|
||||||
def createAccessToken(self, user, token, lifetime, timestamp, lock_bar):
|
def getAccessTokens(self):
|
||||||
try:
|
try:
|
||||||
cursor = self.db.connection.cursor()
|
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))
|
cursor.execute("select * from session")
|
||||||
|
sessions = cursor.fetchall()
|
||||||
|
retVal = [AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'], session['timestamp'], browser=session['browser'], platform=session['platform']) 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, user_agent=None):
|
||||||
|
try:
|
||||||
|
cursor = self.db.connection.cursor()
|
||||||
|
cursor.execute("insert into session (user, timestamp, lock_bar, token, lifetime, browser, platform) VALUES ({}, '{}', {}, '{}', {}, '{}', '{}')".format(user.id, timestamp, lock_bar, token, lifetime, user_agent.browser if user_agent else 'NULL', user_agent.platform if user_agent else 'NULL'))
|
||||||
self.db.connection.commit()
|
self.db.connection.commit()
|
||||||
return self.getAccessToken(token)
|
return self.getAccessToken(token)
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
|
|
|
@ -16,7 +16,7 @@ class AccessToken():
|
||||||
user = None
|
user = None
|
||||||
token = None
|
token = None
|
||||||
|
|
||||||
def __init__(self, id, user, token, lifetime, timestamp=datetime.now()):
|
def __init__(self, id, user, token, lifetime, timestamp=datetime.now(), browser=None, platform=None):
|
||||||
""" Initialize Class AccessToken
|
""" Initialize Class AccessToken
|
||||||
|
|
||||||
No more to say.
|
No more to say.
|
||||||
|
@ -33,6 +33,8 @@ class AccessToken():
|
||||||
self.lifetime = lifetime
|
self.lifetime = lifetime
|
||||||
self.token = token
|
self.token = token
|
||||||
self.lock_bar = False
|
self.lock_bar = False
|
||||||
|
self.browser = browser
|
||||||
|
self.platform = platform
|
||||||
debug.debug("accesstoken is {{ {} }}".format(self))
|
debug.debug("accesstoken is {{ {} }}".format(self))
|
||||||
|
|
||||||
def updateTimestamp(self):
|
def updateTimestamp(self):
|
||||||
|
@ -43,6 +45,27 @@ class AccessToken():
|
||||||
debug.debug("update timestamp from accesstoken {{ {} }}".format(self))
|
debug.debug("update timestamp from accesstoken {{ {} }}".format(self))
|
||||||
self.timestamp = datetime.now()
|
self.timestamp = datetime.now()
|
||||||
|
|
||||||
|
def toJSON(self):
|
||||||
|
""" Create Dic to dump in JSON
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A Dic with static Attributes.
|
||||||
|
"""
|
||||||
|
dic = {
|
||||||
|
"id": self.id,
|
||||||
|
"timestamp": {'year': self.timestamp.year,
|
||||||
|
'month': self.timestamp.month,
|
||||||
|
'day': self.timestamp.day,
|
||||||
|
'hour': self.timestamp.hour,
|
||||||
|
'minute': self.timestamp.minute,
|
||||||
|
'second': self.timestamp.second
|
||||||
|
},
|
||||||
|
"lifetime": self.lifetime,
|
||||||
|
"browser": self.browser,
|
||||||
|
"platform": self.platform
|
||||||
|
}
|
||||||
|
return dic
|
||||||
|
|
||||||
def __eq__(self, token):
|
def __eq__(self, token):
|
||||||
return True if self.token == token else False
|
return True if self.token == token else False
|
||||||
|
|
||||||
|
|
|
@ -144,7 +144,6 @@ def _saveLifeTime(**kwargs):
|
||||||
"exception in save lifetime for accesstoken.", exc_info=True)
|
"exception in save lifetime for accesstoken.", exc_info=True)
|
||||||
return jsonify({"error": str(err)}), 500
|
return jsonify({"error": str(err)}), 500
|
||||||
|
|
||||||
|
|
||||||
@app.route("/logout", methods=['GET'])
|
@app.route("/logout", methods=['GET'])
|
||||||
@login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER], bar=True)
|
@login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER], bar=True)
|
||||||
def _logout(**kwargs):
|
def _logout(**kwargs):
|
||||||
|
@ -178,10 +177,11 @@ def _login():
|
||||||
password = data['password']
|
password = data['password']
|
||||||
debug.debug("username is {{ {} }}".format(username))
|
debug.debug("username is {{ {} }}".format(username))
|
||||||
try:
|
try:
|
||||||
|
user_agent = request.user_agent
|
||||||
debug.info("search {{ {} }} in database".format(username))
|
debug.info("search {{ {} }} in database".format(username))
|
||||||
user = mainController.loginUser(username, password)
|
user = mainController.loginUser(username, password)
|
||||||
debug.debug("user is {{ {} }}".format(user))
|
debug.debug("user is {{ {} }}".format(user))
|
||||||
token = accesTokenController.createAccesToken(user)
|
token = accesTokenController.createAccesToken(user, user_agent=user_agent)
|
||||||
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(
|
||||||
|
|
|
@ -1,14 +1,17 @@
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
from geruecht.decorator import login_required
|
from geruecht.decorator import login_required
|
||||||
import geruecht.controller.mainController as mc
|
import geruecht.controller.mainController as mc
|
||||||
|
import geruecht.controller.accesTokenController as ac
|
||||||
from geruecht.model import USER
|
from geruecht.model import USER
|
||||||
from datetime import datetime, time, date
|
from datetime import datetime, time, date
|
||||||
from geruecht.exceptions import DayLocked
|
from geruecht.exceptions import DayLocked
|
||||||
from geruecht.logger import getDebugLogger, getCreditLogger, getJobsLogger
|
from geruecht.logger import getDebugLogger, getCreditLogger, getJobsLogger
|
||||||
|
from geruecht.model.accessToken import AccessToken
|
||||||
|
|
||||||
user = Blueprint("user", __name__)
|
user = Blueprint("user", __name__)
|
||||||
|
|
||||||
mainController = mc.MainController()
|
mainController = mc.MainController()
|
||||||
|
accesTokenController = ac.AccesTokenController()
|
||||||
|
|
||||||
debug = getDebugLogger()
|
debug = getDebugLogger()
|
||||||
creditL = getCreditLogger()
|
creditL = getCreditLogger()
|
||||||
|
@ -385,4 +388,24 @@ def _deleteJobRequest(**kwargs):
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
debug.debug("exception", exc_info=True)
|
debug.debug("exception", exc_info=True)
|
||||||
return jsonify({"error": str(err)}), 500
|
return jsonify({"error": str(err)}), 500
|
||||||
|
|
||||||
|
|
||||||
|
@user.route("/user/getAccessTokens", methods=['GET', 'POST'])
|
||||||
|
@login_required(groups=[USER])
|
||||||
|
def _getAccessTokens(**kwargs):
|
||||||
|
try:
|
||||||
|
debug.info("/user/getAccessTokens")
|
||||||
|
if request.method == 'POST':
|
||||||
|
data = request.get_json()
|
||||||
|
delAccToken = AccessToken(data['id'], kwargs['accToken'].user, None, None, None)
|
||||||
|
accesTokenController.deleteAccessToken(delAccToken)
|
||||||
|
tokens = accesTokenController.getAccessTokensFromUser(kwargs['accToken'].user)
|
||||||
|
retVal = []
|
||||||
|
for token in tokens:
|
||||||
|
retVal.append(token.toJSON())
|
||||||
|
debug.debug("return {{ {} }}".format(retVal))
|
||||||
|
return jsonify(retVal)
|
||||||
|
except Exception as err:
|
||||||
|
debug.debug("exception", exc_info=True)
|
||||||
|
return jsonify({"error": str(err)}), 500
|
||||||
|
|
Loading…
Reference in New Issue