Fait prendre un peu d'air au code

This commit is contained in:
Pierre-Elliott Bécue 2015-08-26 18:43:41 +02:00
parent 8ae5870468
commit 1353f00e17

310
objets.py
View file

@ -83,7 +83,7 @@ def new_cransldapobject(conn, dn, mode='ro', uldif=None, lockId=None):
else: else:
res = conn.search_s(dn, 0) res = conn.search_s(dn, 0)
if not res: if not res:
raise ValueError ('objet inexistant: %s' % dn) raise ValueError('objet inexistant: %s' % dn)
_, attrs = res[0] _, attrs = res[0]
classe = ObjectFactory.get(attrs['objectClass'][0]) classe = ObjectFactory.get(attrs['objectClass'][0])
@ -100,7 +100,8 @@ class CransLdapObject(object):
""" Qui peut faire quoi ? """ """ Qui peut faire quoi ? """
__slots__ = ("in_context", "conn", "lockId", "attrs", "_modifs", "dn", "parent_dn", "mode") __slots__ = ("in_context", "conn", "lockId", "attrs", "_modifs", "dn", "parent_dn", "mode")
can_be_by = { variables.created: [attributs.nounou], can_be_by = {
variables.created: [attributs.nounou],
variables.modified: [attributs.nounou], variables.modified: [attributs.nounou],
variables.deleted: [attributs.nounou], variables.deleted: [attributs.nounou],
} }
@ -169,7 +170,7 @@ class CransLdapObject(object):
else: else:
res = self.conn.search_s(dn, 0) res = self.conn.search_s(dn, 0)
if not res: if not res:
raise ValueError ('objet inexistant: %s' % dn) raise ValueError('objet inexistant: %s' % dn)
self.dn, ldif = res[0] self.dn, ldif = res[0]
# L'objet sortant de la base ldap, on ne fait pas de vérifications sur # L'objet sortant de la base ldap, on ne fait pas de vérifications sur
@ -202,7 +203,7 @@ class CransLdapObject(object):
for v in nldif[attr]: for v in nldif[attr]:
if v in vals: if v in vals:
vals.remove(v) vals.remove(v)
nvals = [nldif[attr][vals.index(v)] for v in vals ] nvals = [nldif[attr][vals.index(v)] for v in vals]
raise EnvironmentError("λv. str(Attr(v)) n'est peut-être pas une projection (ie non idempotente):", attr, nvals, vals) raise EnvironmentError("λv. str(Attr(v)) n'est peut-être pas une projection (ie non idempotente):", attr, nvals, vals)
def _id(self): def _id(self):
@ -259,11 +260,11 @@ class CransLdapObject(object):
def c_mul(a, b): def c_mul(a, b):
return eval(hex((long(a) * b) & 0xFFFFFFFFL)[:-1]) return eval(hex((long(a) * b) & 0xFFFFFFFFL)[:-1])
value = 0x345678 value = 0x345678
l=0 l = 0
keys = self.keys() keys = self.keys()
keys.sort() keys.sort()
for key in keys: for key in keys:
l+=len(self.attrs[key]) l += len(self.attrs[key])
for item in self.attrs[key]: for item in self.attrs[key]:
value = c_mul(1000003, value) ^ hash(item) value = c_mul(1000003, value) ^ hash(item)
value = value ^ l value = value ^ l
@ -272,25 +273,25 @@ class CransLdapObject(object):
return value return value
def __iter__(self): def __iter__(self):
if self.mode in [ 'w', 'rw' ]: if self.mode in ['w', 'rw']:
return self._modifs.__iter__() return self._modifs.__iter__()
else: else:
return self.attrs.__iter__() return self.attrs.__iter__()
def keys(self): def keys(self):
if self.mode in [ 'w', 'rw' ]: if self.mode in ['w', 'rw']:
return self._modifs.keys() return self._modifs.keys()
else: else:
return self.attrs.keys() return self.attrs.keys()
def values(self): def values(self):
if self.mode in [ 'w', 'rw' ]: if self.mode in ['w', 'rw']:
return self._modifs.values() return self._modifs.values()
else: else:
return self.attrs.values() return self.attrs.values()
def items(self): def items(self):
if self.mode in [ 'w', 'rw' ]: if self.mode in ['w', 'rw']:
return self._modifs.items() return self._modifs.items()
else: else:
return self.attrs.items() return self.attrs.items()
@ -438,7 +439,7 @@ class CransLdapObject(object):
try: try:
if self.conn.search(dn=self.dn): if self.conn.search(dn=self.dn):
raise ValueError ('objet existant: %s' % self.dn) raise ValueError('objet existant: %s' % self.dn)
except ldap.NO_SUCH_OBJECT: except ldap.NO_SUCH_OBJECT:
pass pass
@ -453,8 +454,8 @@ class CransLdapObject(object):
ldif = self._modifs.to_ldif() ldif = self._modifs.to_ldif()
for attr in binary: for attr in binary:
ldif['%s;binary' % attr]=ldif[attr] ldif['%s;binary' % attr] = ldif[attr]
del(ldif[attr]) del ldif[attr]
# Création de la requête LDAP # Création de la requête LDAP
modlist = addModlist(ldif) modlist = addModlist(ldif)
# Requête LDAP de création de l'objet # Requête LDAP de création de l'objet
@ -595,9 +596,9 @@ class CransLdapObject(object):
for attr in binary: for attr in binary:
ldif['%s;binary' % (attr,)] = ldif[attr] ldif['%s;binary' % (attr,)] = ldif[attr]
orig_ldif['%s;binary' % (attr,)] = orig_ldif.get(attr, []) orig_ldif['%s;binary' % (attr,)] = orig_ldif.get(attr, [])
del(ldif[attr]) del ldif[attr]
try: try:
del(orig_ldif[attr]) del orig_ldif[attr]
except KeyError: except KeyError:
pass pass
@ -611,10 +612,10 @@ class CransLdapObject(object):
return default return default
def __getitem__(self, attr, default=None): def __getitem__(self, attr, default=None):
if self._modifs.has_key(attr) and self.mode in [ 'w', 'rw' ]: if self._modifs.has_key(attr) and self.mode in ['w', 'rw']:
return attributs.AttrsList(self, attr, [ v for v in self._modifs[attr] ]) return attributs.AttrsList(self, attr, [v for v in self._modifs[attr]])
elif self.attrs.has_key(attr): elif self.attrs.has_key(attr):
return attributs.AttrsList(self, attr, [ v for v in self.attrs[attr] ]) return attributs.AttrsList(self, attr, [v for v in self.attrs[attr]])
elif self.has_key(attr): elif self.has_key(attr):
return attributs.AttrsList(self, attr, []) if default is None else default return attributs.AttrsList(self, attr, []) if default is None else default
else: else:
@ -700,8 +701,8 @@ class CransLdapObject(object):
if not no_concurrent_lock and not attributs.AttributeFactory.get(attr).concurrent and self._modifs.get(attr, []) == self.attrs.get(attr, []) and attrs_before_verif != self.attrs.get(attr, []): if not no_concurrent_lock and not attributs.AttributeFactory.get(attr).concurrent and self._modifs.get(attr, []) == self.attrs.get(attr, []) and attrs_before_verif != self.attrs.get(attr, []):
if not self.in_context: if not self.in_context:
cranslib.deprecated.usage("Des locks ne devrait être ajoutés que dans un context manager", level=2) cranslib.deprecated.usage("Des locks ne devrait être ajoutés que dans un context manager", level=2)
self.conn.lockholder.addlock("dn", "%s_%s" % (self.dn.replace('=', '-').replace(',','_'), attr), self.lockId) self.conn.lockholder.addlock("dn", "%s_%s" % (self.dn.replace('=', '-').replace(',', '_'), attr), self.lockId)
locked.append(("dn", "%s_%s" % (self.dn.replace('=', '-').replace(',','_'), attr), self.lockId)) locked.append(("dn", "%s_%s" % (self.dn.replace('=', '-').replace(',', '_'), attr), self.lockId))
try: try:
# une fois le lock acquit, on vérifie que l'attribut n'a pas été édité entre temps # une fois le lock acquit, on vérifie que l'attribut n'a pas été édité entre temps
if self.conn.search(dn=self.dn, scope=0)[0].get(attr, []) != self.attrs.get(attr, []): if self.conn.search(dn=self.dn, scope=0)[0].get(attr, []) != self.attrs.get(attr, []):
@ -723,7 +724,7 @@ class CransLdapObject(object):
self.conn.lockholder.removelock(attr, str(attribut), self.lockId) self.conn.lockholder.removelock(attr, str(attribut), self.lockId)
# Si on remet la valeur antérieure au lock, on le libère # Si on remet la valeur antérieure au lock, on le libère
if not attributs.AttributeFactory.get(attr).concurrent and self._modifs.get(attr, []) != self.attrs.get(attr, []) and attrs_before_verif == self.attrs.get(attr, []): if not attributs.AttributeFactory.get(attr).concurrent and self._modifs.get(attr, []) != self.attrs.get(attr, []) and attrs_before_verif == self.attrs.get(attr, []):
self.conn.lockholder.removelock("dn", "%s_%s" % (self.dn.replace('=', '-').replace(',','_'), attr), self.lockId) self.conn.lockholder.removelock("dn", "%s_%s" % (self.dn.replace('=', '-').replace(',', '_'), attr), self.lockId)
# On met à jour self._modifs avec les nouvelles valeurs # On met à jour self._modifs avec les nouvelles valeurs
self._modifs[attr] = attrs_before_verif self._modifs[attr] = attrs_before_verif
@ -780,7 +781,7 @@ class CransLdapObject(object):
Améliorations possibles: Améliorations possibles:
- Vérifier les blacklistes des machines pour les adhérents ? - Vérifier les blacklistes des machines pour les adhérents ?
""" """
blacklist_liste=[] blacklist_liste = []
# blacklistes virtuelle si on est un adhérent pour carte étudiant et chambre invalides # blacklistes virtuelle si on est un adhérent pour carte étudiant et chambre invalides
if isinstance(self, adherent): if isinstance(self, adherent):
if self['chbre'][0] == '????': if self['chbre'][0] == '????':
@ -792,11 +793,11 @@ class CransLdapObject(object):
blacklist_liste.append(bl) blacklist_liste.append(bl)
blacklist_liste.extend(bl for bl in self.get("blacklist", []) if bl.is_actif()) blacklist_liste.extend(bl for bl in self.get("blacklist", []) if bl.is_actif())
if excepts: if excepts:
return [ b for b in blacklist_liste if b['type'] not in excepts ] return [b for b in blacklist_liste if b['type'] not in excepts]
else: else:
return blacklist_liste return blacklist_liste
def blacklist(self, sanction, commentaire, debut="now", fin = '-'): def blacklist(self, sanction, commentaire, debut="now", fin='-'):
""" """
Blacklistage de la ou de toutes la machines du propriétaire Blacklistage de la ou de toutes la machines du propriétaire
* debut et fin sont le nombre de secondes depuis epoch * debut et fin sont le nombre de secondes depuis epoch
@ -858,24 +859,41 @@ class InetOrgPerson(CransLdapObject):
class proprio(CransLdapObject): class proprio(CransLdapObject):
u""" Un propriétaire de machine (adhérent, club…) """ u""" Un propriétaire de machine (adhérent, club…) """
__slots__ = ("_machines", "_factures", "full") __slots__ = ("_machines", "_factures", "full")
can_be_by = { variables.created: [attributs.nounou, attributs.bureau, attributs.cableur], can_be_by = {
variables.modified: [attributs.nounou, attributs.bureau, attributs.soi, attributs.cableur], variables.created: [
variables.deleted: [attributs.nounou, attributs.bureau,], attributs.nounou,
attributs.bureau,
attributs.cableur,
],
variables.modified: [
attributs.nounou,
attributs.bureau,
attributs.soi,
attributs.cableur,
],
variables.deleted: [
attributs.nounou,
attributs.bureau,
],
} }
crans_account_attribs = [attributs.uid, attributs.canonicalAlias, attributs.solde, crans_account_attribs = [
attributs.uid, attributs.canonicalAlias, attributs.solde,
attributs.contourneGreylist, attributs.derniereConnexion, attributs.contourneGreylist, attributs.derniereConnexion,
attributs.homepageAlias, attributs.loginShell, attributs.gecos, attributs.homepageAlias, attributs.loginShell, attributs.gecos,
attributs.uidNumber, attributs.homeDirectory, attributs.uidNumber, attributs.homeDirectory,
attributs.gidNumber, attributs.userPassword, attributs.gidNumber, attributs.userPassword,
attributs.mailAlias, attributs.cn, attributs.rewriteMailHeaders, attributs.mailAlias, attributs.cn, attributs.rewriteMailHeaders,
attributs.mailExt, attributs.compteWiki, attributs.droits, attributs.mailExt, attributs.compteWiki, attributs.droits,
attributs.shadowExpire] attributs.shadowExpire,
default_attribs = [attributs.nom, attributs.chbre, attributs.paiement, attributs.info, ]
default_attribs = [
attributs.nom, attributs.chbre, attributs.paiement, attributs.info,
attributs.blacklist, attributs.controle, attributs.historique, attributs.blacklist, attributs.controle, attributs.historique,
attributs.debutAdhesion, attributs.finAdhesion, attributs.debutConnexion, attributs.debutAdhesion, attributs.finAdhesion, attributs.debutConnexion,
attributs.finConnexion] attributs.finConnexion,
]
@property @property
def attribs(self): def attribs(self):
@ -920,15 +938,15 @@ class proprio(CransLdapObject):
self['uidNumber'] = [] self['uidNumber'] = []
self['gidNumber'] = [] self['gidNumber'] = []
self['gecos'] = [] self['gecos'] = []
self['shadowExpire']=[] self['shadowExpire'] = []
self['derniereConnexion']=[] self['derniereConnexion'] = []
self['mailExt']=[] self['mailExt'] = []
self['uid' ]=[] self['uid'] = []
self._modifs['objectClass'] = [u'adherent'] self._modifs['objectClass'] = [u'adherent']
self.full = False self.full = False
def compte(self, login = None, uidNumber=0, hash_pass = '', shell=config.login_shell): def compte(self, login=None, uidNumber=0, hash_pass='', shell=config.login_shell):
u"""Renvoie le nom du compte crans. S'il n'existe pas, et que login u"""Renvoie le nom du compte crans. S'il n'existe pas, et que login
est précisé, le crée.""" est précisé, le crée."""
@ -952,14 +970,14 @@ class proprio(CransLdapObject):
raise ValueError('Création du compte impossible : /var/mail/%s existant' % str(login)) raise ValueError('Création du compte impossible : /var/mail/%s existant' % str(login))
self._modifs['objectClass'] = [u'adherent', u'cransAccount', u'posixAccount', u'shadowAccount'] self._modifs['objectClass'] = [u'adherent', u'cransAccount', u'posixAccount', u'shadowAccount']
self['uid' ] = [login] self['uid'] = [login]
self['homeDirectory'] = [home] self['homeDirectory'] = [home]
self['mail'] = [login + u"@crans.org"] self['mail'] = [login + u"@crans.org"]
calias = crans_utils.strip_spaces(fn) + u'.' + crans_utils.strip_spaces(ln) + '@crans.org' calias = crans_utils.strip_spaces(fn) + u'.' + crans_utils.strip_spaces(ln) + '@crans.org'
if crans_utils.mailexist(calias): if crans_utils.mailexist(calias):
calias = login calias = login
self['canonicalAlias'] = [calias] self['canonicalAlias'] = [calias]
self['cn'] = [ fn + u' ' + ln ] self['cn'] = [fn + u' ' + ln]
self['loginShell'] = [unicode(shell)] self['loginShell'] = [unicode(shell)]
self['userPassword'] = [unicode(hash_pass)] self['userPassword'] = [unicode(hash_pass)]
self["solde"] = 0.0 self["solde"] = 0.0
@ -1016,7 +1034,11 @@ class proprio(CransLdapObject):
def fin_adhesion(self): def fin_adhesion(self):
"""Retourne la date de fin d'adhésion""" """Retourne la date de fin d'adhésion"""
return max([float(facture.get('finAdhesion', [crans_utils.from_generalized_time_format(attributs.finAdhesion.default)])[0]) for facture in self.factures(refresh=True, mode="ro") if facture.get('controle', [''])[0] != u"FALSE" and facture.get('recuPaiement', [''])[0] != ''] + [0.0]) return max([
float(facture.get('finAdhesion', [crans_utils.from_generalized_time_format(attributs.finAdhesion.default)])[0])
for facture in self.factures(refresh=True, mode="ro")
if facture.get('controle', [''])[0] != u"FALSE" and facture.get('recuPaiement', [''])[0] != ''
] + [0.0])
def fin_connexion_datetime(self): def fin_connexion_datetime(self):
return datetime.datetime.fromtimestamp(self.fin_connexion()) return datetime.datetime.fromtimestamp(self.fin_connexion())
@ -1026,7 +1048,11 @@ class proprio(CransLdapObject):
def fin_connexion(self): def fin_connexion(self):
"""Retourne la date de fin de connexion""" """Retourne la date de fin de connexion"""
return max([float(facture.get('finConnexion', [crans_utils.from_generalized_time_format(attributs.finConnexion.default)])[0]) for facture in self.factures(refresh=True, mode="ro") if facture.get('controle', [''])[0] != u"FALSE" and facture.get('recuPaiement', [''])[0] != ''] + [0.0]) return max([
float(facture.get('finConnexion', [crans_utils.from_generalized_time_format(attributs.finConnexion.default)])[0])
for facture in self.factures(refresh=True, mode="ro")
if facture.get('controle', [''])[0] != u"FALSE" and facture.get('recuPaiement', [''])[0] != ''
] + [0.0])
def paiement_ok(self, no_bl=False): def paiement_ok(self, no_bl=False):
u""" u"""
@ -1069,7 +1095,7 @@ class proprio(CransLdapObject):
if new_solde < config.impression.decouvert: if new_solde < config.impression.decouvert:
raise ValueError(u"Solde minimal atteint, opération non effectuée.") raise ValueError(u"Solde minimal atteint, opération non effectuée.")
transaction = u"credit" if diff >=0 else u"debit" transaction = u"credit" if diff >= 0 else u"debit"
new_solde = u"%.2f" % new_solde new_solde = u"%.2f" % new_solde
self.history_add(login, u"%s %.2f Euros [%s]" % (transaction, abs(diff), comment)) self.history_add(login, u"%s %.2f Euros [%s]" % (transaction, abs(diff), comment))
self["solde"] = new_solde self["solde"] = new_solde
@ -1082,7 +1108,7 @@ class proprio(CransLdapObject):
"""Renvoie la liste des machines""" """Renvoie la liste des machines"""
if self._machines is None or refresh: if self._machines is None or refresh:
try: try:
self._machines = self.conn.search(u'mid=*', dn = self.dn, scope = 1, mode=self.mode if mode is None else mode) self._machines = self.conn.search(u'mid=*', dn=self.dn, scope=1, mode=self.mode if mode is None else mode)
for m in self._machines: for m in self._machines:
m._proprio = self m._proprio = self
except ldap.NO_SUCH_OBJECT: except ldap.NO_SUCH_OBJECT:
@ -1098,7 +1124,7 @@ class proprio(CransLdapObject):
refresh = True refresh = True
if self._factures is None or refresh: if self._factures is None or refresh:
try: try:
self._factures = self.conn.search(u'fid=*', dn = self.dn, scope = 1, mode=mode) self._factures = self.conn.search(u'fid=*', dn=self.dn, scope=1, mode=mode)
for m in self._factures: for m in self._factures:
m._proprio = self m._proprio = self
# Si on manipule un objet pas encore enregistré dans la la bdd # Si on manipule un objet pas encore enregistré dans la la bdd
@ -1160,17 +1186,38 @@ class proprio(CransLdapObject):
class machine(CransLdapObject): class machine(CransLdapObject):
u""" Une machine """ u""" Une machine """
__slots__ = ("_proprio", "_certificats") __slots__ = ("_proprio", "_certificats")
can_be_by = { variables.created: [attributs.nounou, attributs.bureau, attributs.cableur, attributs.parent, attributs.respo], can_be_by = {
variables.modified: [attributs.nounou, attributs.bureau, attributs.cableur, attributs.parent, attributs.respo], variables.created: [
variables.deleted: [attributs.nounou, attributs.bureau, attributs.cableur, attributs.parent, attributs.respo], attributs.nounou,
attributs.bureau,
attributs.cableur,
attributs.parent,
attributs.respo,
],
variables.modified: [
attributs.nounou,
attributs.bureau,
attributs.cableur,
attributs.parent,
attributs.respo,
],
variables.deleted: [
attributs.nounou,
attributs.bureau,
attributs.cableur,
attributs.parent,
attributs.respo,
],
} }
attribs = [attributs.mid, attributs.macAddress, attributs.host, attribs = [
attributs.mid, attributs.macAddress, attributs.host,
attributs.rid, attributs.info, attributs.blacklist, attributs.hostAlias, attributs.rid, attributs.info, attributs.blacklist, attributs.hostAlias,
attributs.exempt, attributs.portTCPout, attributs.portTCPin, attributs.exempt, attributs.portTCPout, attributs.portTCPin,
attributs.portUDPout, attributs.portUDPin, attributs.sshFingerprint, attributs.portUDPout, attributs.portUDPin, attributs.sshFingerprint,
attributs.ipHostNumber, attributs.ip6HostNumber, attributs.historique, attributs.ipHostNumber, attributs.ip6HostNumber, attributs.historique,
attributs.dnsIpv6, attributs.machineAlias] attributs.dnsIpv6, attributs.machineAlias,
]
def __unicode__(self): def __unicode__(self):
return u"%s : host=%s" % (self.__class__.__name__, self['host'][0]) return u"%s : host=%s" % (self.__class__.__name__, self['host'][0])
@ -1191,7 +1238,7 @@ class machine(CransLdapObject):
qu'un de ses certificats l'utilise. qu'un de ses certificats l'utilise.
""" """
if attr in ['host', 'hostAlias']: if attr in ['host', 'hostAlias']:
deleted = [ value for value in self[attr] if value not in values ] deleted = [value for value in self[attr] if value not in values]
for domain in deleted: for domain in deleted:
for certificat in self.certificats(): for certificat in self.certificats():
if domain in certificat['hostCert']: if domain in certificat['hostCert']:
@ -1207,7 +1254,7 @@ class machine(CransLdapObject):
"""Renvoie la liste des certificats de la machine""" """Renvoie la liste des certificats de la machine"""
if refresh or self._certificats is None: if refresh or self._certificats is None:
try: try:
self._certificats = self.conn.search(u'xid=*', dn = self.dn, scope = 1, mode=self.mode) self._certificats = self.conn.search(u'xid=*', dn=self.dn, scope=1, mode=self.mode)
for m in self._certificats: for m in self._certificats:
m._machine = self m._machine = self
except ldap.NO_SUCH_OBJECT: except ldap.NO_SUCH_OBJECT:
@ -1216,7 +1263,7 @@ class machine(CransLdapObject):
def blacklist_actif(self, excepts=[]): def blacklist_actif(self, excepts=[]):
u"""Renvoie la liste des blacklistes actives sur la machine et le proprio""" u"""Renvoie la liste des blacklistes actives sur la machine et le proprio"""
black=self.proprio().blacklist_actif(excepts) black = self.proprio().blacklist_actif(excepts)
black.extend(super(machine, self).blacklist_actif(excepts)) black.extend(super(machine, self).blacklist_actif(excepts))
return black return black
@ -1379,7 +1426,8 @@ class adherent(proprio):
@property @property
def attribs(self): def attribs(self):
return super(adherent, self).attribs + [attributs.aid, attributs.prenom, attributs.tel, return super(adherent, self).attribs + [
attributs.aid, attributs.prenom, attributs.tel,
attributs.mail, attributs.mailInvalide, attributs.charteMA, attributs.mail, attributs.mailInvalide, attributs.charteMA,
attributs.derniereConnexion, attributs.gpgFingerprint, attributs.derniereConnexion, attributs.gpgFingerprint,
attributs.carteEtudiant, attributs.etudes, attributs.carteEtudiant, attributs.etudes,
@ -1402,13 +1450,13 @@ class adherent(proprio):
def clubs(self): def clubs(self):
"""Renvoie la liste des clubs dont l'adherent est responsable""" """Renvoie la liste des clubs dont l'adherent est responsable"""
if self._clubs is None: if self._clubs is None:
self._clubs = self.conn.search(u'responsable=%s' % self['aid'][0], scope = 1, mode=self.mode) self._clubs = self.conn.search(u'responsable=%s' % self['aid'][0], scope=1, mode=self.mode)
return self._clubs return self._clubs
def imprimeur_clubs(self): def imprimeur_clubs(self):
"""Renvoie la liste des clubs dont l'adherent est imprimeur""" """Renvoie la liste des clubs dont l'adherent est imprimeur"""
if self._imprimeur_clubs is None: if self._imprimeur_clubs is None:
self._imprimeur_clubs = self.conn.search(u'imprimeurClub=%s' % self['aid'][0], scope = 1, mode=self.mode) self._imprimeur_clubs = self.conn.search(u'imprimeurClub=%s' % self['aid'][0], scope=1, mode=self.mode)
return self._imprimeur_clubs return self._imprimeur_clubs
def delete(self, comm="", login=None): def delete(self, comm="", login=None):
@ -1421,9 +1469,23 @@ class adherent(proprio):
class club(proprio): class club(proprio):
u"""Club crans""" u"""Club crans"""
__slots__ = () __slots__ = ()
can_be_by = { variables.created: [attributs.nounou, attributs.bureau, attributs.cableur], can_be_by = {
variables.modified: [attributs.nounou, attributs.bureau, attributs.respo, attributs.cableur, attributs.soi], variables.created: [
variables.deleted: [attributs.nounou, attributs.bureau], attributs.nounou,
attributs.bureau,
attributs.cableur,
],
variables.modified: [
attributs.nounou,
attributs.bureau,
attributs.respo,
attributs.cableur,
attributs.soi,
],
variables.deleted: [
attributs.nounou,
attributs.bureau,
],
} }
ldap_name = "club" ldap_name = "club"
@ -1488,46 +1550,88 @@ class machineWifi(machine):
@crans_object @crans_object
class machineCrans(machine): class machineCrans(machine):
__slots__ = () __slots__ = ()
can_be_by = { variables.created: [attributs.nounou], can_be_by = {
variables.modified: [attributs.nounou], variables.created: [
variables.deleted: [attributs.nounou], attributs.nounou,
],
variables.modified: [
attributs.nounou,
],
variables.deleted: [
attributs.nounou,
],
} }
attribs = machine.attribs + [attributs.prise, attributs.nombrePrises] attribs = machine.attribs + [
attributs.prise, attributs.nombrePrises,
]
ldap_name = "machineCrans" ldap_name = "machineCrans"
@crans_object @crans_object
class borneWifi(machine): class borneWifi(machine):
__slots__ = () __slots__ = ()
can_be_by = { variables.created: [attributs.nounou], can_be_by = {
variables.modified: [attributs.nounou], variables.created: [
variables.deleted: [attributs.nounou], attributs.nounou,
],
variables.modified: [
attributs.nounou,
],
variables.deleted: [
attributs.nounou,
],
} }
attribs = machine.attribs + [attributs.canal, attributs.puissance, attributs.hotspot, attribs = machine.attribs + [
attributs.prise, attributs.positionBorne, attributs.nvram] attributs.canal, attributs.puissance, attributs.hotspot,
attributs.prise, attributs.positionBorne, attributs.nvram,
]
ldap_name = "borneWifi" ldap_name = "borneWifi"
@crans_object @crans_object
class switchCrans(machine): class switchCrans(machine):
__slots__ = () __slots__ = ()
can_be_by = { variables.created: [attributs.nounou], can_be_by = {
variables.modified: [attributs.nounou], variables.created: [
variables.deleted: [attributs.nounou], attributs.nounou,
],
variables.modified: [
attributs.nounou,
],
variables.deleted: [
attributs.nounou,
],
} }
attribs = machine.attribs + [attributs.nombrePrises] attribs = machine.attribs + [
attributs.nombrePrises,
]
ldap_name = "switchCrans" ldap_name = "switchCrans"
@crans_object @crans_object
class facture(CransLdapObject): class facture(CransLdapObject):
__slots__ = ("_proprio", "_recuPaiement") __slots__ = ("_proprio", "_recuPaiement")
can_be_by = { variables.created: [attributs.nounou, attributs.bureau, attributs.cableur], can_be_by = {
variables.modified: [attributs.nounou, attributs.bureau, attributs.cableur], variables.created: [
variables.deleted: [attributs.nounou, attributs.bureau, attributs.cableur], attributs.nounou,
attributs.bureau,
attributs.cableur,
],
variables.modified: [
attributs.nounou,
attributs.bureau,
attributs.cableur,
],
variables.deleted: [
attributs.nounou,
attributs.bureau,
attributs.cableur,
],
} }
attribs = [attributs.fid, attributs.modePaiement, attributs.recuPaiement, attribs = [
attributs.fid, attributs.modePaiement, attributs.recuPaiement,
attributs.historique, attributs.article, attributs.info, attributs.historique, attributs.article, attributs.info,
attributs.debutAdhesion, attributs.finAdhesion, attributs.debutConnexion, attributs.debutAdhesion, attributs.finAdhesion, attributs.debutConnexion,
attributs.finConnexion, attributs.controle ] attributs.finConnexion, attributs.controle,
]
ldap_name = "facture" ldap_name = "facture"
def __unicode__(self): def __unicode__(self):
@ -1604,19 +1708,41 @@ class facture(CransLdapObject):
@crans_object @crans_object
class baseCert(CransLdapObject): class baseCert(CransLdapObject):
__slots__ = ("_machine",) __slots__ = ("_machine",)
can_be_by = { variables.created: [attributs.nounou, attributs.bureau, attributs.parent], can_be_by = {
variables.modified: [attributs.nounou, attributs.bureau, attributs.parent], variables.created: [
variables.deleted: [attributs.nounou, attributs.bureau, attributs.parent], attributs.nounou,
attributs.bureau,
attributs.parent,
],
variables.modified: [
attributs.nounou,
attributs.bureau,
attributs.parent,
],
variables.deleted: [
attributs.nounou,
attributs.bureau,
attributs.parent,
],
} }
default_attribs = [ attributs.xid, attributs.certificat, attributs.hostCert, attributs.historique, default_attribs = [
attributs.info, attributs.csr ] attributs.xid, attributs.certificat, attributs.hostCert, attributs.historique,
attributs.info, attributs.csr,
]
tlsa_attribs = [ attributs.certificatUsage, attributs.selector, attributs.matchingType, tlsa_attribs = [
attributs.portTCPin, attributs.portUDPin] attributs.certificatUsage, attributs.selector, attributs.matchingType,
x509_attribs = [ attributs.issuerCN, attributs.start, attributs.end, attributs.portTCPin, attributs.portUDPin,
attributs.crlUrl, attributs.revocked, attributs.serialNumber ] ]
private_attribs = [ attributs.privatekey, attributs.encrypted ] x509_attribs = [
attributs.issuerCN, attributs.start, attributs.end,
attributs.crlUrl, attributs.revocked, attributs.serialNumber,
]
private_attribs = [
attributs.privatekey, attributs.encrypted,
]
@property @property
def attribs(self): def attribs(self):
@ -1651,9 +1777,9 @@ class baseCert(CransLdapObject):
s'il est réèlement présent dans les données du certificat. s'il est réèlement présent dans les données du certificat.
""" """
if attr in ['hostCert']: if attr in ['hostCert']:
deleted = [ value for value in self[attr] if value not in values ] deleted = [value for value in self[attr] if value not in values]
for domain in deleted: for domain in deleted:
if domain in [self['certificat'][0]['subject']['CN']] + self['certificat'][0]['extensions'].get('subjectAltName',[]): if domain in [self['certificat'][0]['subject']['CN']] + self['certificat'][0]['extensions'].get('subjectAltName', []):
raise EnvironmentError("Vous ne pouvez pas retirer le domaine %s alors qu'il est déclaré dans le certificat" % domain) raise EnvironmentError("Vous ne pouvez pas retirer le domaine %s alors qu'il est déclaré dans le certificat" % domain)
def private(self, privatekey, encrypted): def private(self, privatekey, encrypted):
@ -1663,8 +1789,8 @@ class baseCert(CransLdapObject):
return return
self._modifs['objectClass'].append(u"privateKey") self._modifs['objectClass'].append(u"privateKey")
#self.attribs.extend(self.private_attribs) #self.attribs.extend(self.private_attribs)
self['encrypted']=encrypted self['encrypted'] = encrypted
self['privatekey']=privatekey self['privatekey'] = privatekey
def tlsa(self, certificatUsage, matchingType): def tlsa(self, certificatUsage, matchingType):
if not self.mode in ['w', 'rw']: if not self.mode in ['w', 'rw']:
@ -1673,9 +1799,9 @@ class baseCert(CransLdapObject):
return return
self._modifs['objectClass'].append(u"TLSACert") self._modifs['objectClass'].append(u"TLSACert")
#self.attribs.extend(self.tlsa_attribs) #self.attribs.extend(self.tlsa_attribs)
self['certificatUsage']=certificatUsage self['certificatUsage'] = certificatUsage
self['matchingType']=matchingType self['matchingType'] = matchingType
self['selector']=0 self['selector'] = 0
def x509(self, issuerCN, start, end, serialNumber, crlUrl=None): def x509(self, issuerCN, start, end, serialNumber, crlUrl=None):
if not self.mode in ['w', 'rw']: if not self.mode in ['w', 'rw']: