Modification de la structure de l'intranet

darcs-hash:20070124113425-f46e9-b0dc2101073d5c4d896539104cc418693bab419a.gz
This commit is contained in:
gdetrez 2007-01-24 12:34:25 +01:00
parent 0570881d34
commit 8713311bc1
13 changed files with 331 additions and 191 deletions

View file

@ -0,0 +1,38 @@
from cherrypy.filters.basefilter import BaseFilter
import cherrypy._cputil
##########################
# DomFilter
##########################
#
# transforme des objets python
# en chainses de caracteres qui peuvent
# etre parsees avec JSON/javascript
#
class DOMFilter(BaseFilter):
def beforeFinalize(self):
body = cherrypy.response.body
if isinstance(body, dict):
body = self.printAsDom(body)
cherrypy.response.body = body
def printAsDom(self, chose):
if isinstance(chose, dict):
stringList = []
for a_key in chose.keys():
stringList.append('%s:%s' % (self.printAsDom(a_key), self.printAsDom(chose[a_key])))
return "{%s}" % ','.join(stringList)
if isinstance(chose, list):
stringList = []
for an_item in chose:
stringList.append('%s' % (self.printAsDom(an_item)))
return "[%s]" % ','.join(stringList)
if isinstance(chose, str):
return '"%s"' % chose
if isinstance(chose, unicode):
return '"%s"' % chose.encode('utf8')
return str(chose)

View file

@ -0,0 +1,42 @@
from cherrypy.filters.basefilter import BaseFilter
import cherrypy._cputil
import cherrypy
##########################
# verification des droits
##########################
#
def verifDroits(mesDroits, lesDroitsQuilFaut):
if not type(mesDroits) == list:
raise ValueError, "mesDroits doit etre une liste"
if (lesDroitsQuilFaut == "all") or (lesDroitsQuilFaut == []):
return True
if ("Nounou" in mesDroits):
return True
if type(lesDroitsQuilFaut) == str:
return lesDroitsQuilFaut in mesDroits
elif type(lesDroitsQuilFaut) == list:
return True in [d in mesDroits for d in lesDroitsQuilFaut]
return False
class AuthorisationsFilter(BaseFilter):
def before_main(self):
if not cherrypy.config.get('sessionAuthenticateFilter.on', False):
return
if not cherrypy.session.get("session_key"):
return
droits = cherrypy.config.get('crans.droits', 'all')
if not verifDroits(cherrypy.session['droits'], droits):
raise cherrypy.HTTPError(403, "Vous n'avez pas les droits nécessaires pour accéder à cette page.")
##########################
# mise en place des droits
##########################
#
def setDroits(chemin, lesDroitsQuilFaut):
settings= {
chemin:
{ 'crans.droits': lesDroitsQuilFaut}
}
cherrypy.config.update(settings)

View file

@ -0,0 +1,224 @@
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# #############################################################
# ..
# .... ............ ........
# . ....... . .... ..
# . ... .. .. .. .. ..... . ..
# .. .. ....@@@. .. . ........ .
# .. . .. ..@.@@..@@. .@@@@@@@ @@@@@@. ....
# .@@@@. .@@@@. .@@@@..@@.@@..@@@..@@@..@@@@.... ....
# @@@@... .@@@.. @@ @@ .@..@@..@@...@@@. .@@@@@. ..
# .@@@.. . @@@. @@.@@..@@.@@..@@@ @@ .@@@@@@.. .....
# ...@@@.... @@@ .@@.......... ........ ..... ..
# . ..@@@@.. . .@@@@. .. ....... . .............
# . .. .... .. .. . ... ....
# . . .... ............. .. ...
# .. .. ... ........ ... ...
# ................................
#
# #############################################################
# Intranet.py
#
# Classe Intranet, clase de base de l'intranet
#
# Copyright (c) 2006 by www.crans.org
# #############################################################
import crans.cp as _crans_cp
import cherrypy, os
import crans.utils.exceptions
from ClassesIntranet.AuthorisationsManager import setDroits
class Intranet:
# ######################################################## #
# GESTION DES MODULES #
# ######################################################## #
#
#
_loaded_modules = {}
def _make_static_path_for_module(self, module_name ):
return "/" + module_name + "/static"
def loadModule(self, un_module):
MODULES_DIR = cherrypy.config.get("crans.modules.dir")
if not un_module.startswith("."):
# faire ici l'importation
# importer le fichier main.py
try:
module_path = MODULES_DIR + "/" + un_module + "/main"
mon_module = __import__(module_path)
module_root = mon_module.main()
# on ajoute la classe a l'arborescence de cherrypy :
setattr( self, un_module, module_root)
# on ajoute le module aux modules connus :
try:
cat = module_root.category()
if not self._loaded_modules.has_key(cat):
self._loaded_modules[cat] = {}
self._loaded_modules[cat][un_module] = module_root
except:
if cherrypy.config.get("server.environment") == "development":
_crans_cp.log("Impossible d'obtenir les parametres du module %s" % un_module)
_crans_cp.log(crans.utils.exceptions.formatExc())
# on ajoute les droits du module :
try:
droits_module = module_root.droits()
setDroits("/%s" % un_module, droits_module)
except:
if cherrypy.config.get("server.environment") == "development":
_crans_cp.log("Impossible d'obtenir les parametres du module %s" % un_module)
_crans_cp.log(crans.utils.exceptions.formatExc())
except:
_crans_cp.log("Impossible de charger le module %s" % un_module)
if cherrypy.config.get("server.environment") == "development":
_crans_cp.log(crans.utils.exceptions.formatExc())
# ajouter le dossier static ou il faut
staticPath = cherrypy.config.get("rootDir") + "/" + MODULES_DIR + "/" + un_module + "/static"
if os.path.isdir(staticPath):
settings= { self._make_static_path_for_module(un_module):
{ 'sessionAuthenticateFilter.on': False,
'sessionFilter.on': False,
'server.output_filters.templatesEngine.on' : False,
'staticFilter.on': True,
'staticFilter.dir': staticPath,
}
}
cherrypy.config.update(settings)
if cherrypy.config.get("server.environment") == "development":
_crans_cp.log("New static : %s" % staticPath)
# fin de l'ajout du dossier static
def __init__(self):
##
#### import automatique des modules
##
MODULES_DIR = cherrypy.config.get("crans.modules.dir", False)
if MODULES_DIR:
if os.path.isdir(MODULES_DIR):
Liste_Modules = os.listdir(MODULES_DIR)
for un_module in Liste_Modules:
self.loadModule(un_module)
else:
_crans_cp.log("Dossier des modules invalide", 'LOADING', 2)
else:
_crans_cp.log("Pas de dossier de modules", 'LOADING', 2)
# ######################################################## #
# QUELQUES PAGES #
# ######################################################## #
#
#
def index(self):
items = {}
for a_category in self._loaded_modules:
items[a_category] = {}
for a_module_name in self._loaded_modules[a_category]:
module_object = self._loaded_modules[a_category][a_module_name]
if module_object.accessible():
items[a_category][a_module_name] = {}
items[a_category][a_module_name]["name"] = module_object.title()
items[a_category][a_module_name]["icon"] = self._make_static_path_for_module(a_module_name) + "/" + module_object.icon()
items[a_category][a_module_name]["url"] = "/" + a_module_name + "/"
# si la categorie est vide, on la vire
if items[a_category] == {}:
del items[a_category]
return {
'template':'accueil',
'values':{"modules":items},
'stylesheets':['css/accueil.css'],
}
index.exposed= True
def info(self):
return {
'template':'info-diverses',
'values':{},
'stylesheets':['accueil.css'],
}
info.exposed = True
def send_error_repport(self, **kw):
# on récupère tout de suite le traceback
tb = crans.utils.exceptions.formatExc()
# entêtes du mail
exp = "intranet"
dest = cherrypy.config.get("mail.bugreport", "nounous@crans.org")
subject = "Rapport de Bug"
text = """
Bonsoir,
Ceci est un rapport de bug envoye par l'intranet.
%s
""" % "\n".join( [ "%s: %s" % (str(a), str(kw[a])) for a in kw] )
#On ajoute des variables de cherrypy
text += "\n= Cherrypy vars =\n"
try:
text += "url: %s\n" % cherrypy.request.browser_url
except:
pass
try:
text += "headers: \n %s\n" % "\n".join( [" %s: %s" % (str(a), str(cherrypy.request.headers[a])) for a in cherrypy.request.headers] )
except:
pass
try:
text += "query_string: %s\n" % cherrypy.request.query_string
except:
pass
try:
text += "path: %s\n" % cherrypy.request.path
except:
pass
# on ajoute le traceback
text += "\n= Traceback =\n"
text += tb
#on signe, quand même !
text += "\n-- \nRoot.py pour l'intranet\n"
quickSend(exp, dest, subject, text)
return self.index()
send_error_repport.exposed = True
def testErreur(self):
raise Exception, "sdlfkjqmsdklj"
testErreur.exposed = True
def test(self):
return cherrypy.request.remote_addr
test.exposed = True
def _cp_on_http_error(self, status, message):
if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
cherrypy._cputil._cp_on_http_error(status, message)
return
if status==403:
cherrypy.response.body = {
'template':'error403',
'values':{'status':status, 'message':message },
'standalone':False,
}
elif status==404:
cherrypy.response.body = {
'template':'error',
'values':{'status':status, 'message':message },
'standalone':False,
}
elif status==500:
self.send_error_repport(status = status, message = message )
# les filtres ne sont pas appliqués, on le fait à la main...
from plugins.templatesfilter import TemplatesFilter
TemplatesFilter().goWithThisDict({'template':'error', 'values':{'status':status, 'message':message }})
else:
self.send_error_repport(status = status, message = message)
cherrypy._cputil._cp_on_http_error(status, message)

View file

@ -0,0 +1,18 @@
import cherrypy
from AuthorisationsManager import verifDroits
class ModuleBase:
def category(self):
return "Personnel"
def title(self):
return "Titre"
def icon(self):
return "icon.png"
_droits = []
def droits(self):
return self._droits
def accessible(self):
return verifDroits(cherrypy.session['droits'], self.droits())

View file

@ -0,0 +1,109 @@
from cherrypy.filters.basefilter import BaseFilter
import cherrypy, os
from Cheetah.Template import Template
import crans.cp as _crans_cp
from ClassesIntranet import current_module
# ######################################################## #
# Configuration de Cheetah #
# ######################################################## #
def serverSidePath(self, path):
root_dir = cherrypy.config.configMap["global"]["rootDir"]
if os.path.isfile(path):
return path
try:
module_name = current_module()
hyp_path = root_dir + '/modules/' + module_name + '/templates/' + path
if os.path.isfile(hyp_path):
return hyp_path
except:
pass
return root_dir + '/templates/' + path
# on surcharge cette fonction dans la classe Template
Template.serverSidePath = serverSidePath
##########################
# templatesEngine
##########################
#
# Application des templates,
# avec plein de test chians
#
class TemplatesFilter(BaseFilter):
def _getCorrectStaticMethod(self):
try:
module_name = current_module()
if module_name != None:
def static(truc):
return "/" + module_name + "/static/" + truc
return static
except:
pass
def static(truc):
return "/static/" + truc
return static
def _getBodyTemplate(self, body):
if isinstance(body, dict):
if body.has_key('template'):
if body['template'].endswith(".py"):
return body['template']
elif body['template'].endswith(".tmpl"):
return body['template']
else:
return body['template'] + ".tmpl"
return False
def _isStandaloneBody(self, body):
if isinstance(body, dict):
if body.has_key('standalone'):
return body['standalone']
if body.has_key('template'):
return False
else:
return True
return True
def _getBodyNameSpace(self, body):
if isinstance(body, dict):
if body.has_key('values'):
return body['values']
return {}
def _useMainTemplate(self, body):
values = {'environment':cherrypy.config.configMap["global"]["server.environment"],
'static':self._getCorrectStaticMethod(),
}
try:
t = Template(file='main.tmpl', searchList= [body,{'login':cherrypy.session['uid']}, values])
except:
t = Template(file='main.tmpl', searchList=[body,{'login':''},values])
return str(t)
def goWithThisDict(self, aDict):
body = aDict
bodyTemplate = self._getBodyTemplate(body)
if bodyTemplate:
templatevalues = self._getBodyNameSpace(body)
defaultvalues = {'static':self._getCorrectStaticMethod()}
t = Template(file=bodyTemplate, searchList=[templatevalues, defaultvalues])
body['page'] = str(t)
if not self._isStandaloneBody(body):
body = self._useMainTemplate(body)
else:
body = body["page"]
cherrypy.response.body = body
def beforeFinalize(self):
body = cherrypy.response.body
if isinstance(body, dict):
self.goWithThisDict(body)

View file

@ -0,0 +1,8 @@
import cherrypy
def current_module():
current_path = cherrypy.request.object_path
module_name = current_path.split('/')[1]
if module_name != 'index':
return module_name
return None