Ajout des modules initiaux

darcs-hash:20070124114812-f46e9-171ef12f1e1b89ae005adf4aab6f6535fb9289e6.gz
This commit is contained in:
gdetrez 2007-01-24 12:48:12 +01:00
parent 8713311bc1
commit ed3ab40ccd
80 changed files with 4852 additions and 5 deletions

View file

@ -0,0 +1,249 @@
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
# ##################################################################################################### #
# Machines
# ##################################################################################################### #
# Description:
# Affiche la liste des machies, les infons sur une machine et permet des modifications
# Informations:
#
# Pages:
# index:liste des machines + le reste (AJAX)
#
# ##################################################################################################### #
import cherrypy, sys, os, datetime
from time import strftime, localtime, time
# libraries crans
sys.path.append('/usr/scripts/gestion/')
import crans.cp
if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
from ldap_crans_test import *
# print("mesmachines : unsing test ldap : env=" + cherrypy.config.configMap["global"]["server.environment"])
else:
from ldap_crans import *
# print("mesmachines : unsing prod ldap : env=" + cherrypy.config.configMap["global"]["server.environment"])
from ClassesIntranet.ModuleBase import ModuleBase
class main(ModuleBase):
def title(self):
return "Mes Machines"
def icon(self):
return "machines_icon_fixe.png"
def AJAXListeMachines(self):
adh = cherrypy.session['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['mid'] = une_machine.id()
# type
if une_machine.objectClass == 'machineFixe':
machineInfos['type'] = 'fixe'
#machineInfos['type'] = 'Machine fixe'
else:
machineInfos['type'] = 'wifi'
#machineInfos['type'] = 'Machine wifi'
# clef ipsec
machines.append(machineInfos)
return {"machines":machines}
AJAXListeMachines.exposed = True
def AJAXMachineInfo(self, mid):
try:
machine = cherrypy.session['LDAP'].search('mid=' + mid)['machine'][0]
if machine.proprietaire().mail() != cherrypy.session['uid']:
raise Exception
# zamok -> pour tester l'affichage des ports, des alias
#machine = cherrypy.session['LDAP'].search('mid=896')['machine'][0]
machineInfos = {}
# nom, mac, mid, ip
machineInfos['nom'] = machine.nom()
machineInfos['nomCourt'] = machine.nom().split('.',1)[0]
machineInfos['mac'] = machine.mac()
machineInfos['mid'] = machine.id()
machineInfos['ip'] = machine.ip()
# type
if machine.objectClass == 'machineFixe':
machineInfos['type'] = 'fixe'
else:
machineInfos['type'] = 'wifi'
# clef ipsec
try:
machineInfos['ipsec'] = machine.ipsec()
except:
machineInfos['ipsec'] = ''
# alias
machineInfos['alias'] = machine.alias()
# blacklists
machineInfos['blacklist'] = []
for blacklist_type in machine.blacklist_all()[0].keys():
for (begin, end) in machine.blacklist_all()[0][blacklist_type]:
blacklist = {}
blacklist['begin'] = strftime('%d/%m/%Y %H:%M', localtime(int(begin)))
blacklist['end'] = strftime('%d/%m/%Y %H:%M', localtime(int(end)))
blacklist['type'] = blacklist_type
blacklist['actif'] = 1
machineInfos['blacklist'].append(blacklist)
for blacklist_type in machine.blacklist_all()[1].keys():
for (begin, end) in machine.blacklist_all()[1][blacklist_type]:
blacklist = {}
blacklist['begin'] = strftime('%d/%m/%Y %H:%M', localtime(int(begin)))
blacklist['end'] = strftime('%d/%m/%Y %H:%M', localtime(int(end)))
blacklist['type'] = blacklist_type
blacklist['actif'] = 0
machineInfos['blacklist'].append(blacklist)
# ports
machineInfos['ports'] = []
if machine.portTCPin() != []:
machineInfos['ports'].append(
{
'titre':'Ports TCP ouvert ext->machine',
'ports':machine.portTCPin()
}
)
if machine.portTCPout() != []:
machineInfos['ports'].append(
{
'titre':'Ports TCP ouvert machine->ext',
'ports':machine.portTCPout()
}
)
if machine.portUDPin() != []:
machineInfos['ports'].append(
{
'titre':'Ports UDP ouvert ext->machine',
'ports':machine.portUDPin()
}
)
if machine.portUDPout() != []:
machineInfos['ports'].append(
{
'titre':'Ports TCP ouvert machine->ext',
'ports':machine.portUDPout()
}
)
return machineInfos
except Exception, e:
return {"erreur":str(e)}
AJAXMachineInfo.exposed = True
##########################
# affichage
##########################
#
# methode qui affiche la template
#
def index(self):
return {
'template' :'machines',
'values' :{},
'stylesheets' :['machines.css'],
'scripts':['machines.js'],
}
index.exposed = True
###########################################################################
# methodes pour changer
# des valeurs
###########################################################################
#
##########################
# machine:nom
##########################
def AJAXChangerNom(self, mid, nouveauNom):
try:
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
mach = cherrypy.session['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.")
anciennom = mach.nom()
nouveauNom = mach.nom(nouveauNom)
mach.save()
del mach
except ValueError, e:
raise e
#return {'error':str(e)}
crans.cp.log("Changer nom machine : %s->%s" % (anciennom, nouveauNom), "MESMACHINES")
return {'message':u"Modification réussie", 'mid':mid}
AJAXChangerNom.exposed = True
##########################
# machine:mac
##########################
def AJAXchangerMAC(self, mid, nouvelleMAC):
try:
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
mach = cherrypy.session['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.")
anciennemac = mach.mac()
nommachine = mach.nom()
mach.mac(nouvelleMAC)
mach.save()
del mach
except ValueError, e:
return {'error':e.args[0]}
crans.cp.log("Change mac machine %s : %s->%s" % (nommachine, anciennemac, nouvelleMAC), "MESMACHINES")
return {'message':u"Modification réussie", 'mid':mid}
AJAXchangerMAC.exposed = True
##########################
# machine:suppression
##########################
def AJAXSupprimerMachine(self, mid):
try:
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
mach = cherrypy.session['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.")
mach.delete()
except ValueError, e:
return {'error':e.args[0]}
crans.cp.log("Machine supprimee", "MACHINES")
return {'message':u"Machine supprimée"}
AJAXSupprimerMachine.exposed = True
##########################
# machine:creation
##########################
def AJAXCreerMachine(self, nomNouvelleMachine, MACNouvelleMachine, typeNouvelleMachine):
adh = cherrypy.session['LDAP'].search('uid=' + cherrypy.session['uid'])['adherent'][0]
if typeNouvelleMachine=='fixe' and adh.droits() == [] and adh.machines_fixes() != []:
return {'error':'Vous avez deja une machine fixe. Vous ne pouvez ajouter que des machines WiFi.'}
try:
if typeNouvelleMachine=='wifi':
m = MachineWifi(adh)
elif typeNouvelleMachine=='fixe':
m = MachineFixe(adh)
else:
raise Exception, "type de machine inconnu : %s " % typeNouvelleMachine
m.nom(nomNouvelleMachine)
m.mac(MACNouvelleMachine)
m.ip("<automatique>")
message = m.save()
del m
except ValueError, e:
del m
return {'error':e.args[0].replace("\n","\\n")}
crans.cp.log("Nouvelle machine %s" % nomNouvelleMachine, "MACHINES")
return {'message':u"Machine enregistrée avec succès"}
AJAXCreerMachine.exposed = True

View file

@ -0,0 +1,160 @@
/*************************************************************
..
.... ............ ........
. ....... . .... ..
. ... .. .. .. .. ..... . ..
.. .. ....@@@. .. . ........ .
.. . .. ..@.@@..@@. .@@@@@@@ @@@@@@. ....
.@@@@. .@@@@. .@@@@..@@.@@..@@@..@@@..@@@@.... ....
@@@@... .@@@.. @@ @@ .@..@@..@@...@@@. .@@@@@. ..
.@@@.. . @@@. @@.@@..@@.@@..@@@ @@ .@@@@@@.. .....
...@@@.... @@@ .@@.......... ........ ..... ..
. ..@@@@.. . .@@@@. .. ....... . .............
. .. .... .. .. . ... ....
. . .... ............. .. ...
.. .. ... ........ ... ...
................................
==============================================================
macines.css - Intranet Style
Copyright (c) 2006 by www.crans.org
**************************************************************/
#globalDiv {
padding-left : 20%;
margin:0;
position:relative;
}
h2 {
margin: 0 5px .5em 5px;padding:5px;
}
div.alias {
color:gray;
margin:0;
padding:0 0 0 60px;
display:block;
font-weight:normal;
font-size:0.6em;
}
table.blacklist_table,
table.ports_table {
border-top: thin black solid;
border-left: thin black solid;
}
table.blacklist_table td,
table.blacklist_table th,
table.ports_table td,
table.ports_table th {
border-right: thin black solid;
border-bottom: thin black solid;
padding: 3px;
}
.actif {
color:red;
}
.inactif {
}
#gestion_machines_main_frame {
padding:5px;
}
dl.basicInfos dt {
float:left;
font-weight:bold;
clear:left;
}
dl.basicInfos dd {
float:left;
margin:0 1em;
}
ul#listeMachines {
list-style-type:none;
margin:0;
padding:0;
}
ul#listeMachines li {
float:left;
height:70px;
width:100px;
margin:5px;
display:block;
text-align:center;
}
ul#listeMachines li span {
margin-bottom:0;
display:block;
}
ul#listeMachines li a {
display:block;
color:black;
text-decoration:none;
}
ul#listeMachines li a:hover {
background:#bbbbff;
}
ul#listeMachines li a:active {
background:#8888ff;
}
ul#listeMachines li img {
margin:2px auto;
width:32px;
height:32px;
}
#menu_actions {
background:#eeeeff;
padding:.3em;
width:18%;
float:left;
position:absolute;
top:1em;
left:0;
border: thin black solid;
}
#menu_actions ul {
list-style-type:none;
padding:0;
margin:.5em;
}
#menu_actions ul li a {
text-decoration:none;
}
#menu_actions ul li a:hover {
text-decoration:underline;
}
#menu_actions h1 {
font-size:1em;
margin:0;
text-align:center;
border-bottom: thin black solid;
}
// on change la couleur des messages
.message {
background-color:#000080;
color:white;
}
label {
width:175px;
display:block;
float:left;
}

View file

@ -0,0 +1,348 @@
/* ************************************************************
* Machines
************************************************************
* Machines.init : initialisation de la page
* Machines.listeMachines : liste des machines
* Machines.infoPane : information sur une machine
* Machines.actions : modifications, ajout...
* Machines.AJAX : ajax
*/
Machines = {};
/*****************************
Machines.init
*****************************/
Machines.init = function()
{
// afficher le tableau codelist
appendChildNodes("globalDiv", Machines.createFrames());
appendChildNodes("globalDiv", Machines.actions.makeMenu());
// recuperer la liste des codes
this.listeMachines.load();
}
Machines.createFrames = function()
{
var main = DIV({"id":"gestion_machines_main_frame"});
var inside = DIV({"id":"__insideDivId", "style":"background:white;margin:5px;padding:5px;"},main);
var outside = DIV({"id":"__outsideDivId","style":"background:#000080;z-index:500;padding:0;"}, inside );
roundElement(outside);
roundElement(inside);
log("Creation du cadre");
return outside
}
/*****************************
Machines.listeMachines
*****************************/
Machines.listeMachines = {};
Machines.listeMachines.load = function()
{
Machines.AJAX.call("AJAXListeMachines", Machines.listeMachines.display);
log("Chargement liste...");
Machines.currentMachine = '';
}
Machines.listeMachines.display = function(result)
{
Crans.loading.display(false);
log("display liste");
replaceChildNodes( "gestion_machines_main_frame",
H2({}, "Mes machines"),
UL({"id":"listeMachines"}),
DIV( {"style":"clear:both;"} )
);
if (result.machines) {
replaceChildNodes('listeMachines',map(Machines.listeMachines.newMachineNodeFromDict ,result.machines));
Machines.actions.updateMenu(Machines.actions.actionForMachineList);
Machines.currentMid = '';
}
else if (result.erreur)
logError("Erreur distante : " + result.erreur);
else
logError("Probleme bizarre...");
}
Machines.listeMachines.newMachineNodeFromDict = function (aDict, style)
{
var nom = aDict.nomCourt;
var mid = aDict.mid;
var image = "machines_icon_" + aDict.type + ".png";
//log("create an item : " + nom);
if (style) {
var anIcon = LI({'id':'machine_' + mid,"style":style});
} else
var anIcon = LI( {'id':'machine_' + mid} );
appendChildNodes(anIcon, A({"href":"#", "onclick":"Machines.infoPane.loadInfo('"+mid+"');return false;"}, IMG({"src":"/static/images/" + image}), SPAN({},nom) ) );
return anIcon;
}
/*****************************
Machines.infoPane
*****************************/
Machines.infoPane = {};
Machines.infoPane.loadInfo = function(mid)
{
if (!mid)
if (!Machines.currentMachine) {
logError("Machines.infoPane.loadInfo : pas de mid, pas de machine courrante...");
return
} else
mid = Machines.currentMachine.mid;
log("load info : " + mid);
Machines.AJAX.call("AJAXMachineInfo?mid=" + mid, Machines.infoPane.display);
try {
pulsate('machine_' + mid);
} catch (error) {}
}
Machines.infoPane.display = function(result)
{
Crans.loading.display(false);
if (result.nom) {
log("displaying info : " + result.mid);
// building pane
var machinePane = DIV({"id":"machine_pane"});
// lien pour retourner a la liste des machines
var back_link = A({"href":"#", "onclick":"Machines.listeMachines.load(); return false;"},"Retour");
appendChildNodes( machinePane, back_link );
// titre (nom de machine + alias)
var title = H2({}, IMG({"src":"/static/images/machines_icon_" + result.type + ".png"}), " ", result.nom);
var alias = DIV({"class":"alias"},
map(function(a_name) { return SPAN({}, a_name + " ")}, result.alias));
appendChildNodes( title, alias );
appendChildNodes( machinePane, title );
// infos de base (type, mac, ip, ipsec...)
var basicInfos = createDOM("DL", {"class":"basicInfos"});
appendChildNodes(basicInfos, createDOM("DT", "type:" ), createDOM("DD",{},"Machine " + result.type ) );
appendChildNodes(basicInfos, createDOM("DT", "mac: " ), createDOM("DD",{},result.mac ) );
appendChildNodes(basicInfos, createDOM("DT", "ip: " ), createDOM("DD",{},result.ip ) );
if (result.ipsec)
appendChildNodes(basicInfos, createDOM("DT", "Clef ipSec:" ), createDOM("DD",{},result.ipsec ) );
appendChildNodes( machinePane, basicInfos );
appendChildNodes( machinePane, DIV( {"style":"clear:both;"} ) );
// blacklist
if (result.blacklist)
if (result.blacklist.length) {
var subtitle = H3({}, "Blacklist");
appendChildNodes( machinePane, subtitle );
var blacklist_table = TABLE({"class":"blacklist_table", "cellspacing":"0"},
THEAD({},
TH({}, "Cause"),
TH({}, "Debut"),
TH({}, "Fin")
)
);
map(function(a_blacklist_dict) {
var style = "inactif";
if (a_blacklist_dict.actif)
style = "actif";
var line = TR({"class":style},
TD({}, a_blacklist_dict.type),
TD({}, a_blacklist_dict.begin),
TD({}, a_blacklist_dict.end)
);
appendChildNodes(blacklist_table, line);
}, result.blacklist );
appendChildNodes( machinePane, blacklist_table );
}
// liste des ports ouverts
if (result.ports)
if (result.ports.length) {
var subtitle = H3({}, "Ports ouverts");
appendChildNodes( machinePane, subtitle );
var port_table = TABLE({"class":"ports_table", "cellspacing":"0"});
map(function(a_port_dict) {
var line = TR({},
TH({}, a_port_dict.titre),
map(function(a_port) {return TD({}, a_port);}, a_port_dict.ports)
);
appendChildNodes(port_table, line);
}, result.ports );
appendChildNodes( machinePane, port_table );
}
// attaching pane to document
replaceChildNodes( "gestion_machines_main_frame", machinePane);
// updationg actions
Machines.currentMachine = result;
Machines.actions.updateMenu(Machines.actions.actionsForInfoPane);
} else if (result.erreur) {
logError("Erreur distante : " + result.erreur);
} else
logError("Probleme bizarr...");
}
/*****************************
Machines.actions
*****************************/
Machines.actions = {}
Machines.actions.disponibles =
{
'Ajouter machine fixe':'Machines.actions.formulaire.nouvelleMachine(\'fixe\');',
'Ajouter machine wifi':'Machines.actions.formulaire.nouvelleMachine(\'wifi\');',
'Modifier Mac':'Machines.actions.formulaire.modifierMac(Machines.currentMid);',
'Renommer':'Machines.actions.formulaire.renommer(Machines.currentMid);',
'Supprimer':'Machines.actions.formulaire.supprimer(Machines.currentMid);',
'Demander l\'ouverture d\'un port':'Machines.actions.formulaire.ouverturePort(Machines.currentMid);'
}
Machines.actions.actionForMachineList = ['Ajouter machine fixe', 'Ajouter machine wifi'];
Machines.actions.actionsForInfoPane = ['Modifier Mac', 'Renommer', 'Supprimer'];
Machines.actions.makeMenu = function(actionListe)
{
log("building action menu");
var liste = UL({"id":"liste_actions"});
//this.updateMenu(actionListe, liste)
return DIV( {"id":"menu_actions"},
H1( {}, "ACTIONS"),
liste
);
}
Machines.actions.updateMenu = function(actionListe, liste_actionsNode)
{
if (!liste_actionsNode)
liste_actionsNode = "liste_actions";
replaceChildNodes(liste_actionsNode);
map(
function(actionName) {
appendChildNodes(liste_actionsNode, LI({}, Machines.actions.makeActionLink(actionName)));
}
, actionListe);
}
Machines.actions.makeActionLink = function(actionName)
{
if (this.disponibles[actionName])
{
return A({"href":"#", "onclick":this.disponibles[actionName] + "return false;"}, actionName);
} else
logError("action inconnue " + actionName);
return A({}, "???");
}
Machines.actions.callback = function(result) {
Crans.loading.display(false);
if (result.message){
log(result.message);
Crans.messages.setMessage(result.message);
if (result.mid)
Machines.infoPane.loadInfo(result.mid);
else
Machines.listeMachines.load();
}
if (result.error){
alert(result.error);
logError("AJAX error");
}
}
// actions : affichage des formulaires
Machines.actions.formulaire = {}
Machines.actions.formulaire.modifierMac = function()
{
if (!Machines.currentMachine)
logError("pas de machine courrante");
else {
var c = '';
while ( c == '')
c = prompt("Adresse MAC de la machine :",Machines.currentMachine.mac);
if (c == null)
return false;
// AJAX stuff
Machines.AJAX.call('AJAXchangerMAC?nouvelleMAC=' + c + '&mid=' + Machines.currentMachine.mid,
Machines.actions.callback);
}
return false;
}
Machines.actions.formulaire.renommer = function() {
if (!Machines.currentMachine)
logError("pas de machine courrante");
else {
var c = '';
while ( c == '')
c = prompt("Nom de la machine :",Machines.currentMachine.nomCourt);
if (c == null)
return false;
// AJAX stuff
Machines.AJAX.call('AJAXChangerNom?nouveauNom=' + c + '&mid=' + Machines.currentMachine.mid,
Machines.actions.callback);
}
return false;
}
Machines.actions.formulaire.supprimer = function() {
if (!Machines.currentMachine)
logError("pas de machine courrante");
else {
if (confirm("Supprimer la machine " + Machines.currentMachine.nomCourt +" ?")) {
// AJAX stuff
Machines.AJAX.call('AJAXSupprimerMachine?mid=' + Machines.currentMachine.mid,
Machines.actions.callback);
}
}
return false;
}
Machines.actions.formulaire.nouvelleMachine = function(type) {
replaceChildNodes( "gestion_machines_main_frame",
A({"href":"#", "onclick":"Machines.listeMachines.load(); return false;"},"Retour"),
H2({}, "Nouvelle machine"),
FORM({"style":"clear:both;", 'onsubmit':'Machines.actions.creerMachine(this.typeField.value, this.nom.value, this.mac.value);return false;'},
createDOM('label', {'for':'add_machine_nom'}, "Nom de la machine : "),
INPUT({"name":"nom"}),
BR(),
createDOM('label', {'for':'add_machine_mac'}, "Adresse MAC : "),
INPUT({"name":"mac"}),
BR(),
createDOM('label', {'for':'add_machine_type'}, "Type de machine : "),
SPAN({'id':'add_machine_type'}, type),
INPUT({"name":"typeField", 'type':'hidden', 'value':type}),
BR(),
BUTTON({"class":"liens", 'type':'submit'}, 'Ajouter')
)
);
return false;
}
Machines.actions.creerMachine = function(type, nom, mac) {
Machines.AJAX.call('AJAXCreerMachine?nomNouvelleMachine=' + nom
+ '&MACNouvelleMachine=' + mac
+ '&typeNouvelleMachine=' + type,
Machines.actions.callback);
}
/*****************************
Machines.AJAX
*****************************/
Machines.AJAX = {}
Machines.AJAX.call = function(page, callBack) {
logDebug("calling AJAX : " + page);
var e = loadJSONDoc(page);
e.addCallback(callBack);
e.addErrback(this.errorHandler);
Crans.loading.display(true);
}
Machines.AJAX.errorHandler = function(d) {
//Machines.AJAX..modifPrix("Erreur", false);
logError("AJAX Error: " + d);
Crans.loading.display(false);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB