#! /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() 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()