diff --git a/intranet/Root.py b/intranet/Root.py index 4b4a4262..5919f4a7 100755 --- a/intranet/Root.py +++ b/intranet/Root.py @@ -1,257 +1,149 @@ -#! /usr/bin/env python -# -*- coding: utf-8 -*- - -import cherrypy, sys, os, datetime -from Cheetah.Template import Template -sys.path.append('/usr/scripts/gestion/') - -# ######################################################## # -# Configuration de Cheetah # -# ######################################################## # - -def serverSidePath(self, path): - if (cherrypy.config.configMap["global"]["server.environment"] == "development"): - if os.path.isfile(os.getcwd()+'/templates/'+path+".dev"): return os.getcwd()+'/templates/'+path+".dev" # les template se trouve dans le dossier template - return os.getcwd()+'/templates/'+path - -# on surcharge cette fonction dans la classe Template -Template.serverSidePath = serverSidePath - - - -# ######################################################## # -# FILTRES MAISON # -# ######################################################## # - -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) - - - - -########################## -# templatesEngine -########################## -# -# Application des templates, -# avec plein de test chians -# -class templatesEngine(BaseFilter): - - 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): - t = Template(file='main.tmpl', searchList=[body,{'login':cherrypy.session['uid'], 'environment':cherrypy.config.configMap["global"]["server.environment"]}]) - return str(t) - - - - def beforeFinalize(self): - - body = cherrypy.response.body - if isinstance(body, dict): - bodyTemplate = self._getBodyTemplate(body) - if bodyTemplate: - templatevalues = self._getBodyNameSpace(body) - t = Template(file=bodyTemplate, searchList=[templatevalues]) - body['page'] = str(t) - - if not self._isStandaloneBody(body): - body = self._useMainTemplate(body) - else: - body = body["page"] - - cherrypy.response.body = body - - -########################## -# verification des droits -########################## -# -# Application des templates, -# avec plein de test chians -# -class verifDroits(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 (droits != "all"): - if not droits in cherrypy.session['droits']: - raise cherrypy.HTTPError(403, "Vous n'avez pas les droits nĂ©cessaires.") - -# ######################################################## # -# SERVER # -# ######################################################## # -class Intranet: - __ldap = None - def __init__(self): - import monCompte, impression, factures - self.__ldap = cherrypy.config.configMap["global"]["crans_ldap"] - - # liste des modules disponibles - self.monCompte = monCompte.monCompte() +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +import cherrypy, sys, os, datetime +sys.path.append('/usr/scripts/gestion/') + +# ######################################################## # +# FILTRES MAISON # +# ######################################################## # + +from plugins.domfilter import DOMFilter +from plugins.templatesfilter import TemplatesFilter +from plugins.verifdroitsfilter import VerifDroitsFilter + +# ######################################################## # +# SERVER # +# ######################################################## # +class Intranet: + __ldap = None + def __init__(self): + import monCompte, impression, factures + self.__ldap = cherrypy.config.configMap["global"]["crans_ldap"] + + # liste des modules disponibles + self.monCompte = monCompte.monCompte() self.sous = factures.root() - # liste des modules en developpement - if (cherrypy.config.configMap["global"]["server.environment"] == "development"): - self.impression = impression.root() - - - _cpFilterList = [templatesEngine(), DOMFilter(), verifDroits()] - - def index(self): - return { - 'template':'accueil', - 'values':{}, - } - index.exposed= True - - def info(self): - return { - 'template':'info-diverses', - 'values':{} - } - info.exposed = True - - ''' - def nounous(self): - return "coucou" - nounous.exposed= True - - def test(self): - return {"quoi":cherrypy.request.path, "il_faut":cherrypy.config.configMap["/nounous"]["crans.droits"], "moi":cherrypy.session['droits'] } - test.exposed = True - - def environment(self): - return cherrypy.config.configMap["global"]["server.environment"] - environment.exposed = True - ''' - - -# ######################################################## # -# LOGIN MAISON # -# ######################################################## # -# -# Methode pour afficher la template de login -# -def login(from_page = '', login = None, password = '', error_msg=''): - return { - 'template':'login', - 'values':{'login':login, 'password':password, 'from_page':from_page, 'message':error_msg}, - 'standalone':True - } -# -# methode qui verifie le login -# -def verifLogin(login = '', password = ''): - message = None - if login != '' and password != '': - try: - globalLdap = cherrypy.config.configMap["global"]["crans_ldap"] - adh =globalLdap.search('uid=' + login)['adherent'][0] - if adh.checkPassword(password): - cherrypy.session['uid'] = login - cherrypy.session['session_key'] = True - cherrypy.session['droits'] = adh.droits() - return - else: - #print("bad password") - message = u"L'authentification a echoué." - except Exception, e: - #print(e) - message = u"L'authentification a echoué." - else: - #print("sth empty") - message = u"L'authentification a echoué." - return message - -# ######################################################## # -# CHERRYPY # -# ######################################################## # -# -# mise en place de cherrypy + conf -# -#cherrypy.config.update(file="/usr/scripts/intranet/dev.cfg") -cherrypy.config.update(file="/usr/scripts/intranet/prod.cfg") -cherrypy.config.update(file="/usr/scripts/intranet/intranet.cfg") -settings={'/': { - 'sessionAuthenticateFilter.checkLoginAndPassword': verifLogin, - 'sessionAuthenticateFilter.loginScreen': login - } - } -cherrypy.config.update(settings) -if (cherrypy.config.configMap["global"]["server.environment"] == "development"): - from ldap_crans_test import crans_ldap - print("settings : unsing test ldap : env=" + cherrypy.config.configMap["global"]["server.environment"]) -else: - from ldap_crans import crans_ldap - print("settings : unsing prod ldap : env=" + cherrypy.config.configMap["global"]["server.environment"]) -cherrypy.config.update({'global':{'crans_ldap':crans_ldap()}}) -cherrypy.root = Intranet() - -cherrypy.server.start() + # liste des modules en developpement + if (cherrypy.config.configMap["global"]["server.environment"] == "development"): + self.impression = impression.root() + + + _cpFilterList = [TemplatesFilter(), DOMFilter(), VerifDroitsFilter()] + + def index(self): + return { + 'template':'accueil', + 'values':{}, + } + index.exposed= True + + def info(self): + return { + 'template':'info-diverses', + 'values':{} + } + info.exposed = True + + ''' + def nounous(self): + return "coucou" + nounous.exposed= True + + def test(self): + return {"quoi":cherrypy.request.path, "il_faut":cherrypy.config.configMap["/nounous"]["crans.droits"], "moi":cherrypy.session['droits'] + } + test.exposed = True + + def environment(self): + return cherrypy.config.configMap["global"]["server.environment"] + environment.exposed = True + ''' + +# ######################################################## # +# LOGIN MAISON # +# ######################################################## # +# +# Methode pour afficher la template de login +# +def login(from_page = '', login = None, password = '', error_msg=''): + return { +'template':'login', +'values':{'login':login, 'password':password, 'from_page':from_page, 'message':error_msg}, +'standalone':True +} +# +# methode qui verifie le login +# +def verifLogin(login = '', password = ''): + message = None + if login != '' and password != '': + try: + globalLdap = cherrypy.config.configMap["global"]["crans_ldap"] + adh =globalLdap.search('uid=' + login)['adherent'][0] + if adh.checkPassword(password): + cherrypy.session['uid'] = login + cherrypy.session['session_key'] = True + cherrypy.session['droits'] = adh.droits() + return + else: + #print("bad password") + message = u"L'authentification a echoué." + except Exception, e: + #print(e) + message = u"L'authentification a echoué." + else: + #print("sth empty") + message = u"L'authentification a echoué." + return message + +# ######################################################## # +# COMMAND LINE OPTION # +# ######################################################## # +# +# + +from optparse import OptionParser + +parser = OptionParser() +parser.add_option("-d", "--dev", + action="store_true", dest="dev", default=False, + help="launch in dev mode") + +(options, args) = parser.parse_args() + + +# ######################################################## # +# CHERRYPY # +# ######################################################## # +# +# mise en place de cherrypy + conf +# + +cherrypy.config.update(file="/usr/scripts/intranet/intranet.cfg") +if (options.dev): + cherrypy.config.update(file="/usr/scripts/intranet/dev.cfg") +else: + cherrypy.config.update(file="/usr/scripts/intranet/prod.cfg") + + +settings={'/': { + 'sessionAuthenticateFilter.checkLoginAndPassword': verifLogin, + 'sessionAuthenticateFilter.loginScreen': login + }} +cherrypy.config.update(settings) + +if (cherrypy.config.configMap["global"]["server.environment"] == "development"): + from ldap_crans_test import crans_ldap + print("settings : unsing test ldap : env=" + cherrypy.config.configMap["global"]["server.environment"]) +else: + from ldap_crans import crans_ldap + print("settings : unsing prod ldap : env=" + cherrypy.config.configMap["global"]["server.environment"]) +cherrypy.config.update({'global':{'crans_ldap':crans_ldap()}}) +cherrypy.root = Intranet() + +cherrypy.server.start() + + diff --git a/intranet/intranet.cfg b/intranet/intranet.cfg index 2d122f05..8c128c02 100644 --- a/intranet/intranet.cfg +++ b/intranet/intranet.cfg @@ -1,2 +1,5 @@ +[global] +rootDir="/usr/scripts/intranet" + [/nounous] crans.droits="nounou" diff --git a/intranet/plugins/__init__.py b/intranet/plugins/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/intranet/plugins/domfilter.py b/intranet/plugins/domfilter.py new file mode 100644 index 00000000..54cbc557 --- /dev/null +++ b/intranet/plugins/domfilter.py @@ -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) diff --git a/intranet/plugins/templatesfilter.py b/intranet/plugins/templatesfilter.py new file mode 100644 index 00000000..70cfc11a --- /dev/null +++ b/intranet/plugins/templatesfilter.py @@ -0,0 +1,78 @@ +from cherrypy.filters.basefilter import BaseFilter +import cherrypy._cputil, os +from Cheetah.Template import Template + +# ######################################################## # +# Configuration de Cheetah # +# ######################################################## # + +def serverSidePath(self, path): + if (cherrypy.config.configMap["global"]["server.environment"] == "development"): + if os.path.isfile(os.getcwd()+'/templates/'+path+".dev"): + return cherrypy.config.configMap["global"]["rootDir"]+'/templates/'+path+".dev" + # les template se trouve dans le dossier template + return cherrypy.config.configMap["global"]["rootDir"]+'/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 _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): + t = Template(file='main.tmpl', searchList=[body,{'login':cherrypy.session['uid'], 'environment':cherrypy.config.configMap["global"]["server.environment"]}]) + return str(t) + + + + def beforeFinalize(self): + + body = cherrypy.response.body + if isinstance(body, dict): + bodyTemplate = self._getBodyTemplate(body) + if bodyTemplate: + templatevalues = self._getBodyNameSpace(body) + t = Template(file=bodyTemplate, searchList=[templatevalues]) + body['page'] = str(t) + + if not self._isStandaloneBody(body): + body = self._useMainTemplate(body) + else: + body = body["page"] + + cherrypy.response.body = body + diff --git a/intranet/plugins/verifdroitsfilter.py b/intranet/plugins/verifdroitsfilter.py new file mode 100644 index 00000000..8e904b4a --- /dev/null +++ b/intranet/plugins/verifdroitsfilter.py @@ -0,0 +1,22 @@ +from cherrypy.filters.basefilter import BaseFilter +import cherrypy._cputil + +########################## +# verification des droits +########################## +# +# Application des templates, +# avec plein de test chians +# +class VerifDroitsFilter(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 (droits != "all"): + if not droits in cherrypy.session['droits']: + raise cherrypy.HTTPError(403, "Vous n'avez pas les droits nécessaires.") +