add addWorker and deletWorker

This commit is contained in:
Tim Gröger 2020-01-18 23:31:49 +01:00
parent d61a97387c
commit 754f373cb0
11 changed files with 161 additions and 30 deletions

View File

@ -21,8 +21,10 @@ from geruecht import routes
from geruecht.baruser.routes import baruser
from geruecht.finanzer.routes import finanzer
from geruecht.user.routes import user
from geruecht.vorstand.routes import vorstand
LOGGER.info("Registrate bluebrints")
app.register_blueprint(baruser)
app.register_blueprint(finanzer)
app.register_blueprint(user)
app.register_blueprint(vorstand)

View File

@ -18,7 +18,7 @@ def _bar():
print(request.headers)
token = request.headers.get("Token")
print(token)
accToken = accesTokenController.validateAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, [BAR])
dic = {}
if accToken:
@ -57,7 +57,7 @@ def _baradd():
"""
token = request.headers.get("Token")
print(token)
accToken = accesTokenController.validateAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, [BAR])
if accToken:
data = request.get_json()
@ -94,7 +94,7 @@ def _getUsers():
"""
token = request.headers.get("Token")
print(token)
accToken = accesTokenController.validateAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, [BAR])
retVal = {}
if accToken:
@ -105,7 +105,7 @@ def _getUsers():
@baruser.route("/barGetUser", methods=['POST'])
def _getUser():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, [BAR])
if accToken:
data = request.get_json()
username = data['userId']
@ -126,10 +126,9 @@ def _getUser():
def _search():
token = request.headers.get("Token")
print(token)
accToken = accesTokenController.validateAccessToken(token, BAR)
accToken2 = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [BAR, MONEY])
if accToken or accToken2:
if accToken:
data = request.get_json()
searchString = data['searchString']

View File

@ -36,8 +36,14 @@ mailConfig = config.getMail()
db = DatabaseController(dbConfig['URL'], dbConfig['user'], dbConfig['passwd'], dbConfig['database'])
ldapController = LDAPController(ldapConfig['URL'], ldapConfig['dn'])
accesTokenController = AccesTokenController(accConfig)
from . emailController import EmailController
emailController = EmailController(mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['port'], mailConfig['email'])
from . userController import UserController
userController = UserController()
def getUserController():
if userController is not None:
return userController
else:
return UserController()
userController = UserController()
accesTokenController = AccesTokenController(accConfig)

View File

@ -1,9 +1,12 @@
from geruecht.model.accessToken import AccessToken
#import geruecht.controller.userController as userController
from geruecht.model import BAR
from geruecht.controller import LOGGER
from datetime import datetime, timedelta
import hashlib
from . import Singleton
class AccesTokenController(metaclass=Singleton):
""" Control all createt AccesToken
@ -26,6 +29,12 @@ class AccesTokenController(metaclass=Singleton):
self.tokenList = []
#def checkBar(self, user):
# if (userController.checkBarUser(user)):
# user.group.append(BAR)
# elif BAR in user.group:
# user.group.remove(BAR)
def validateAccessToken(self, token, group):
""" Verify Accestoken
@ -47,6 +56,7 @@ class AccesTokenController(metaclass=Singleton):
now = datetime.now()
LOGGER.debug("Check if AccessToken's Endtime {} is bigger then now {}".format(endTime, now))
if now <= endTime:
self.checkBar(accToken.user)
LOGGER.debug("Check if AccesToken {} has same group {}".format(accToken, group))
if self.isSameGroup(accToken, group):
accToken.updateTimestamp()
@ -72,24 +82,27 @@ class AccesTokenController(metaclass=Singleton):
LOGGER.info("Create AccessToken")
now = datetime.ctime(datetime.now())
token = hashlib.md5((now + user.dn).encode('utf-8')).hexdigest()
self.checkBar(user)
accToken = AccessToken(user, token, datetime.now())
LOGGER.debug("Add AccessToken {} to current Tokens".format(accToken))
self.tokenList.append(accToken)
LOGGER.info("Finished create AccessToken {} with Token {}".format(accToken, token))
return token
def isSameGroup(self, accToken, group):
def isSameGroup(self, accToken, groups):
""" Verify group in AccessToken
Verify if the User in the AccesToken has the right group.
Args:
accToken: AccessToken to verify.
group: Group to verify.
groups: Group to verify.
Returns:
A Bool. If the same then True else False
"""
print("controll if", accToken, "hase group", group)
LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, group))
return True if group in accToken.user.group else False
print("controll if", accToken, "hase groups", groups)
LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, groups))
for group in groups:
if group in accToken.user.group: return True
return False

View File

@ -2,7 +2,7 @@ import pymysql
from . import Singleton
from geruecht.model.user import User
from geruecht.model.creditList import CreditList
from datetime import datetime
from datetime import datetime, timedelta
class DatabaseController(metaclass=Singleton):
'''
@ -61,6 +61,22 @@ class DatabaseController(metaclass=Singleton):
return retVal
def getUserById(self, id):
self.connect()
retVal = None
try:
cursor = self.db.cursor()
cursor.execute("select * from user where id={}".format(id))
data = cursor.fetchone()
self.db.close()
except Exception as err:
raise err
if data:
retVal = User(data)
creditLists = self.getCreditListFromUser(retVal)
retVal.initGeruechte(creditLists)
return retVal
def _convertGroupToString(self, groups):
retVal = ''
for group in groups:
@ -164,6 +180,52 @@ class DatabaseController(metaclass=Singleton):
self.db.close()
raise err
def getWorker(self, user, date):
self.connect()
try:
cursor = self.db.cursor()
cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
data = cursor.fetchone()
self.db.close()
except Exception as err:
raise err
return {"user": user, "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']}
def getWorkers(self, date):
self.connect()
try:
cursor = self.db.cursor()
cursor.execute("select * from bardienste where startdatetime='{}'".format(date))
data = cursor.fetchall()
self.db.close()
except Exception as err:
raise err
return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime']} for work in data]
def setWorker(self, user, date):
self.connect()
try:
cursor = self.db.cursor()
cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime) values ({},'{}','{}')".format(user.id, date, date + timedelta(days=1)))
self.db.commit()
self.db.close()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
def deleteWorker(self, user, date):
self.connect()
try:
cursor = self.db.cursor()
cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
self.db.commit()
self.db.close()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
if __name__ == '__main__':
db = DatabaseController()

View File

@ -1,13 +1,28 @@
from . import LOGGER, Singleton, db, ldapController as ldap, emailController
from geruecht.model.user import User
from geruecht.exceptions import PermissionDenied
from datetime import datetime
from datetime import datetime, timedelta
class UserController(metaclass=Singleton):
def __init__(self):
pass
def getWorker(self, date, username=None):
if (username):
user = self.getUser(username)
return [db.getWorker(user, date)]
return db.getWorkers(date)
def addWorker(self, username, date):
user = self.getUser(username)
if (not db.getWorker(user, date)):
db.setWorker(user, date)
def deleteWorker(self, username, date):
user = self.getUser(username)
db.setWorker(user, date)
def lockUser(self, username, locked):
user = self.getUser(username)
user.updateData({'locked': locked})
@ -54,6 +69,16 @@ class UserController(metaclass=Singleton):
self.__updateGeruechte(user)
return db.getAllUser()
def checkBarUser(self, user):
date = datetime.now()
startdatetime = date.replace(hour=11, minute=0, microsecond=0)
enddatetime = startdatetime + timedelta(days=1)
result = False
if date >= startdatetime and date < enddatetime:
result = db.getWorker(user, startdatetime)
return True if result else False
def getUser(self, username):
user = db.getUser(username)
groups = ldap.getGroup(username)

View File

@ -20,7 +20,7 @@ def _getFinanzer():
LOGGER.info("Get main for Finanzer")
token = request.headers.get("Token")
LOGGER.debug("Verify AccessToken with Token {}".format(token))
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
LOGGER.debug("Get all Useres")
users = userController.getAllUsersfromDB()
@ -50,7 +50,7 @@ def _addAmount():
LOGGER.info("Add Amount")
token = request.headers.get("Token")
LOGGER.debug("Verify AccessToken with Token {}".format(token))
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
data = request.get_json()
@ -93,7 +93,7 @@ def _addCredit():
LOGGER.info("Add Amount")
token = request.headers.get("Token")
LOGGER.debug("Verify AccessToken with Token {}".format(token))
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
@ -128,7 +128,7 @@ def _addCredit():
@finanzer.route("/finanzerLock", methods=['POST'])
def _finanzerLock():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
data = request.get_json()
@ -141,7 +141,7 @@ def _finanzerLock():
@finanzer.route("/finanzerSetConfig", methods=['POST'])
def _finanzerSetConfig():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
data = request.get_json()
@ -155,7 +155,7 @@ def _finanzerSetConfig():
@finanzer.route("/finanzerAddUser", methods=['POST'])
def _finanzerAddUser():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
data = request.get_json()
@ -175,7 +175,7 @@ def _finanzerAddUser():
@finanzer.route("/finanzerSendOneMail", methods=['POST'])
def _finanzerSendOneMail():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
data = request.get_json()
@ -187,7 +187,7 @@ def _finanzerSendOneMail():
@finanzer.route("/finanzerSendAllMail", methods=['GET'])
def _finanzerSendAllMail():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
retVal = userController.sendAllMail()

View File

@ -12,16 +12,16 @@ def login(user, password):
@app.route("/valid")
def _valid():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, MONEY)
accToken = accesTokenController.validateAccessToken(token, [MONEY])
if accToken:
return jsonify(accToken.user.toJSON())
accToken = accesTokenController.validateAccessToken(token, BAR)
accToken = accesTokenController.validateAccessToken(token, [BAR])
if accToken:
return jsonify(accToken.user.toJSON())
accToken = accesTokenController.validateAccessToken(token, GASTRO)
accToken = accesTokenController.validateAccessToken(token, [GASTRO])
if accToken:
return jsonify(accToken.user.toJSON())
accToken = accesTokenController.validateAccessToken(token, USER)
accToken = accesTokenController.validateAccessToken(token, [USER])
if accToken:
return jsonify(accToken.user.toJSON())
return jsonify({"error": "permission denied"}), 401

View File

@ -9,7 +9,7 @@ user = Blueprint("user", __name__)
def _main():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, USER)
accToken = accesTokenController.validateAccessToken(token, [USER])
if accToken:
accToken.user = userController.getUser(accToken.user.uid)
retVal = accToken.user.toJSON()
@ -21,7 +21,7 @@ def _main():
def _addAmount():
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, USER)
accToken = accesTokenController.validateAccessToken(token, [USER])
if accToken:
data = request.get_json()
amount = int(data['amount'])

View File

View File

@ -0,0 +1,24 @@
from flask import Blueprint, request, jsonify
from datetime import datetime
from geruecht.controller import accesTokenController, userController
from geruecht.model import MONEY, GASTRO
vorstand = Blueprint("vorstand", __name__)
@vorstand.route("/sm/addUser", methods=['POST', 'GET'])
def _addUser():
if request.method == 'GET':
return "<h1>HEllo World</h1>"
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, [MONEY, GASTRO])
if accToken:
data = request.get_json()
user = data['user']
date = datetime.utcfromtimestamp(int(data['date']))
userController.addWorker(user['username'], date)
print(data)
return jsonify({"date": date})
return jsonify({"error": "permission denied"}), 401