Root.py 8.88 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
#! /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):
13 14
    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
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    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"
gdetrez's avatar
gdetrez committed
86
        return False
87 88 89 90 91 92 93 94 95

    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
gdetrez's avatar
gdetrez committed
96
        return True
97 98 99 100 101
    
    def _getBodyNameSpace(self, body):
        if isinstance(body, dict):
            if body.has_key('values'):
                return body['values']
gdetrez's avatar
gdetrez committed
102
        return {}
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

    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()
158 159 160 161 162
        self.sous = factures.root()
        
        # liste des modules en developpement
        if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
            self.impression = impression.root()
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238


    _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
#
239 240 241
#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") 
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
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()