user kann seine accessToken abrufen und löschen

This commit is contained in:
Tim Gröger 2020-06-05 00:34:32 +02:00
parent a70904ceac
commit c957195ffb
5 changed files with 78 additions and 12 deletions

View File

@ -79,7 +79,7 @@ class AccesTokenController(metaclass=Singleton):
debug.debug("no valid accesstoken with token: {{ {} }} and group: {{ {} }}".format(token, group))
return False
def createAccesToken(self, user):
def createAccesToken(self, user, user_agent=None):
""" Create an AccessToken
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())
token = hashlib.md5((now + user.dn).encode('utf-8')).hexdigest()
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))
return token
@ -115,6 +115,12 @@ class AccesTokenController(metaclass=Singleton):
if group in accToken.user.group: return True
return False
def getAccessTokensFromUser(self, user):
return db.getAccessTokensFromUser(user)
def deleteAccessToken(self, accToken):
db.deleteAccessToken(accToken)
def updateAccessToken(self, accToken):
accToken.updateTimestamp()
return db.updateAccessToken(accToken)

View File

@ -16,29 +16,43 @@ class Base:
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
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
except Exception as err:
traceback.print_exc()
self.db.connection.rollback()
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
def getAccessTokens(self):
def getAccessTokensFromUser(self, user):
try:
cursor = self.db.connection.cursor()
cursor.execute("select * from session")
cursor.execute("select * from session where user={}".format(user.id))
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
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):
def getAccessTokens(self):
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))
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()
return self.getAccessToken(token)
except Exception as err:

View File

@ -16,7 +16,7 @@ class AccessToken():
user = 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
No more to say.
@ -33,6 +33,8 @@ class AccessToken():
self.lifetime = lifetime
self.token = token
self.lock_bar = False
self.browser = browser
self.platform = platform
debug.debug("accesstoken is {{ {} }}".format(self))
def updateTimestamp(self):
@ -43,6 +45,27 @@ class AccessToken():
debug.debug("update timestamp from accesstoken {{ {} }}".format(self))
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):
return True if self.token == token else False

View File

@ -144,7 +144,6 @@ def _saveLifeTime(**kwargs):
"exception in save lifetime for accesstoken.", exc_info=True)
return jsonify({"error": str(err)}), 500
@app.route("/logout", methods=['GET'])
@login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER], bar=True)
def _logout(**kwargs):
@ -178,10 +177,11 @@ def _login():
password = data['password']
debug.debug("username is {{ {} }}".format(username))
try:
user_agent = request.user_agent
debug.info("search {{ {} }} in database".format(username))
user = mainController.loginUser(username, password)
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.info("validate accesstoken")
dic = accesTokenController.validateAccessToken(

View File

@ -1,14 +1,17 @@
from flask import Blueprint, request, jsonify
from geruecht.decorator import login_required
import geruecht.controller.mainController as mc
import geruecht.controller.accesTokenController as ac
from geruecht.model import USER
from datetime import datetime, time, date
from geruecht.exceptions import DayLocked
from geruecht.logger import getDebugLogger, getCreditLogger, getJobsLogger
from geruecht.model.accessToken import AccessToken
user = Blueprint("user", __name__)
mainController = mc.MainController()
accesTokenController = ac.AccesTokenController()
debug = getDebugLogger()
creditL = getCreditLogger()
@ -385,4 +388,24 @@ def _deleteJobRequest(**kwargs):
return jsonify(retVal)
except Exception as err:
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