450 lines
16 KiB
Python
Executable file
450 lines
16 KiB
Python
Executable file
#! /usr/bin/env python
|
||
# -*- coding: iso-8859-15 -*-
|
||
|
||
import cherrypy, sys, os, datetime
|
||
# libraries crans
|
||
sys.path.append('/usr/scripts/gestion/')
|
||
from config_mail import MailConfig
|
||
if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
|
||
from ldap_crans_test import *
|
||
print("monCompte : unsing test ldap : env=" + cherrypy.config.configMap["global"]["server.environment"])
|
||
else:
|
||
from ldap_crans import *
|
||
print("monCompte : unsing prod ldap : env=" + cherrypy.config.configMap["global"]["server.environment"])
|
||
|
||
|
||
|
||
class monCompte:
|
||
__ldap = None
|
||
|
||
def __init__(self):
|
||
self.__ldap = cherrypy.config.configMap["global"]["crans_ldap"]
|
||
|
||
|
||
def getCurrentAdministrativeYear(self):
|
||
'''
|
||
premiere partie de l''annee scolaire en cours
|
||
ex : le 5 juin 2006 retourne 2005
|
||
'''
|
||
now = datetime.datetime.now()
|
||
currentYear = int(now.strftime("%Y"))
|
||
currentMonth = int(now.strftime("%m"))
|
||
if currentMonth > 8:
|
||
administrativeYear = currentYear
|
||
else:
|
||
administrativeYear = currentYear - 1
|
||
return administrativeYear
|
||
|
||
##########################
|
||
# affichage
|
||
##########################
|
||
#
|
||
# methode qui affiche la template avec toutes les infos de
|
||
# l'adherent + les formulaires
|
||
#
|
||
def index(self, message = '', error = '', currentTab = 'mainTab'):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'])['adherent'][0]
|
||
t = {}
|
||
t['message'] = message
|
||
t['error'] = error
|
||
|
||
|
||
############## info adherent ##############
|
||
adherent = {}
|
||
# nom, prenom, chambre, tel, solde, droits, mail
|
||
adherent['prenom'] = adh.prenom()
|
||
adherent['nom'] = adh.nom()
|
||
adherent['chambre'] = adh.chbre()
|
||
adherent['telephone'] = adh.tel
|
||
adherent['solde'] = adh.solde
|
||
adherent['droits'] = u", ".join(adh.droits())
|
||
adherent['mail'] = adh.email()
|
||
# cotisation
|
||
administrativeYear = self.getCurrentAdministrativeYear()
|
||
if administrativeYear in adh.paiement():
|
||
adherent['cotisationOK'] = 'OK'
|
||
else:
|
||
adherent['cotisationOK'] = None
|
||
# carte etudiant
|
||
if administrativeYear in adh.carteEtudiant():
|
||
adherent['carteOK'] = 'OK'
|
||
else:
|
||
adherent['carteOK'] = None
|
||
# annee scolaire (ex 2001-2002)
|
||
adherent['anneeScolaire'] = str(administrativeYear) + '-' + str(administrativeYear + 1)
|
||
t['adherent'] = adherent
|
||
|
||
|
||
|
||
|
||
############## info machines ##############
|
||
machines = []
|
||
for une_machine in adh.machines():
|
||
machineInfos = {}
|
||
# nom, mac, mid, ip
|
||
machineInfos['id'] = une_machine.nom
|
||
machineInfos['nom'] = une_machine.nom
|
||
machineInfos['nomCourt'] = une_machine.nom().split('.',1)[0]
|
||
machineInfos['mac'] = une_machine.mac
|
||
machineInfos['mid'] = une_machine.id()
|
||
machineInfos['ip'] = une_machine.ip()
|
||
# type
|
||
if une_machine.objectClass == 'machineFixe':
|
||
machineInfos['type'] = 'Machine fixe'
|
||
else:
|
||
machineInfos['type'] = 'Machine wifi'
|
||
# clef ipsec
|
||
try:
|
||
machineInfos['ipsec'] = une_machine.ipsec
|
||
except:
|
||
machineInfos['ipsec'] = ''
|
||
machines.append(machineInfos)
|
||
t['machines'] = machines
|
||
|
||
############## info mail ##############
|
||
mailInfos = {}
|
||
#try:
|
||
mailConfig = MailConfig(cherrypy.session['uid'])
|
||
mailInfos['forwarding_address'] = mailConfig['forward']
|
||
mailInfos['spam'] = {}
|
||
mailInfos['spam']['no'] = mailConfig['spam'] == 'accepte'
|
||
mailInfos['spam']['mark'] = mailConfig['spam'] == 'marque'
|
||
mailInfos['spam']['drop'] = mailConfig['spam'] == 'supprime'
|
||
#except Exception, e:
|
||
# t['mailError'] = u"Erreur:fichiers de configuration mail incompr<70>hensibles"
|
||
|
||
mailInfos['alias'] = adh.alias()
|
||
mailInfos['contourneGreylist'] = adh.contourneGreylist()
|
||
mailInfos['rewriteMailHeaders'] = adh.rewriteMailHeaders()
|
||
t['mailInfos'] = mailInfos
|
||
|
||
|
||
|
||
return {
|
||
'template' :'monCompte',
|
||
'values' :t,
|
||
'stylesheets' :['monCompte.css'],
|
||
# 'scripts':['crans.js','passwordGenerator.js'],
|
||
'scripts':['crans_domtab.js','crans.js','passwordGenerator.js'],
|
||
}
|
||
index.exposed = True
|
||
|
||
|
||
|
||
def listeMachines(self):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'])['adherent'][0]
|
||
machines = []
|
||
for une_machine in adh.machines():
|
||
machineInfos = {}
|
||
# nom, mac, mid, ip
|
||
machineInfos['nom'] = une_machine.nom()
|
||
machineInfos['nomCourt'] = une_machine.nom().split('.',1)[0]
|
||
machineInfos['mac'] = une_machine.mac()
|
||
machineInfos['mid'] = une_machine.id()
|
||
machineInfos['ip'] = une_machine.ip()
|
||
# type
|
||
if une_machine.objectClass == 'machineFixe':
|
||
machineInfos['type'] = 'Machine fixe'
|
||
else:
|
||
machineInfos['type'] = 'Machine wifi'
|
||
# clef ipsec
|
||
try:
|
||
machineInfos['ipsec'] = une_machine.ipsec()
|
||
except:
|
||
machineInfos['ipsec'] = ''
|
||
machines.append(machineInfos)
|
||
return {'machines':machines}
|
||
listeMachines.exposed = True
|
||
|
||
|
||
##########################
|
||
# paypal
|
||
##########################
|
||
#
|
||
# methode qui affiche successivement les
|
||
# templates du popup pour recharger son compte impression
|
||
# via paypal
|
||
#
|
||
def rechargerCompteImpression(self, etape = '1', combien = None):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'])['adherent'][0]
|
||
if (etape == "1"): # Introduction
|
||
return {
|
||
'template' :'MonCompteRechargePaypal1',
|
||
'standalone' :True,
|
||
'values' :{},
|
||
}
|
||
elif (etape == "2"): # choix montant
|
||
return {
|
||
'template' :'MonCompteRechargePaypal2',
|
||
'standalone' :True,
|
||
'values' :{},
|
||
}
|
||
elif (etape == "3"): # confirmer facture
|
||
# creer objet facture
|
||
f = Facture(adh)
|
||
# /!\ verifier que combien est un nombre
|
||
# et qu'il n'y a pas plus de 2 chiffres apr<70>s le point...
|
||
# (ce serait bien aussi si on pouvait mettre une virgue a la place du point)
|
||
try:
|
||
# remplacage des virgules
|
||
combien = combien.replace(u',', u'.')
|
||
# convertissage
|
||
combien = float(combien)
|
||
# arrondissage-tronquage :
|
||
combien = float(int(combien*100)/100.0)
|
||
except Exception:
|
||
return {
|
||
'template' :'MonCompteRechargePaypal2',
|
||
'standalone' :True,
|
||
'values' :{'error':"Le montant doit être un nombre !", 'combien':combien},
|
||
}
|
||
f.ajoute({'nombre': 1, 'code': 'SOLDE', 'designation': 'Credit du compte impression (intranet)', 'pu': combien})
|
||
cherrypy.session['freshFacture'] = f
|
||
pageData = {}
|
||
pageData['details'] = [
|
||
{
|
||
'intitule':art['designation'],
|
||
'quantite':art['nombre'],
|
||
'prixUnitaire':art['pu'],
|
||
'prixTotal':art['pu']*art['nombre'],
|
||
} for art in f.articles()]
|
||
pageData['total'] = f.total()
|
||
return {
|
||
'template' :'MonCompteRechargePaypal3',
|
||
'standalone' :True,
|
||
'values' :pageData,
|
||
}
|
||
elif (etape == "4"): # payer maintenant ?
|
||
# sauver objet facture
|
||
f = cherrypy.session['freshFacture']
|
||
f.save()
|
||
return {
|
||
'template' :'MonCompteRechargePaypal4',
|
||
'standalone' :True,
|
||
'values' :{'lienPaypal' : f.urlPaypal()},
|
||
}
|
||
rechargerCompteImpression.exposed = True
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
###########################################################################
|
||
# methodes pour changer
|
||
# des valeurs
|
||
###########################################################################
|
||
#
|
||
# En fait, les methodes recoivent les valeurs d'un formulaire
|
||
# (ou equivalent de javascript), font la modification puis
|
||
# appellent la methode principale d'affichage
|
||
# en lui passant eventuellement un message a afficher
|
||
# (pour indiquer la reussite ou non de l'operation)
|
||
#
|
||
|
||
##########################
|
||
# Adherent:nom
|
||
##########################
|
||
def changeNomAdherent(self, nouveauNom):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'], 'w')['adherent'][0]
|
||
try:
|
||
adh.nom(nouveauNom)
|
||
adh.save()
|
||
except ValueError, e:
|
||
return self.index(error=e.args[0])
|
||
del adh
|
||
return self.index(message=u'Modification r<>ussie')
|
||
changeNomAdherent.exposed = True
|
||
|
||
##########################
|
||
# Adherent:password
|
||
##########################
|
||
def changePasswordAdherent(self, ancienPassword, nouveauPassword1, nouveauPassword2):
|
||
if ancienPassword=='':
|
||
msg = 'Erreur, mot de passe incorrect'
|
||
return self.index(error=msg)
|
||
if nouveauPassword1=='':
|
||
msg = 'Erreur, le nouveau mot de passe ne doit pas ètre vide.'
|
||
return self.index(error=msg)
|
||
if nouveauPassword1!=nouveauPassword2:
|
||
msg = 'Erreur, la confirmation ne correspond pas au nouveau mot de passe.'
|
||
return self.index(error=msg)
|
||
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'],'w')['adherent'][0]
|
||
if adh.checkPassword(ancienPassword):
|
||
adh.changePasswd(nouveauPassword1)
|
||
adh.save()
|
||
msg = u'Changement effectu<74>'
|
||
else:
|
||
msg = 'Erreur, mot de passe incorrect'
|
||
return self.index(error=msg)
|
||
del adh
|
||
return self.index(message=msg)
|
||
changePasswordAdherent.exposed = True
|
||
|
||
|
||
##########################
|
||
# Adherent:prenom
|
||
##########################
|
||
def changePrenomAdherent(self, nouveauPrenom):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'], 'w')['adherent'][0]
|
||
try:
|
||
adh.prenom(nouveauPrenom)
|
||
adh.save()
|
||
except ValueError, e:
|
||
return self.index(error=e.args[0])
|
||
del adh
|
||
return self.index(message=u'Modification r<>ussie')
|
||
changePrenomAdherent.exposed = True
|
||
|
||
##########################
|
||
# Adherent:tel
|
||
##########################
|
||
def changeTelAdherent(self, nouveauTel):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'], 'w')['adherent'][0]
|
||
try:
|
||
adh.tel(nouveauTel)
|
||
adh.save()
|
||
except ValueError, e:
|
||
return self.index(error=e.args[0])
|
||
del adh
|
||
return self.index(message=u'Modification r<>ussie')
|
||
changeTelAdherent.exposed = True
|
||
|
||
##########################
|
||
# machine:nom
|
||
##########################
|
||
def changeNomMachine(self, mid, nouveauNom):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'])['adherent'][0]
|
||
mach = self.__ldap.search('mid=' + mid, 'w')['machine'][0]
|
||
# tester si c'est bien la machine de l'adherent
|
||
if mach.proprietaire().compte() != cherrypy.session['uid']:
|
||
del adh, mach
|
||
raise Exception(u"L'uid de l'adherent ne correspond mas au proprietaire de la machine.")
|
||
try:
|
||
mach.nom(nouveauNom)
|
||
mach.save()
|
||
del mach
|
||
except ValueError, e:
|
||
del mach
|
||
return {'error':e.args[0]}
|
||
return {'message':u"Modification r<>ussie"}
|
||
changeNomMachine.exposed = True
|
||
|
||
##########################
|
||
# machine:mac
|
||
##########################
|
||
def changeMACMachine(self, mid, nouvelleMAC):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'])['adherent'][0]
|
||
mach = self.__ldap.search('mid=' + mid, 'w')['machine'][0]
|
||
# tester si c'est bien la machine de l'adherent
|
||
if mach.proprietaire().compte() != cherrypy.session['uid']:
|
||
del adh, mach
|
||
raise Exception(u"L'uid de l'adherent ne correspond mas au proprietaire de la machine.")
|
||
|
||
try:
|
||
mach.mac(nouvelleMAC)
|
||
mach.save()
|
||
del mach
|
||
except ValueError, e:
|
||
del mach
|
||
return {'error':e.args[0]}
|
||
return {'message':u"Modification r<>ussie"}
|
||
changeMACMachine.exposed = True
|
||
|
||
|
||
|
||
##########################
|
||
# machine:suppression
|
||
##########################
|
||
def supprimeMachine(self, mid):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'])['adherent'][0]
|
||
mach = self.__ldap.search('mid=' + mid, 'w')['machine'][0]
|
||
# tester si c'est bien la machine de l'adherent
|
||
if mach.proprietaire().compte() != cherrypy.session['uid']:
|
||
del adh, mach
|
||
raise Exception(u"L'uid de l'adherent ne correspond mas au proprietaire de la machine.")
|
||
try:
|
||
mach.delete()
|
||
except ValueError, e:
|
||
return {'error':e.args[0]}
|
||
return {'message':u"Machine supprim<69>e"}
|
||
supprimeMachine.exposed = True
|
||
|
||
##########################
|
||
# machine:creation
|
||
##########################
|
||
def creerMachine(self, nomNouvelleMachine, MACNouvelleMachine, estMachineWifi='0'):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'])['adherent'][0]
|
||
try:
|
||
if estMachineWifi=='true':
|
||
m = MachineWifi(adh)
|
||
else:
|
||
m = MachineFixe(adh)
|
||
m.nom(nomNouvelleMachine)
|
||
m.mac(MACNouvelleMachine)
|
||
m.ip("<automatique>")
|
||
message = m.save()
|
||
del m
|
||
except ValueError, e:
|
||
del m
|
||
return {'error':e.args[0]}
|
||
return {'message':u"Machine enregistr<74>e avec succ<63>s"}
|
||
creerMachine.exposed = True
|
||
|
||
|
||
##########################
|
||
# mail:alias:creation
|
||
##########################
|
||
def newAlias(self, alias):
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'],'w')['adherent'][0]
|
||
if adh.alias().__len__() >= 3:
|
||
return self.index(error=u"Vous avez plus de 2 alias. Demander <20> un c<>bleur pour en rajouter.")
|
||
try:
|
||
adh.alias(alias)
|
||
adh.save()
|
||
del adh
|
||
except ValueError, e:
|
||
return self.index(error=e.args[0])
|
||
except RuntimeError:
|
||
return self.index(error=u"Vous poss<73>dez d<>j<EFBFBD> cet alias")
|
||
except EnvironmentError:
|
||
return self.index(error=u"Vous poss<73>dez d<>j<EFBFBD> cet alias")
|
||
return self.index(message=u'Alias enregistr<74>')
|
||
newAlias.exposed = True
|
||
|
||
|
||
##########################
|
||
# mail:sauver
|
||
##########################
|
||
def saveMailPrefs(self, forwarding_address, spanTreatment=None, contourneGreylist=False, rewriteMailHeaders=False):
|
||
if spanTreatment == 'no':
|
||
spanTreatment = 'accepte'
|
||
if spanTreatment == 'mark':
|
||
spanTreatment = 'marque'
|
||
if spanTreatment == 'drop':
|
||
spanTreatment = 'supprime'
|
||
|
||
if contourneGreylist == 'oui':
|
||
contourneGreylist = True
|
||
if rewriteMailHeaders == 'oui':
|
||
rewriteMailHeaders = True
|
||
|
||
try:
|
||
adh = self.__ldap.search('uid=' + cherrypy.session['uid'],'w')['adherent'][0]
|
||
MailConfig(cherrypy.session['uid'], forward=forwarding_address, spam=spanTreatment)
|
||
adh.contourneGreylist(contourneGreylist)
|
||
adh.rewriteMailHeaders(rewriteMailHeaders)
|
||
adh.save()
|
||
del adh
|
||
except ValueError, e:
|
||
return self.index(error=e.args[0])
|
||
except Exception, e:
|
||
return self.index(error=u"Une erreur est survenue lors de lenregistrement. V<>rifiez que l'adresse mail fournie est correcte.")
|
||
return self.index(message=u'Vos pr<70>f<EFBFBD>rences ont <20>t<EFBFBD> enregistr<74>es')
|
||
saveMailPrefs.exposed = True
|
||
|