flaschengeist/geruecht/controller/userController.py

589 lines
24 KiB
Python

from . import Singleton, mailConfig
import geruecht.controller.databaseController as dc
import geruecht.controller.ldapController as lc
import geruecht.controller.emailController as ec
import calendar
from geruecht.model.user import User
from geruecht.exceptions import PermissionDenied
from datetime import datetime, timedelta
from geruecht.exceptions import UsernameExistLDAP, LDAPExcetpion, DayLocked, TansactJobIsAnswerdException
from geruecht.logger import getDebugLogger
db = dc.DatabaseController()
ldap = lc.LDAPController()
emailController = ec.EmailController(
mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['crypt'], mailConfig['port'], mailConfig['email'])
debug = getDebugLogger()
class UserController(metaclass=Singleton):
def __init__(self):
debug.debug("init UserController")
pass
def getAllJobKinds(self):
debug.info("get all jobkinds")
retVal = db.getAllJobKinds()
debug.debug("jobkinds are {{ {} }}".format(retVal))
return retVal
def getJobKind(self, name):
debug.info("get jobkinds {{ {} }}".format(name))
retVal = db.getJobKind(name)
debug.debug("jobkind is {{ {} }} is {{ {} }}".format(name, retVal))
return retVal
def setJobKind(self, name):
debug.info("set jobkind {{ {} }} ".format(name))
retVal = db.setJobKind(name)
debug.debug(
"seted jobkind {{ {} }} is {{ {} }}".format(name, retVal))
return retVal
def deleteJobKind(self, jobkind):
debug.info("delete jobkind {{ {} }}".format(jobkind))
db.deleteJobKind(jobkind)
def updateJobKind(self, jobkind):
debug.info("update workgroup {{ {} }}".format(jobkind))
retVal = db.updateJobKind(jobkind)
debug.debug("updated jobkind is {{ {} }}".format(retVal))
return retVal
def updateWorkgroupsOfUser(self, user, workgroups):
debug.info("update workgroups {{ {} }} of user {{ {} }}".format(workgroups, user))
db.deleteWorkgroupsOfUser(user)
for workgroup in workgroups:
db.setUserWorkgroup(user, workgroup)
return db.getWorkgroupsOfUser(user['id'])
def getAllWorkgroups(self):
debug.info("get all workgroups")
retVal = db.getAllWorkgroups()
debug.debug("workgroups are {{ {} }}".format(retVal))
return retVal
def getWorkgroups(self, name):
debug.info("get Workgroup {{ {} }}".format(name))
retVal = db.getWorkgroup(name)
debug.debug("workgroup is {{ {} }} is {{ {} }}".format(name, retVal))
return retVal
def setWorkgroup(self, name, boss):
debug.info("set workgroup {{ {} }} with boss {{ {} }}".format(name, boss))
retVal = db.setWorkgroup(name, boss)
debug.debug(
"seted workgroup {{ {} }} is {{ {} }}".format(name, retVal))
return retVal
def deleteWorkgroup(self, workgroup):
debug.info("delete workgroup {{ {} }}".format(workgroup))
db.deleteWorkgroup(workgroup)
def updateWorkgroup(self, workgroup):
debug.info("update workgroup {{ {} }}".format(workgroup))
retVal = db.updateWorkgroup(workgroup)
debug.debug("updated workgroup is {{ {} }}".format(retVal))
return retVal
def getAllStatus(self):
debug.info("get all status for user")
retVal = db.getAllStatus()
debug.debug("status are {{ {} }}".format(retVal))
return retVal
def getStatus(self, name):
debug.info("get status of user {{ {} }}".format(name))
retVal = db.getStatus(name)
debug.debug("status of user {{ {} }} is {{ {} }}".format(name, retVal))
return retVal
def setStatus(self, name):
debug.info("set status of user {{ {} }}".format(name))
retVal = db.setStatus(name)
debug.debug(
"settet status of user {{ {} }} is {{ {} }}".format(name, retVal))
return retVal
def deleteStatus(self, status):
debug.info("delete status {{ {} }}".format(status))
db.deleteStatus(status)
def updateStatus(self, status):
debug.info("update status {{ {} }}".format(status))
retVal = db.updateStatus(status)
debug.debug("updated status is {{ {} }}".format(retVal))
return retVal
def updateStatusOfUser(self, username, status):
debug.info("update status {{ {} }} of user {{ {} }}".format(
status, username))
retVal = db.updateStatusOfUser(username, status)
debug.debug(
"updatet status of user {{ {} }} is {{ {} }}".format(username, retVal))
return retVal
def updateVotingOfUser(self, username, voting):
debug.info("update voting {{ {} }} of user {{ {} }}".format(
voting, username))
retVal = db.updateVotingOfUser(username, voting)
debug.debug(
"updatet voting of user {{ {} }} is {{ {} }}".format(username, retVal))
return retVal
def deleteDrinkType(self, type):
debug.info("delete drink type {{ {} }}".format(type))
db.deleteDrinkType(type)
def updateDrinkType(self, type):
debug.info("update drink type {{ {} }}".format(type))
retVal = db.updateDrinkType(type)
debug.debug("updated drink type is {{ {} }}".format(retVal))
return retVal
def setDrinkType(self, type):
debug.info("set drink type {{ {} }}".format(type))
retVal = db.setDrinkType(type)
debug.debug("seted drink type is {{ {} }}".format(retVal))
return retVal
def deletDrinkPrice(self, drink):
debug.info("delete drink {{ {} }}".format(drink))
db.deleteDrink(drink)
def setDrinkPrice(self, drink):
debug.info("set drink {{ {} }}".format(drink))
retVal = db.setDrinkPrice(drink)
debug.debug("seted drink is {{ {} }}".format(retVal))
return retVal
def updateDrinkPrice(self, drink):
debug.info("update drink {{ {} }}".format(drink))
retVal = db.updateDrinkPrice(drink)
debug.debug("updated drink is {{ {} }}".format(retVal))
return retVal
def getAllDrinkTypes(self):
debug.info("get all drink types")
retVal = db.getAllDrinkTypes()
debug.debug("all drink types are {{ {} }}".format(retVal))
return retVal
def getPricelist(self):
debug.info("get all drinks")
list = db.getPriceList()
debug.debug("all drinks are {{ {} }}".format(list))
return list
def setTransactJob(self, from_user, to_user, date):
debug.info("set transact job from {{ {} }} to {{ {} }} on {{ {} }}".format(
from_user, to_user, date))
jobtransact = db.setTransactJob(from_user, to_user, date.date())
debug.debug("transact job is {{ {} }}".format(jobtransact))
debug.info("send mail with transact job to user")
emailController.sendMail(
jobtransact['to_user'], 'jobtransact', jobtransact)
return jobtransact
def getTransactJobFromUser(self, user, date):
debug.info(
"get transact job from user {{ {} }} on {{ {} }}".format(user, date))
retVal = db.getTransactJobFromUser(user, date.date())
debug.debug(
"transact job from user {{ {} }} is {{ {} }}".format(user, retVal))
return retVal
def getAllTransactJobFromUser(self, user, date):
debug.info(
"get all transact job from user {{ {} }} start on {{ {} }}".format(user, date))
retVal = db.getAllTransactJobFromUser(user, date.date())
debug.debug("all transact job are {{ {} }}".format(retVal))
return retVal
def getAllTransactJobToUser(self, user, date):
debug.info(
"get all transact job from to_user {{ {} }} start on {{ {} }}".format(user, date))
retVal = db.getAllTransactJobToUser(user, date.date())
debug.debug("all transact job are {{ {} }}".format(retVal))
return retVal
def getTransactJob(self, from_user, to_user, date):
debug.info("get transact job from user {{ {} }} to user {{ {} }} on {{ {} }}".format(
from_user, to_user, date))
retVal = db.getTransactJob(from_user, to_user, date.date())
debug.debug("transact job is {{ {} }}".format(retVal))
return retVal
def deleteTransactJob(self, from_user, to_user, date):
debug.info("delete transact job from user {{ {} }} to user {{ {} }} on {{ {} }}".format(
from_user, to_user, date))
transactJob = self.getTransactJob(from_user, to_user, date)
debug.debug("transact job is {{ {} }}".format(transactJob))
if transactJob['answerd']:
debug.warning(
"transactjob {{ {} }} can not delete because is answerd")
raise TansactJobIsAnswerdException(
"TransactJob is already answerd")
db.deleteTransactJob(from_user, to_user, date.date())
def answerdTransactJob(self, from_user, to_user, date, answer):
debug.info("answer transact job from user {{ {} }} to user {{ {} }} on {{ {} }} with answer {{ {} }}".format(
from_user, to_user, date, answer))
transactJob = db.updateTransactJob(
from_user, to_user, date.date(), answer)
debug.debug("transactjob is {{ {} }}".format(transactJob))
if answer:
debug.info("add worker on date {{ {} }}".format(date))
self.addWorker(to_user.uid, date)
return transactJob
def setLockedDay(self, date, locked, hard=False):
debug.info(
"set day locked on {{ {} }} with state {{ {} }}".format(date, locked))
retVal = db.setLockedDay(date.date(), locked, hard)
debug.debug("seted day locked is {{ {} }}".format(retVal))
return retVal
def getLockedDays(self, from_date, to_date):
debug.info("get locked days from {{ {} }} to {{ {} }}".format(
from_date.date(), to_date.date()))
oneDay = timedelta(1)
delta = to_date.date() - from_date.date()
retVal = []
startdate = from_date - oneDay
for _ in range(delta.days + 1):
startdate += oneDay
lockday = self.getLockedDay(startdate)
retVal.append(lockday)
debug.debug("lock days are {{ {} }}".format(retVal))
return retVal
def getLockedDay(self, date):
debug.info("get locked day on {{ {} }}".format(date))
now = datetime.now()
debug.debug("now is {{ {} }}".format(now))
oldMonth = False
debug.debug("check if date old month or current month")
for i in range(1, 8):
if datetime(now.year, now.month, i).weekday() == 2:
if now.day < i:
oldMonth = True
break
debug.debug("oldMonth is {{ {} }}".format(oldMonth))
lockedYear = now.year
lockedMonth = now.month if now.month < now.month else now.month - \
1 if oldMonth else now.month
endDay = 1
debug.debug("calculate end day of month")
lockedYear = lockedYear if lockedMonth != 12 else (lockedYear + 1)
lockedMonth = (lockedMonth + 1) if lockedMonth != 12 else 1
for i in range(1, 8):
nextMonth = datetime(lockedYear, lockedMonth, i)
if nextMonth.weekday() == 2:
endDay = i
break
monthLockedEndDate = datetime(
lockedYear, lockedMonth, endDay) - timedelta(1)
debug.debug("get lock day from database")
retVal = db.getLockedDay(date.date())
if not retVal:
debug.debug(
"lock day not exists, retVal is {{ {} }}".format(retVal))
if date.date() <= monthLockedEndDate.date():
debug.debug("lock day {{ {} }}".format(date.date()))
self.setLockedDay(date, True)
retVal = db.getLockedDay(date.date())
else:
retVal = {"daydate": date.date(), "locked": False}
debug.debug("locked day is {{ {} }}".format(retVal))
return retVal
def getWorker(self, date, username=None):
debug.info("get worker {{ {} }} on {{ {} }}".format(username, date))
if (username):
user = self.getUser(username)
debug.debug("user is {{ {} }}".format(user))
retVal = [db.getWorker(user, date)]
debug.debug("worker is {{ {} }}".format(retVal))
return retVal
retVal = db.getWorkers(date)
debug.debug("workers are {{ {} }}".format(retVal))
return retVal
def addWorker(self, username, date, userExc=False):
debug.info("add job user {{ {} }} on {{ {} }}".format(username, date))
if (userExc):
debug.debug("this is a user execution, check if day is locked")
lockedDay = self.getLockedDay(date)
if lockedDay:
if lockedDay['locked']:
debug.debug("day is lockey. user cant get job")
raise DayLocked("Day is locked. You can't get the Job")
user = self.getUser(username)
debug.debug("user is {{ {} }}".format(user))
debug.debug("check if user has job on date")
if (not db.getWorker(user, date)):
debug.debug("set job to user")
db.setWorker(user, date)
retVal = self.getWorker(date, username=username)
debug.debug("worker on date is {{ {} }}".format(retVal))
return retVal
def deleteWorker(self, username, date, userExc=False):
debug.info(
"delete worker {{ {} }} on date {{ {} }}".format(username, date))
user = self.getUser(username)
debug.debug("user is {{ {} }}".format(user))
if userExc:
debug.debug("is user execution, check if day locked")
lockedDay = self.getLockedDay(date)
if lockedDay:
if lockedDay['locked']:
debug.debug(
"day is locked, check if accepted transact job exists")
transactJobs = self.getTransactJobFromUser(user, date)
debug.debug(
"transact job is {{ {} }}".format(transactJobs))
found = False
for job in transactJobs:
if job['accepted'] and job['answerd']:
debug.debug("accepted transact job exists")
found = True
break
if not found:
debug.debug("no accepted transact job found")
raise DayLocked(
"Day is locked. You can't delete the Job")
db.deleteWorker(user, date)
def lockUser(self, username, locked):
debug.info("lock user {{ {} }} for credit with status {{ {} }}".format(
username, locked))
user = self.getUser(username)
debug.debug("user is {{ {} }}".format(user))
user.updateData({'locked': locked})
db.updateUser(user)
retVal = self.getUser(username)
debug.debug("locked user is {{ {} }}".format(retVal))
return retVal
def updateConfig(self, username, data):
debug.info(
"update config of user {{ {} }} with config {{ {} }}".format(username, data))
user = self.getUser(username)
debug.debug("user is {{ {} }}".format(user))
user.updateData(data)
db.updateUser(user)
retVal = self.getUser(username)
debug.debug("updated config of user is {{ {} }}".format(retVal))
return retVal
def __updateDataFromLDAP(self, user):
debug.info("update data from ldap for user {{ {} }}".format(user))
groups = ldap.getGroup(user.uid)
debug.debug("ldap gorups are {{ {} }}".format(groups))
user_data = ldap.getUserData(user.uid)
debug.debug("ldap data is {{ {} }}".format(user_data))
user_data['gruppe'] = groups
user_data['group'] = groups
user.updateData(user_data)
db.updateUser(user)
def autoLock(self, user):
debug.info("start autolock of user {{ {} }}".format(user))
if user.autoLock:
debug.debug("autolock is active")
credit = user.getGeruecht(year=datetime.now().year).getSchulden()
limit = -1*user.limit
if credit <= limit:
debug.debug(
"credit {{ {} }} is more than user limit {{ {} }}".format(credit, limit))
debug.debug("lock user")
user.updateData({'locked': True})
debug.debug("send mail to user")
emailController.sendMail(user)
else:
debug.debug(
"cretid {{ {} }} is less than user limit {{ {} }}".format(credit, limit))
debug.debug("unlock user")
user.updateData({'locked': False})
db.updateUser(user)
def addAmount(self, username, amount, year, month, finanzer=False):
debug.info("add amount {{ {} }} to user {{ {} }} no month {{ {} }}, year {{ {} }}".format(
amount, username, month, year))
user = self.getUser(username)
debug.debug("user is {{ {} }}".format(user))
if user.uid == 'extern':
debug.debug("user is extern user, so exit add amount")
return
if not user.locked or finanzer:
debug.debug("user is not locked {{ {} }} or is finanzer execution {{ {} }}".format(
user.locked, finanzer))
user.addAmount(amount, year=year, month=month)
creditLists = user.updateGeruecht()
debug.debug("creditList is {{ {} }}".format(creditLists))
for creditList in creditLists:
debug.debug("update creditlist {{ {} }}".format(creditList))
db.updateCreditList(creditList)
debug.debug("do autolock")
self.autoLock(user)
retVal = user.getGeruecht(year)
debug.debug("updated creditlists is {{ {} }}".format(retVal))
return retVal
def addCredit(self, username, credit, year, month):
debug.info("add credit {{ {} }} to user {{ {} }} on month {{ {} }}, year {{ {} }}".format(
credit, username, month, year))
user = self.getUser(username)
debug.debug("user is {{ {} }}".format(user))
if user.uid == 'extern':
debug.debug("user is extern user, so exit add credit")
return
user.addCredit(credit, year=year, month=month)
creditLists = user.updateGeruecht()
debug.debug("creditlists are {{ {} }}".format(creditLists))
for creditList in creditLists:
debug.debug("update creditlist {{ {} }}".format(creditList))
db.updateCreditList(creditList)
debug.debug("do autolock")
self.autoLock(user)
retVal = user.getGeruecht(year)
debug.debug("updated creditlists are {{ {} }}".format(retVal))
return retVal
def getAllUsersfromDB(self):
debug.info("get all users from database")
users = db.getAllUser()
debug.debug("users are {{ {} }}".format(users))
for user in users:
try:
debug.debug("update data from ldap")
self.__updateDataFromLDAP(user)
except:
pass
debug.debug("update creditlists")
self.__updateGeruechte(user)
retVal = db.getAllUser(extern=True)
debug.debug("all users are {{ {} }}".format(retVal))
return retVal
def checkBarUser(self, user):
debug.info("check if user {{ {} }} is baruser")
date = datetime.now()
zero = date.replace(hour=0, minute=0, second=0, microsecond=0)
end = zero + timedelta(hours=12)
startdatetime = date.replace(
hour=12, minute=0, second=0, microsecond=0)
if date > zero and end > date:
startdatetime = startdatetime - timedelta(days=1)
enddatetime = startdatetime + timedelta(days=1)
debug.debug("startdatetime is {{ {} }} and enddatetime is {{ {} }}".format(
startdatetime, end))
result = False
if date >= startdatetime and date < enddatetime:
result = db.getWorker(user, startdatetime)
debug.debug("worker is {{ {} }}".format(result))
return True if result else False
def getUser(self, username):
debug.info("get user {{ {} }}".format(username))
user = db.getUser(username)
debug.debug("user is {{ {} }}".format(user))
groups = ldap.getGroup(username)
debug.debug("groups are {{ {} }}".format(groups))
user_data = ldap.getUserData(username)
debug.debug("user data from ldap is {{ {} }}".format(user_data))
user_data['gruppe'] = groups
user_data['group'] = groups
if user is None:
debug.debug("user not exists in database -> insert into database")
user = User(user_data)
db.insertUser(user)
else:
debug.debug("update database with user")
user.updateData(user_data)
db.updateUser(user)
user = db.getUser(username)
self.__updateGeruechte(user)
debug.debug("user is {{ {} }}".format(user))
return user
def __updateGeruechte(self, user):
debug.debug("update creditlists")
user.getGeruecht(datetime.now().year)
creditLists = user.updateGeruecht()
debug.debug("creditlists are {{ {} }}".format(creditLists))
if user.getGeruecht(datetime.now().year).getSchulden() != 0:
for creditList in creditLists:
debug.debug("update creditlist {{ {} }}".format(creditList))
db.updateCreditList(creditList)
def sendMail(self, username):
debug.info("send mail to user {{ {} }}".format(username))
if type(username) == User:
user = username
if type(username) == str:
user = db.getUser(username)
retVal = emailController.sendMail(user)
debug.debug("send mail is {{ {} }}".format(retVal))
return retVal
def sendAllMail(self):
debug.info("send mail to all user")
retVal = []
users = db.getAllUser()
debug.debug("users are {{ {} }}".format(users))
for user in users:
retVal.append(self.sendMail(user))
debug.debug("send mails are {{ {} }}".format(retVal))
return retVal
def modifyUser(self, user, ldap_conn, attributes):
debug.info("modify user {{ {} }} with attributes {{ {} }} with ldap_conn {{ {} }}".format(
user, attributes, ldap_conn))
try:
if 'username' in attributes:
debug.debug("change username, so change first in database")
db.changeUsername(user, attributes['username'])
ldap.modifyUser(user, ldap_conn, attributes)
if 'username' in attributes:
retVal = self.getUser(attributes['username'])
debug.debug("user is {{ {} }}".format(retVal))
return retVal
else:
retVal = self.getUser(user.uid)
debug.debug("user is {{ {} }}".format(retVal))
return retVal
except UsernameExistLDAP as err:
debug.debug(
"username exists on ldap, rechange username on database", exc_info=True)
db.changeUsername(user, user.uid)
raise Exception(err)
except LDAPExcetpion as err:
if 'username' in attributes:
db.changeUsername(user, user.uid)
raise Exception(err)
except Exception as err:
raise Exception(err)
def validateUser(self, username, password):
debug.info("validate user {{ {} }}".format(username))
ldap.login(username, password)
def loginUser(self, username, password):
debug.info("login user {{ {} }}".format(username))
try:
user = self.getUser(username)
debug.debug("user is {{ {} }}".format(user))
user.password = password
ldap.login(username, password)
ldap_conn = ldap.bind(user, password)
return user, ldap_conn
except PermissionDenied as err:
debug.debug("permission is denied", exc_info=True)
raise err