Merge branch 'feature/dienstverwaltung' into develop
This commit is contained in:
commit
f7d3b17680
|
@ -5,6 +5,8 @@
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from .logger import getLogger
|
from .logger import getLogger
|
||||||
|
from geruecht.controller import dbConfig
|
||||||
|
from flask_mysqldb import MySQL
|
||||||
|
|
||||||
LOGGER = getLogger(__name__)
|
LOGGER = getLogger(__name__)
|
||||||
LOGGER.info("Initialize App")
|
LOGGER.info("Initialize App")
|
||||||
|
@ -15,14 +17,22 @@ from flask_cors import CORS
|
||||||
LOGGER.info("Build APP")
|
LOGGER.info("Build APP")
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
CORS(app)
|
CORS(app)
|
||||||
# app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
|
app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
|
||||||
|
app.config['MYSQL_HOST'] = dbConfig['URL']
|
||||||
|
app.config['MYSQL_USER'] = dbConfig['user']
|
||||||
|
app.config['MYSQL_PASSWORD'] = dbConfig['passwd']
|
||||||
|
app.config['MYSQL_DB'] = dbConfig['database']
|
||||||
|
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
|
||||||
|
db = MySQL(app)
|
||||||
|
|
||||||
from geruecht import routes
|
from geruecht import routes
|
||||||
from geruecht.baruser.routes import baruser
|
from geruecht.baruser.routes import baruser
|
||||||
from geruecht.finanzer.routes import finanzer
|
from geruecht.finanzer.routes import finanzer
|
||||||
from geruecht.user.routes import user
|
from geruecht.user.routes import user
|
||||||
|
from geruecht.vorstand.routes import vorstand
|
||||||
|
|
||||||
LOGGER.info("Registrate bluebrints")
|
LOGGER.info("Registrate bluebrints")
|
||||||
app.register_blueprint(baruser)
|
app.register_blueprint(baruser)
|
||||||
app.register_blueprint(finanzer)
|
app.register_blueprint(finanzer)
|
||||||
app.register_blueprint(user)
|
app.register_blueprint(user)
|
||||||
|
app.register_blueprint(vorstand)
|
||||||
|
|
|
@ -1,12 +1,20 @@
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
from geruecht.controller import ldapController as ldap, accesTokenController, userController
|
import geruecht.controller as gc
|
||||||
|
import geruecht.controller.ldapController as lc
|
||||||
|
import geruecht.controller.userController as uc
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from geruecht.model import BAR, MONEY
|
from geruecht.model import BAR, MONEY
|
||||||
|
from geruecht.decorator import login_required
|
||||||
|
|
||||||
baruser = Blueprint("baruser", __name__)
|
baruser = Blueprint("baruser", __name__)
|
||||||
|
|
||||||
|
ldap= lc.LDAPController(gc.ldapConfig['URL'], gc.ldapConfig['dn'])
|
||||||
|
userController = uc.UserController()
|
||||||
|
|
||||||
|
|
||||||
@baruser.route("/bar")
|
@baruser.route("/bar")
|
||||||
def _bar():
|
@login_required(groups=[BAR])
|
||||||
|
def _bar(**kwargs):
|
||||||
""" Main function for Baruser
|
""" Main function for Baruser
|
||||||
|
|
||||||
Returns JSON-file with all Users, who hast amounts in this month.
|
Returns JSON-file with all Users, who hast amounts in this month.
|
||||||
|
@ -15,13 +23,7 @@ def _bar():
|
||||||
JSON-File with Users, who has amounts in this month
|
JSON-File with Users, who has amounts in this month
|
||||||
or ERROR 401 Permission Denied
|
or ERROR 401 Permission Denied
|
||||||
"""
|
"""
|
||||||
print(request.headers)
|
|
||||||
token = request.headers.get("Token")
|
|
||||||
print(token)
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, BAR)
|
|
||||||
|
|
||||||
dic = {}
|
dic = {}
|
||||||
if accToken:
|
|
||||||
users = userController.getAllUsersfromDB()
|
users = userController.getAllUsersfromDB()
|
||||||
for user in users:
|
for user in users:
|
||||||
geruecht = None
|
geruecht = None
|
||||||
|
@ -43,10 +45,11 @@ def _bar():
|
||||||
"type": type
|
"type": type
|
||||||
}
|
}
|
||||||
return jsonify(dic)
|
return jsonify(dic)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@baruser.route("/baradd", methods=['POST'])
|
@baruser.route("/baradd", methods=['POST'])
|
||||||
def _baradd():
|
@login_required(groups=[BAR])
|
||||||
|
def _baradd(**kwargs):
|
||||||
""" Function for Baruser to add amount
|
""" Function for Baruser to add amount
|
||||||
|
|
||||||
This function added to the user with the posted userID the posted amount.
|
This function added to the user with the posted userID the posted amount.
|
||||||
|
@ -55,11 +58,6 @@ def _baradd():
|
||||||
JSON-File with userID and the amount
|
JSON-File with userID and the amount
|
||||||
or ERROR 401 Permission Denied
|
or ERROR 401 Permission Denied
|
||||||
"""
|
"""
|
||||||
token = request.headers.get("Token")
|
|
||||||
print(token)
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, BAR)
|
|
||||||
|
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
userID = data['userId']
|
userID = data['userId']
|
||||||
amount = int(data['amount'])
|
amount = int(data['amount'])
|
||||||
|
@ -80,10 +78,11 @@ def _baradd():
|
||||||
dic['type'] = type
|
dic['type'] = type
|
||||||
|
|
||||||
return jsonify(dic)
|
return jsonify(dic)
|
||||||
return jsonify({"error", "permission denied"}), 401
|
|
||||||
|
|
||||||
@baruser.route("/barGetUsers")
|
@baruser.route("/barGetUsers")
|
||||||
def _getUsers():
|
@login_required(groups=[BAR, MONEY])
|
||||||
|
def _getUsers(**kwargs):
|
||||||
""" Get Users without amount
|
""" Get Users without amount
|
||||||
|
|
||||||
This Function returns all Users, who hasn't an amount in this month.
|
This Function returns all Users, who hasn't an amount in this month.
|
||||||
|
@ -92,21 +91,14 @@ def _getUsers():
|
||||||
JSON-File with Users
|
JSON-File with Users
|
||||||
or ERROR 401 Permission Denied
|
or ERROR 401 Permission Denied
|
||||||
"""
|
"""
|
||||||
token = request.headers.get("Token")
|
|
||||||
print(token)
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, BAR)
|
|
||||||
|
|
||||||
retVal = {}
|
retVal = {}
|
||||||
if accToken:
|
|
||||||
retVal = ldap.getAllUser()
|
retVal = ldap.getAllUser()
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@baruser.route("/barGetUser", methods=['POST'])
|
@baruser.route("/barGetUser", methods=['POST'])
|
||||||
def _getUser():
|
@login_required(groups=[BAR])
|
||||||
token = request.headers.get("Token")
|
def _getUser(**kwargs):
|
||||||
accToken = accesTokenController.validateAccessToken(token, BAR)
|
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
username = data['userId']
|
username = data['userId']
|
||||||
user = userController.getUser(username)
|
user = userController.getUser(username)
|
||||||
|
@ -120,21 +112,12 @@ def _getUser():
|
||||||
retVal['amount'] = amount
|
retVal['amount'] = amount
|
||||||
retVal['type'] = type
|
retVal['type'] = type
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify("error", "permission denied"), 401
|
|
||||||
|
|
||||||
@baruser.route("/search", methods=['POST'])
|
@baruser.route("/search", methods=['POST'])
|
||||||
def _search():
|
@login_required(groups=[BAR, MONEY])
|
||||||
token = request.headers.get("Token")
|
def _search(**kwargs):
|
||||||
print(token)
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, BAR)
|
|
||||||
accToken2 = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
if accToken or accToken2:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
|
||||||
searchString = data['searchString']
|
searchString = data['searchString']
|
||||||
|
|
||||||
retVal = ldap.searchUser(searchString)
|
retVal = ldap.searchUser(searchString)
|
||||||
|
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
import yaml
|
import yaml
|
||||||
import sys
|
import sys
|
||||||
from . import LOGGER
|
from .logger import getLogger
|
||||||
|
LOGGER = getLogger(__name__)
|
||||||
|
|
||||||
default = {
|
default = {
|
||||||
'AccessTokenLifeTime': 1800,
|
'AccessTokenLifeTime': 1800,
|
||||||
|
@ -34,7 +35,7 @@ class ConifgParser():
|
||||||
self.ldap = self.config['LDAP']
|
self.ldap = self.config['LDAP']
|
||||||
LOGGER.info("Set LDAPconfig: {}".format(self.ldap))
|
LOGGER.info("Set LDAPconfig: {}".format(self.ldap))
|
||||||
if 'AccessTokenLifeTime' in self.config:
|
if 'AccessTokenLifeTime' in self.config:
|
||||||
self.accessTokenLifeTime = self.config['AccessTokenLifeTime']
|
self.accessTokenLifeTime = int(self.config['AccessTokenLifeTime'])
|
||||||
LOGGER.info("Set AccessTokenLifeTime: {}".format(self.accessTokenLifeTime))
|
LOGGER.info("Set AccessTokenLifeTime: {}".format(self.accessTokenLifeTime))
|
||||||
else:
|
else:
|
||||||
self.accessTokenLifeTime = default['AccessTokenLifeTime']
|
self.accessTokenLifeTime = default['AccessTokenLifeTime']
|
||||||
|
|
|
@ -15,29 +15,7 @@ class Singleton(type):
|
||||||
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
||||||
return cls._instances[cls]
|
return cls._instances[cls]
|
||||||
|
|
||||||
from .databaseController import DatabaseController
|
|
||||||
def getDatabesController():
|
|
||||||
if db is not None:
|
|
||||||
return db
|
|
||||||
else:
|
|
||||||
return DatabaseController(dbConfig['URL'], dbConfig['user'], dbConfig['passwd'], dbConfig['database'])
|
|
||||||
from .ldapController import LDAPController
|
|
||||||
def getLDAPController():
|
|
||||||
if ldapController is not None:
|
|
||||||
return ldapController
|
|
||||||
else:
|
|
||||||
return LDAPController(ldapConfig['URL'], ldapConfig['dn'])
|
|
||||||
from .accesTokenController import AccesTokenController
|
|
||||||
|
|
||||||
dbConfig = config.getDatabase()
|
dbConfig = config.getDatabase()
|
||||||
ldapConfig = config.getLDAP()
|
ldapConfig = config.getLDAP()
|
||||||
accConfig = config.getAccessToken()
|
accConfig = config.getAccessToken()
|
||||||
mailConfig = config.getMail()
|
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()
|
|
|
@ -1,9 +1,14 @@
|
||||||
from geruecht.model.accessToken import AccessToken
|
from geruecht.model.accessToken import AccessToken
|
||||||
|
import geruecht.controller as gc
|
||||||
|
import geruecht.controller.userController as uc
|
||||||
|
from geruecht.model import BAR
|
||||||
from geruecht.controller import LOGGER
|
from geruecht.controller import LOGGER
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import hashlib
|
import hashlib
|
||||||
from . import Singleton
|
from . import Singleton
|
||||||
|
|
||||||
|
userController = uc.UserController()
|
||||||
|
|
||||||
class AccesTokenController(metaclass=Singleton):
|
class AccesTokenController(metaclass=Singleton):
|
||||||
""" Control all createt AccesToken
|
""" Control all createt AccesToken
|
||||||
|
|
||||||
|
@ -22,10 +27,16 @@ class AccesTokenController(metaclass=Singleton):
|
||||||
Initialize Thread and set tokenList empty.
|
Initialize Thread and set tokenList empty.
|
||||||
"""
|
"""
|
||||||
LOGGER.info("Initialize AccessTokenController")
|
LOGGER.info("Initialize AccessTokenController")
|
||||||
self.lifetime = lifetime
|
self.lifetime = gc.accConfig
|
||||||
|
|
||||||
self.tokenList = []
|
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):
|
def validateAccessToken(self, token, group):
|
||||||
""" Verify Accestoken
|
""" Verify Accestoken
|
||||||
|
|
||||||
|
@ -47,6 +58,7 @@ class AccesTokenController(metaclass=Singleton):
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
LOGGER.debug("Check if AccessToken's Endtime {} is bigger then now {}".format(endTime, now))
|
LOGGER.debug("Check if AccessToken's Endtime {} is bigger then now {}".format(endTime, now))
|
||||||
if now <= endTime:
|
if now <= endTime:
|
||||||
|
self.checkBar(accToken.user)
|
||||||
LOGGER.debug("Check if AccesToken {} has same group {}".format(accToken, group))
|
LOGGER.debug("Check if AccesToken {} has same group {}".format(accToken, group))
|
||||||
if self.isSameGroup(accToken, group):
|
if self.isSameGroup(accToken, group):
|
||||||
accToken.updateTimestamp()
|
accToken.updateTimestamp()
|
||||||
|
@ -72,24 +84,27 @@ class AccesTokenController(metaclass=Singleton):
|
||||||
LOGGER.info("Create AccessToken")
|
LOGGER.info("Create AccessToken")
|
||||||
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)
|
||||||
accToken = AccessToken(user, token, datetime.now())
|
accToken = AccessToken(user, token, datetime.now())
|
||||||
LOGGER.debug("Add AccessToken {} to current Tokens".format(accToken))
|
LOGGER.debug("Add AccessToken {} to current Tokens".format(accToken))
|
||||||
self.tokenList.append(accToken)
|
self.tokenList.append(accToken)
|
||||||
LOGGER.info("Finished create AccessToken {} with Token {}".format(accToken, token))
|
LOGGER.info("Finished create AccessToken {} with Token {}".format(accToken, token))
|
||||||
return token
|
return token
|
||||||
|
|
||||||
def isSameGroup(self, accToken, group):
|
def isSameGroup(self, accToken, groups):
|
||||||
""" Verify group in AccessToken
|
""" Verify group in AccessToken
|
||||||
|
|
||||||
Verify if the User in the AccesToken has the right group.
|
Verify if the User in the AccesToken has the right group.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
accToken: AccessToken to verify.
|
accToken: AccessToken to verify.
|
||||||
group: Group to verify.
|
groups: Group to verify.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A Bool. If the same then True else False
|
A Bool. If the same then True else False
|
||||||
"""
|
"""
|
||||||
print("controll if", accToken, "hase group", group)
|
print("controll if", accToken, "hase groups", groups)
|
||||||
LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, group))
|
LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, groups))
|
||||||
return True if group in accToken.user.group else False
|
for group in groups:
|
||||||
|
if group in accToken.user.group: return True
|
||||||
|
return False
|
||||||
|
|
|
@ -1,8 +1,9 @@
|
||||||
import pymysql
|
import pymysql
|
||||||
from . import Singleton
|
from . import Singleton
|
||||||
|
from geruecht import db
|
||||||
from geruecht.model.user import User
|
from geruecht.model.user import User
|
||||||
from geruecht.model.creditList import CreditList
|
from geruecht.model.creditList import CreditList
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
class DatabaseController(metaclass=Singleton):
|
class DatabaseController(metaclass=Singleton):
|
||||||
'''
|
'''
|
||||||
|
@ -11,29 +12,13 @@ class DatabaseController(metaclass=Singleton):
|
||||||
Connect to the Database and execute sql-executions
|
Connect to the Database and execute sql-executions
|
||||||
'''
|
'''
|
||||||
|
|
||||||
def __init__(self, url='192.168.5.108', user='wu5', password='E1n$tein', database='geruecht'):
|
def __init__(self):
|
||||||
self.url = url
|
self.db = db
|
||||||
self.user = user
|
|
||||||
self.password = password
|
|
||||||
self.database = database
|
|
||||||
self.connect()
|
|
||||||
|
|
||||||
|
|
||||||
def connect(self):
|
|
||||||
try:
|
|
||||||
self.db = pymysql.connect(self.url, self.user, self.password, self.database, cursorclass=pymysql.cursors.DictCursor)
|
|
||||||
except Exception as err:
|
|
||||||
raise err
|
|
||||||
|
|
||||||
def getAllUser(self):
|
def getAllUser(self):
|
||||||
self.connect()
|
cursor = self.db.connection.cursor()
|
||||||
cursor = self.db.cursor()
|
|
||||||
try:
|
|
||||||
cursor.execute("select * from user")
|
cursor.execute("select * from user")
|
||||||
data = cursor.fetchall()
|
data = cursor.fetchall()
|
||||||
self.db.close()
|
|
||||||
except Exception as err:
|
|
||||||
raise err
|
|
||||||
|
|
||||||
if data:
|
if data:
|
||||||
retVal = []
|
retVal = []
|
||||||
|
@ -45,15 +30,10 @@ class DatabaseController(metaclass=Singleton):
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def getUser(self, username):
|
def getUser(self, username):
|
||||||
self.connect()
|
|
||||||
retVal = None
|
retVal = None
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
try:
|
|
||||||
cursor.execute("select * from user where uid='{}'".format(username))
|
cursor.execute("select * from user where uid='{}'".format(username))
|
||||||
data = cursor.fetchone()
|
data = cursor.fetchone()
|
||||||
self.db.close()
|
|
||||||
except Exception as err:
|
|
||||||
raise err
|
|
||||||
if data:
|
if data:
|
||||||
retVal = User(data)
|
retVal = User(data)
|
||||||
creditLists = self.getCreditListFromUser(retVal)
|
creditLists = self.getCreditListFromUser(retVal)
|
||||||
|
@ -61,6 +41,17 @@ class DatabaseController(metaclass=Singleton):
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
|
def getUserById(self, id):
|
||||||
|
retVal = None
|
||||||
|
cursor = self.db.connection.cursor()
|
||||||
|
cursor.execute("select * from user where id={}".format(id))
|
||||||
|
data = cursor.fetchone()
|
||||||
|
if data:
|
||||||
|
retVal = User(data)
|
||||||
|
creditLists = self.getCreditListFromUser(retVal)
|
||||||
|
retVal.initGeruechte(creditLists)
|
||||||
|
return retVal
|
||||||
|
|
||||||
def _convertGroupToString(self, groups):
|
def _convertGroupToString(self, groups):
|
||||||
retVal = ''
|
retVal = ''
|
||||||
for group in groups:
|
for group in groups:
|
||||||
|
@ -69,75 +60,49 @@ class DatabaseController(metaclass=Singleton):
|
||||||
retVal += group
|
retVal += group
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
|
|
||||||
def insertUser(self, user):
|
def insertUser(self, user):
|
||||||
self.connect()
|
cursor = self.db.connection.cursor()
|
||||||
cursor = self.db.cursor()
|
|
||||||
groups = self._convertGroupToString(user.group)
|
groups = self._convertGroupToString(user.group)
|
||||||
try:
|
|
||||||
cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe, lockLimit, locked, autoLock, mail) VALUES ('{}','{}','{}','{}','{}',{},{},{},'{}')".format(
|
cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe, lockLimit, locked, autoLock, mail) VALUES ('{}','{}','{}','{}','{}',{},{},{},'{}')".format(
|
||||||
user.uid, user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail))
|
user.uid, user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail))
|
||||||
self.db.commit()
|
self.db.connection.commit()
|
||||||
except Exception as err:
|
|
||||||
self.db.rollback()
|
|
||||||
self.db.close()
|
|
||||||
raise err
|
|
||||||
self.db.close()
|
|
||||||
|
|
||||||
def updateUser(self, user):
|
def updateUser(self, user):
|
||||||
self.connect()
|
cursor = self.db.connection.cursor()
|
||||||
cursor = self.db.cursor()
|
|
||||||
groups = self._convertGroupToString(user.group)
|
groups = self._convertGroupToString(user.group)
|
||||||
try:
|
|
||||||
sql = "update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}', lockLimit={}, locked={}, autoLock={}, mail='{}' where uid='{}'".format(
|
sql = "update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}', lockLimit={}, locked={}, autoLock={}, mail='{}' where uid='{}'".format(
|
||||||
user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail, user.uid)
|
user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail, user.uid)
|
||||||
print(sql)
|
print(sql)
|
||||||
cursor.execute(sql)
|
cursor.execute(sql)
|
||||||
self.db.commit()
|
self.db.connection.commit()
|
||||||
except Exception as err:
|
|
||||||
self.db.rollback()
|
|
||||||
self.db.close()
|
|
||||||
print(err.__traceback__)
|
|
||||||
raise err
|
|
||||||
|
|
||||||
self.db.close()
|
|
||||||
|
|
||||||
def getCreditListFromUser(self, user, **kwargs):
|
def getCreditListFromUser(self, user, **kwargs):
|
||||||
self.connect()
|
cursor = self.db.connection.cursor()
|
||||||
cursor = self.db.cursor()
|
|
||||||
try:
|
|
||||||
if 'year' in kwargs:
|
if 'year' in kwargs:
|
||||||
sql = "select * from creditList where user_id={} and year_date={}".format(user.id, kwargs['year'])
|
sql = "select * from creditList where user_id={} and year_date={}".format(user.id, kwargs['year'])
|
||||||
else:
|
else:
|
||||||
sql = "select * from creditList where user_id={}".format(user.id)
|
sql = "select * from creditList where user_id={}".format(user.id)
|
||||||
cursor.execute(sql)
|
cursor.execute(sql)
|
||||||
data = cursor.fetchall()
|
data = cursor.fetchall()
|
||||||
self.db.close()
|
|
||||||
except Exception as err:
|
|
||||||
self.db.close()
|
|
||||||
raise err
|
|
||||||
if len(data) == 1:
|
if len(data) == 1:
|
||||||
return [CreditList(data[0])]
|
return [CreditList(data[0])]
|
||||||
else:
|
else:
|
||||||
return [CreditList(value) for value in data]
|
return [CreditList(value) for value in data]
|
||||||
|
|
||||||
|
|
||||||
def createCreditList(self, user_id, year=datetime.now().year):
|
def createCreditList(self, user_id, year=datetime.now().year):
|
||||||
self.connect()
|
cursor = self.db.connection.cursor()
|
||||||
cursor = self.db.cursor()
|
|
||||||
try:
|
|
||||||
cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id))
|
cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id))
|
||||||
self.db.commit()
|
self.db.connection.commit()
|
||||||
self.db.close()
|
|
||||||
except Exception as err:
|
|
||||||
self.db.close()
|
|
||||||
raise err
|
|
||||||
|
|
||||||
def updateCreditList(self, creditlist):
|
def updateCreditList(self, creditlist):
|
||||||
self.connect()
|
cursor = self.db.connection.cursor()
|
||||||
cursor = self.db.cursor()
|
|
||||||
try:
|
|
||||||
cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year))
|
cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year))
|
||||||
data = cursor.fetchall()
|
data = cursor.fetchall()
|
||||||
self.db.close()
|
|
||||||
if len(data) == 0:
|
if len(data) == 0:
|
||||||
self.createCreditList(creditlist.user_id, creditlist.year)
|
self.createCreditList(creditlist.user_id, creditlist.year)
|
||||||
sql = "update creditList set jan_guthaben={}, jan_schulden={},feb_guthaben={}, feb_schulden={}, maer_guthaben={}, maer_schulden={}, apr_guthaben={}, apr_schulden={}, mai_guthaben={}, mai_schulden={}, jun_guthaben={}, jun_schulden={}, jul_guthaben={}, jul_schulden={}, aug_guthaben={}, aug_schulden={},sep_guthaben={}, sep_schulden={},okt_guthaben={}, okt_schulden={}, nov_guthaben={}, nov_schulden={}, dez_guthaben={}, dez_schulden={}, last_schulden={} where year_date={} and user_id={}".format(creditlist.jan_guthaben, creditlist.jan_schulden,
|
sql = "update creditList set jan_guthaben={}, jan_schulden={},feb_guthaben={}, feb_schulden={}, maer_guthaben={}, maer_schulden={}, apr_guthaben={}, apr_schulden={}, mai_guthaben={}, mai_schulden={}, jun_guthaben={}, jun_schulden={}, jul_guthaben={}, jul_schulden={}, aug_guthaben={}, aug_schulden={},sep_guthaben={}, sep_schulden={},okt_guthaben={}, okt_schulden={}, nov_guthaben={}, nov_schulden={}, dez_guthaben={}, dez_schulden={}, last_schulden={} where year_date={} and user_id={}".format(creditlist.jan_guthaben, creditlist.jan_schulden,
|
||||||
|
@ -154,16 +119,34 @@ class DatabaseController(metaclass=Singleton):
|
||||||
creditlist.dez_guthaben, creditlist.dez_schulden,
|
creditlist.dez_guthaben, creditlist.dez_schulden,
|
||||||
creditlist.last_schulden, creditlist.year, creditlist.user_id)
|
creditlist.last_schulden, creditlist.year, creditlist.user_id)
|
||||||
print(sql)
|
print(sql)
|
||||||
self.connect()
|
cursor = self.db.connection.cursor()
|
||||||
cursor = self.db.cursor()
|
|
||||||
cursor.execute(sql)
|
cursor.execute(sql)
|
||||||
self.db.commit()
|
self.db.connection.commit()
|
||||||
self.db.close()
|
|
||||||
except Exception as err:
|
|
||||||
self.db.rollback()
|
|
||||||
self.db.close()
|
|
||||||
raise err
|
|
||||||
|
|
||||||
|
def getWorker(self, user, date):
|
||||||
|
cursor = self.db.connection.cursor()
|
||||||
|
cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
|
||||||
|
data = cursor.fetchone()
|
||||||
|
return {"user": user.toJSON(), "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None
|
||||||
|
|
||||||
|
|
||||||
|
def getWorkers(self, date):
|
||||||
|
cursor = self.db.connection.cursor()
|
||||||
|
cursor.execute("select * from bardienste where startdatetime='{}'".format(date))
|
||||||
|
data = cursor.fetchall()
|
||||||
|
return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime']} for work in data]
|
||||||
|
|
||||||
|
|
||||||
|
def setWorker(self, user, date):
|
||||||
|
cursor = self.db.connection.cursor()
|
||||||
|
cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime) values ({},'{}','{}')".format(user.id, date, date + timedelta(days=1)))
|
||||||
|
self.db.connection.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def deleteWorker(self, user, date):
|
||||||
|
cursor = self.db.connection.cursor()
|
||||||
|
cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
|
||||||
|
self.db.connection.commit()
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
db = DatabaseController()
|
db = DatabaseController()
|
||||||
|
|
|
@ -1,13 +1,36 @@
|
||||||
from . import LOGGER, Singleton, db, ldapController as ldap, emailController
|
from . import LOGGER, Singleton, ldapConfig, dbConfig, mailConfig
|
||||||
|
import geruecht.controller.databaseController as dc
|
||||||
|
import geruecht.controller.ldapController as lc
|
||||||
|
import geruecht.controller.emailController as ec
|
||||||
from geruecht.model.user import User
|
from geruecht.model.user import User
|
||||||
from geruecht.exceptions import PermissionDenied
|
from geruecht.exceptions import PermissionDenied
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
db = dc.DatabaseController()
|
||||||
|
ldap = lc.LDAPController(ldapConfig['URL'], ldapConfig['dn'])
|
||||||
|
emailController = ec.EmailController(mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['port'], mailConfig['email'])
|
||||||
|
|
||||||
class UserController(metaclass=Singleton):
|
class UserController(metaclass=Singleton):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
pass
|
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)
|
||||||
|
return self.getWorker(date, username=username)
|
||||||
|
|
||||||
|
def deleteWorker(self, username, date):
|
||||||
|
user = self.getUser(username)
|
||||||
|
db.deleteWorker(user, date)
|
||||||
|
|
||||||
def lockUser(self, username, locked):
|
def lockUser(self, username, locked):
|
||||||
user = self.getUser(username)
|
user = self.getUser(username)
|
||||||
user.updateData({'locked': locked})
|
user.updateData({'locked': locked})
|
||||||
|
@ -54,6 +77,20 @@ class UserController(metaclass=Singleton):
|
||||||
self.__updateGeruechte(user)
|
self.__updateGeruechte(user)
|
||||||
return db.getAllUser()
|
return db.getAllUser()
|
||||||
|
|
||||||
|
def checkBarUser(self, user):
|
||||||
|
date = datetime.now()
|
||||||
|
zero = date.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||||
|
end = zero + timedelta(hours=11)
|
||||||
|
startdatetime = date.replace(hour=11, minute=0, second=0, microsecond=0)
|
||||||
|
if date > zero and end > date:
|
||||||
|
startdatetime = startdatetime - timedelta(days=1)
|
||||||
|
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):
|
def getUser(self, username):
|
||||||
user = db.getUser(username)
|
user = db.getUser(username)
|
||||||
groups = ldap.getGroup(username)
|
groups = ldap.getGroup(username)
|
||||||
|
|
|
@ -0,0 +1,21 @@
|
||||||
|
from functools import wraps
|
||||||
|
def login_required(**kwargs):
|
||||||
|
import geruecht.controller.accesTokenController as ac
|
||||||
|
from geruecht.model import BAR, USER, MONEY, GASTRO
|
||||||
|
from flask import request, jsonify
|
||||||
|
accessController = ac.AccesTokenController()
|
||||||
|
groups = [USER, BAR, GASTRO, MONEY]
|
||||||
|
if "groups" in kwargs:
|
||||||
|
groups = kwargs["groups"]
|
||||||
|
def real_decorator(func):
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
token = request.headers.get('Token')
|
||||||
|
accToken = accessController.validateAccessToken(token, groups)
|
||||||
|
kwargs['accToken'] = accToken
|
||||||
|
if accToken:
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
return jsonify({"error": "error", "message": "permission denied"}), 401
|
||||||
|
return wrapper
|
||||||
|
return real_decorator
|
|
@ -1,14 +1,18 @@
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
from geruecht.finanzer import LOGGER
|
from geruecht.finanzer import LOGGER
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from geruecht.controller import accesTokenController, userController
|
import geruecht.controller.userController as uc
|
||||||
from geruecht.model import MONEY
|
from geruecht.model import MONEY
|
||||||
|
from geruecht.decorator import login_required
|
||||||
|
|
||||||
finanzer = Blueprint("finanzer", __name__)
|
finanzer = Blueprint("finanzer", __name__)
|
||||||
|
|
||||||
|
userController = uc.UserController()
|
||||||
|
|
||||||
|
|
||||||
@finanzer.route("/getFinanzerMain")
|
@finanzer.route("/getFinanzerMain")
|
||||||
def _getFinanzer():
|
@login_required(groups=[MONEY])
|
||||||
|
def _getFinanzer(**kwargs):
|
||||||
""" Function for /getFinanzerMain
|
""" Function for /getFinanzerMain
|
||||||
|
|
||||||
Retrieves all User for the groupe 'moneymaster'
|
Retrieves all User for the groupe 'moneymaster'
|
||||||
|
@ -17,11 +21,6 @@ def _getFinanzer():
|
||||||
A JSON-File with Users
|
A JSON-File with Users
|
||||||
or ERROR 401 Permission Denied.
|
or ERROR 401 Permission Denied.
|
||||||
"""
|
"""
|
||||||
LOGGER.info("Get main for Finanzer")
|
|
||||||
token = request.headers.get("Token")
|
|
||||||
LOGGER.debug("Verify AccessToken with Token {}".format(token))
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
if accToken:
|
|
||||||
LOGGER.debug("Get all Useres")
|
LOGGER.debug("Get all Useres")
|
||||||
users = userController.getAllUsersfromDB()
|
users = userController.getAllUsersfromDB()
|
||||||
dic = {}
|
dic = {}
|
||||||
|
@ -32,11 +31,10 @@ def _getFinanzer():
|
||||||
LOGGER.debug("ReturnValue is {}".format(dic))
|
LOGGER.debug("ReturnValue is {}".format(dic))
|
||||||
LOGGER.info("Send main for Finanzer")
|
LOGGER.info("Send main for Finanzer")
|
||||||
return jsonify(dic)
|
return jsonify(dic)
|
||||||
LOGGER.info("Permission Denied")
|
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@finanzer.route("/finanzerAddAmount", methods=['POST'])
|
@finanzer.route("/finanzerAddAmount", methods=['POST'])
|
||||||
def _addAmount():
|
@login_required(groups=[MONEY])
|
||||||
|
def _addAmount(**kwargs):
|
||||||
""" Add Amount to User
|
""" Add Amount to User
|
||||||
|
|
||||||
This Function add an amount to the user with posted userID.
|
This Function add an amount to the user with posted userID.
|
||||||
|
@ -47,12 +45,6 @@ def _addAmount():
|
||||||
JSON-File with geruecht of year
|
JSON-File with geruecht of year
|
||||||
or ERROR 401 Permission Denied
|
or ERROR 401 Permission Denied
|
||||||
"""
|
"""
|
||||||
LOGGER.info("Add Amount")
|
|
||||||
token = request.headers.get("Token")
|
|
||||||
LOGGER.debug("Verify AccessToken with Token {}".format(token))
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
LOGGER.debug("Get data {}".format(data))
|
LOGGER.debug("Get data {}".format(data))
|
||||||
userID = data['userId']
|
userID = data['userId']
|
||||||
|
@ -75,11 +67,10 @@ def _addAmount():
|
||||||
retVal['locked'] = user.locked
|
retVal['locked'] = user.locked
|
||||||
LOGGER.info("Send updated Geruecht")
|
LOGGER.info("Send updated Geruecht")
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
LOGGER.info("Permission Denied")
|
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@finanzer.route("/finanzerAddCredit", methods=['POST'])
|
@finanzer.route("/finanzerAddCredit", methods=['POST'])
|
||||||
def _addCredit():
|
@login_required(groups=[MONEY])
|
||||||
|
def _addCredit(**kwargs):
|
||||||
""" Add Credit to User
|
""" Add Credit to User
|
||||||
|
|
||||||
This Function add an credit to the user with posted userID.
|
This Function add an credit to the user with posted userID.
|
||||||
|
@ -90,13 +81,6 @@ def _addCredit():
|
||||||
JSON-File with geruecht of year
|
JSON-File with geruecht of year
|
||||||
or ERROR 401 Permission Denied
|
or ERROR 401 Permission Denied
|
||||||
"""
|
"""
|
||||||
LOGGER.info("Add Amount")
|
|
||||||
token = request.headers.get("Token")
|
|
||||||
LOGGER.debug("Verify AccessToken with Token {}".format(token))
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
if accToken:
|
|
||||||
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
print(data)
|
print(data)
|
||||||
LOGGER.debug("Get data {}".format(data))
|
LOGGER.debug("Get data {}".format(data))
|
||||||
|
@ -122,42 +106,31 @@ def _addCredit():
|
||||||
retVal['locked'] = user.locked
|
retVal['locked'] = user.locked
|
||||||
LOGGER.info("Send updated Geruecht")
|
LOGGER.info("Send updated Geruecht")
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
LOGGER.info("Permission Denied")
|
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@finanzer.route("/finanzerLock", methods=['POST'])
|
@finanzer.route("/finanzerLock", methods=['POST'])
|
||||||
def _finanzerLock():
|
@login_required(groups=[MONEY])
|
||||||
token = request.headers.get("Token")
|
def _finanzerLock(**kwargs):
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
username = data['userId']
|
username = data['userId']
|
||||||
locked = bool(data['locked'])
|
locked = bool(data['locked'])
|
||||||
retVal = userController.lockUser(username, locked).toJSON()
|
retVal = userController.lockUser(username, locked).toJSON()
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@finanzer.route("/finanzerSetConfig", methods=['POST'])
|
@finanzer.route("/finanzerSetConfig", methods=['POST'])
|
||||||
def _finanzerSetConfig():
|
@login_required(groups=[MONEY])
|
||||||
token = request.headers.get("Token")
|
def _finanzerSetConfig(**kwargs):
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
username = data['userId']
|
username = data['userId']
|
||||||
autoLock = bool(data['autoLock'])
|
autoLock = bool(data['autoLock'])
|
||||||
limit = int(data['limit'])
|
limit = int(data['limit'])
|
||||||
retVal = userController.updateConfig(username, {'lockLimit': limit, 'autoLock': autoLock}).toJSON()
|
retVal = userController.updateConfig(username, {'lockLimit': limit, 'autoLock': autoLock}).toJSON()
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@finanzer.route("/finanzerAddUser", methods=['POST'])
|
@finanzer.route("/finanzerAddUser", methods=['POST'])
|
||||||
def _finanzerAddUser():
|
@login_required(groups=[MONEY])
|
||||||
token = request.headers.get("Token")
|
def _finanzerAddUser(**kwargs):
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
username = data['userId']
|
username = data['userId']
|
||||||
userController.getUser(username)
|
userController.getUser(username)
|
||||||
|
@ -170,26 +143,17 @@ def _finanzerAddUser():
|
||||||
dic[user.uid]['creditList'] = {credit.year: credit.toJSON() for credit in user.geruechte}
|
dic[user.uid]['creditList'] = {credit.year: credit.toJSON() for credit in user.geruechte}
|
||||||
LOGGER.debug("ReturnValue is {}".format(dic))
|
LOGGER.debug("ReturnValue is {}".format(dic))
|
||||||
return jsonify(dic), 200
|
return jsonify(dic), 200
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@finanzer.route("/finanzerSendOneMail", methods=['POST'])
|
@finanzer.route("/finanzerSendOneMail", methods=['POST'])
|
||||||
def _finanzerSendOneMail():
|
@login_required(groups=[MONEY])
|
||||||
token = request.headers.get("Token")
|
def _finanzerSendOneMail(**kwargs):
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
username = data['userId']
|
username = data['userId']
|
||||||
retVal = userController.sendMail(username)
|
retVal = userController.sendMail(username)
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error:", "permission denied"}), 401
|
|
||||||
|
|
||||||
@finanzer.route("/finanzerSendAllMail", methods=['GET'])
|
@finanzer.route("/finanzerSendAllMail", methods=['GET'])
|
||||||
def _finanzerSendAllMail():
|
@login_required(groups=[MONEY])
|
||||||
token = request.headers.get("Token")
|
def _finanzerSendAllMail(**kwargs):
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
if accToken:
|
|
||||||
retVal = userController.sendAllMail()
|
retVal = userController.sendAllMail()
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
|
@ -1,17 +0,0 @@
|
||||||
from geruecht.controller import db
|
|
||||||
|
|
||||||
class PriceList(db.Model):
|
|
||||||
""" Database Model for PriceList
|
|
||||||
|
|
||||||
PriceList has lots of Drinks and safe all Prices (normal, for club, for other clubs, which catagory, etc)
|
|
||||||
"""
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
|
||||||
|
|
||||||
name = db.Column(db.String, nullable=False, unique=True)
|
|
||||||
price = db.Column(db.Integer, nullable=False)
|
|
||||||
price_club = db.Column(db.Integer, nullable=False)
|
|
||||||
price_ext_club = db.Column(db.Integer, nullable=False)
|
|
||||||
category = db.Column(db.Integer, nullable=False)
|
|
||||||
upPrice = db.Column(db.Integer)
|
|
||||||
upPrice_club = db.Column(db.Integer)
|
|
||||||
upPrice_ext_club = db.Column(db.Integer)
|
|
|
@ -1,9 +1,12 @@
|
||||||
from geruecht import app, LOGGER
|
from geruecht import app, LOGGER
|
||||||
from geruecht.exceptions import PermissionDenied
|
from geruecht.exceptions import PermissionDenied
|
||||||
from geruecht.controller import accesTokenController, userController
|
import geruecht.controller.accesTokenController as ac
|
||||||
|
import geruecht.controller.userController as uc
|
||||||
from geruecht.model import MONEY, BAR, USER, GASTRO
|
from geruecht.model import MONEY, BAR, USER, GASTRO
|
||||||
from flask import request, jsonify
|
from flask import request, jsonify
|
||||||
|
|
||||||
|
accesTokenController = ac.AccesTokenController()
|
||||||
|
userController = uc.UserController()
|
||||||
|
|
||||||
def login(user, password):
|
def login(user, password):
|
||||||
return user.login(password)
|
return user.login(password)
|
||||||
|
@ -12,16 +15,16 @@ def login(user, password):
|
||||||
@app.route("/valid")
|
@app.route("/valid")
|
||||||
def _valid():
|
def _valid():
|
||||||
token = request.headers.get("Token")
|
token = request.headers.get("Token")
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
accToken = accesTokenController.validateAccessToken(token, [MONEY])
|
||||||
if accToken:
|
if accToken:
|
||||||
return jsonify(accToken.user.toJSON())
|
return jsonify(accToken.user.toJSON())
|
||||||
accToken = accesTokenController.validateAccessToken(token, BAR)
|
accToken = accesTokenController.validateAccessToken(token, [BAR])
|
||||||
if accToken:
|
if accToken:
|
||||||
return jsonify(accToken.user.toJSON())
|
return jsonify(accToken.user.toJSON())
|
||||||
accToken = accesTokenController.validateAccessToken(token, GASTRO)
|
accToken = accesTokenController.validateAccessToken(token, [GASTRO])
|
||||||
if accToken:
|
if accToken:
|
||||||
return jsonify(accToken.user.toJSON())
|
return jsonify(accToken.user.toJSON())
|
||||||
accToken = accesTokenController.validateAccessToken(token, USER)
|
accToken = accesTokenController.validateAccessToken(token, [USER])
|
||||||
if accToken:
|
if accToken:
|
||||||
return jsonify(accToken.user.toJSON())
|
return jsonify(accToken.user.toJSON())
|
||||||
return jsonify({"error": "permission denied"}), 401
|
return jsonify({"error": "permission denied"}), 401
|
||||||
|
@ -48,7 +51,7 @@ def _login():
|
||||||
user = userController.loginUser(username, password)
|
user = userController.loginUser(username, password)
|
||||||
user.password = password
|
user.password = password
|
||||||
token = accesTokenController.createAccesToken(user)
|
token = accesTokenController.createAccesToken(user)
|
||||||
dic = user.toJSON()
|
dic = accesTokenController.validateAccessToken(token, [USER]).user.toJSON()
|
||||||
dic["token"] = token
|
dic["token"] = token
|
||||||
dic["accessToken"] = token
|
dic["accessToken"] = token
|
||||||
LOGGER.info("User {} success login.".format(username))
|
LOGGER.info("User {} success login.".format(username))
|
||||||
|
|
|
@ -1,28 +1,30 @@
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
from geruecht.controller import userController, accesTokenController
|
from geruecht.decorator import login_required
|
||||||
|
import geruecht.controller.userController as uc
|
||||||
from geruecht.model import USER
|
from geruecht.model import USER
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
user = Blueprint("user", __name__)
|
user = Blueprint("user", __name__)
|
||||||
|
|
||||||
@user.route("/user/main")
|
userController = uc.UserController()
|
||||||
def _main():
|
|
||||||
|
|
||||||
token = request.headers.get("Token")
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, USER)
|
@user.route("/user/main")
|
||||||
if accToken:
|
@login_required(groups=[USER])
|
||||||
|
def _main(**kwargs):
|
||||||
|
if 'accToken' in kwargs:
|
||||||
|
accToken = kwargs['accToken']
|
||||||
accToken.user = userController.getUser(accToken.user.uid)
|
accToken.user = userController.getUser(accToken.user.uid)
|
||||||
retVal = accToken.user.toJSON()
|
retVal = accToken.user.toJSON()
|
||||||
retVal['creditList'] = {credit.year: credit.toJSON() for credit in accToken.user.geruechte}
|
retVal['creditList'] = {credit.year: credit.toJSON() for credit in accToken.user.geruechte}
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
return jsonify("error", "something went wrong"), 500
|
||||||
|
|
||||||
@user.route("/user/addAmount", methods=['POST'])
|
@user.route("/user/addAmount", methods=['POST'])
|
||||||
def _addAmount():
|
@login_required(groups=[USER])
|
||||||
|
def _addAmount(**kwargs):
|
||||||
token = request.headers.get("Token")
|
if 'accToken' in kwargs:
|
||||||
accToken = accesTokenController.validateAccessToken(token, USER)
|
accToken = kwargs['accToken']
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
amount = int(data['amount'])
|
amount = int(data['amount'])
|
||||||
date = datetime.now()
|
date = datetime.now()
|
||||||
|
@ -31,4 +33,4 @@ def _addAmount():
|
||||||
retVal = accToken.user.toJSON()
|
retVal = accToken.user.toJSON()
|
||||||
retVal['creditList'] = {credit.year: credit.toJSON() for credit in accToken.user.geruechte}
|
retVal['creditList'] = {credit.year: credit.toJSON() for credit in accToken.user.geruechte}
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
return jsonify({"error": "permission denied"}), 401
|
return jsonify({"error": "something went wrong"}), 500
|
|
@ -0,0 +1,41 @@
|
||||||
|
from flask import Blueprint, request, jsonify
|
||||||
|
from datetime import datetime
|
||||||
|
import geruecht.controller.userController as uc
|
||||||
|
from geruecht.decorator import login_required
|
||||||
|
from geruecht.model import MONEY, GASTRO
|
||||||
|
|
||||||
|
vorstand = Blueprint("vorstand", __name__)
|
||||||
|
userController = uc.UserController()
|
||||||
|
|
||||||
|
|
||||||
|
@vorstand.route("/sm/addUser", methods=['POST', 'GET'])
|
||||||
|
@login_required(groups=[MONEY, GASTRO])
|
||||||
|
def _addUser(**kwargs):
|
||||||
|
|
||||||
|
if request.method == 'GET':
|
||||||
|
return "<h1>HEllo World</h1>"
|
||||||
|
|
||||||
|
data = request.get_json()
|
||||||
|
user = data['user']
|
||||||
|
date = datetime.utcfromtimestamp(int(data['date']))
|
||||||
|
retVal = userController.addWorker(user['username'], date)
|
||||||
|
print(retVal)
|
||||||
|
return jsonify(retVal)
|
||||||
|
|
||||||
|
@vorstand.route("/sm/getUser", methods=['POST'])
|
||||||
|
@login_required(groups=[MONEY, GASTRO])
|
||||||
|
def _getUser(**kwargs):
|
||||||
|
data = request.get_json()
|
||||||
|
date = datetime.utcfromtimestamp(int(data['date']))
|
||||||
|
retVal = userController.getWorker(date)
|
||||||
|
print(retVal)
|
||||||
|
return jsonify(retVal)
|
||||||
|
|
||||||
|
@vorstand.route("/sm/deleteUser", methods=['POST'])
|
||||||
|
@login_required(groups=[MONEY, GASTRO])
|
||||||
|
def _deletUser(**kwargs):
|
||||||
|
data = request.get_json()
|
||||||
|
user = data['user']
|
||||||
|
date = datetime.utcfromtimestamp(int(data['date']))
|
||||||
|
userController.deleteWorker(user['username'], date)
|
||||||
|
return jsonify({"ok": "ok"})
|
Loading…
Reference in New Issue