Root.py 10.1 KB
Newer Older
gdetrez's avatar
gdetrez committed
1
#!/usr/bin/env python
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# -*- coding: iso-8859-15 -*-
# #############################################################
#                                            ..                
#                       ....  ............   ........          
#                     .     .......   .            ....  ..    
#                   .  ... ..   ..   ..    ..   ..... .  ..    
#                   .. .. ....@@@.  ..  .       ........  .    
#              ..  .  .. ..@.@@..@@.  .@@@@@@@   @@@@@@. ....  
#         .@@@@. .@@@@. .@@@@..@@.@@..@@@..@@@..@@@@.... ....  
#       @@@@... .@@@.. @@ @@  .@..@@..@@...@@@.  .@@@@@.    .. 
#     .@@@..  . @@@.   @@.@@..@@.@@..@@@   @@ .@@@@@@..  ..... 
#    ...@@@.... @@@    .@@.......... ........ .....        ..  
#   . ..@@@@.. .         .@@@@.   .. .......  . .............  
#  .   ..   ....           ..     .. . ... ....                
# .    .       ....   ............. .. ...                     
# ..  ..  ...   ........ ...      ...                          
#  ................................                            
#                                                              
# #############################################################
# __init__.py                                                                                                                    
#                                                              
#     Classe impression
#                                                              
# Copyright (c) 2006 by www.crans.org                          
# #############################################################
gdetrez's avatar
gdetrez committed
27 28 29


import cherrypy, sys, os, datetime
30
import crans.utils.exceptions
gdetrez's avatar
gdetrez committed
31 32
sys.path.append('/usr/scripts/gestion/')

gdetrez's avatar
gdetrez committed
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
            
# ######################################################## #
#                 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")
parser.add_option("-p", "--port",
    action="store", type="int", dest="port",
    help="change server port")
     
(options, args) = parser.parse_args()


# ######################################################## #
#                          CONFIG                          #
# ######################################################## #
# 
# mise en place de la conf
#

# on suppose qu'en version de developpement, le script est lance depuis le shell
if (options.dev):
    cherrypy.config.update(file=os.getcwd() + "/conf/intranet.cfg")
63
    cherrypy.config.update(file=os.getcwd() + "/conf/dev.cfg") 
gdetrez's avatar
gdetrez committed
64 65 66 67 68
    settings={'global': { 'rootDir': os.getcwd() } }                                                                                                                                         
    cherrypy.config.update(settings)                                                                                                               
                
else:
    cherrypy.config.update(file="/usr/scripts/intranet/conf/intranet.cfg") 
69
    cherrypy.config.update(file="/usr/scripts/intranet/conf/prod.cfg") 
gdetrez's avatar
gdetrez committed
70 71 72 73 74 75 76

# changer le port ??
if (options.port):
    settings={'global':{'server.socketPort':options.port}}
    cherrypy.config.update(settings)                                                                                                               
    

gdetrez's avatar
gdetrez committed
77
# import du crans_ldap qu'il va bien
gdetrez's avatar
gdetrez committed
78 79
if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
    from ldap_crans_test import crans_ldap
gdetrez's avatar
gdetrez committed
80
    cherrypy.log("settings : unsing test ldap : env=" + cherrypy.config.configMap["global"]["server.environment"], "LDAP")
gdetrez's avatar
gdetrez committed
81 82
else:
    from ldap_crans import crans_ldap
gdetrez's avatar
gdetrez committed
83
    cherrypy.log("settings : unsing prod ldap : env=" + cherrypy.config.configMap["global"]["server.environment"], "LDAP")
gdetrez's avatar
gdetrez committed
84 85
cherrypy.config.update({'global':{'crans_ldap':crans_ldap()}})

gdetrez's avatar
gdetrez committed
86 87 88 89 90 91 92
# ######################################################## #
#                     FILTRES MAISON                       #
# ######################################################## #

from plugins.domfilter import DOMFilter
from plugins.templatesfilter import TemplatesFilter
from plugins.verifdroitsfilter import VerifDroitsFilter
gdetrez's avatar
gdetrez committed
93
from crans.mail import quickSend                    
gdetrez's avatar
gdetrez committed
94 95 96 97 98 99
# ######################################################## #
#                         SERVER                           #
# ######################################################## #
class Intranet:
    __ldap = None
    def __init__(self):
100
        from pages import monCompte, impression, factures, digicode, mesmachines
101
        from pages import gestionFactures
gdetrez's avatar
gdetrez committed
102 103 104 105
        self.__ldap = cherrypy.config.configMap["global"]["crans_ldap"]
        
        # liste des modules disponibles
        self.monCompte = monCompte.monCompte()
106
        self.sous = factures.root()
gdetrez's avatar
gdetrez committed
107
        self.impression = impression.root()        
gdetrez's avatar
gdetrez committed
108
        self.digicode = digicode.root()
109
        self.mesMachines = mesmachines.root()
110 111
        self.gestionFactures = gestionFactures.root()

gdetrez's avatar
gdetrez committed
112
        # liste des modules en developpement
113
        #if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
gdetrez's avatar
gdetrez committed
114 115 116 117 118 119 120 121
            
            
    _cpFilterList = [TemplatesFilter(), DOMFilter(), VerifDroitsFilter()]
    
    def index(self):
        return {
            'template':'accueil',
            'values':{},
gdetrez's avatar
gdetrez committed
122
            'stylesheets':['accueil.css'],
gdetrez's avatar
gdetrez committed
123 124 125 126 127
            }
    index.exposed= True
    
    def info(self):
        return {
gdetrez's avatar
gdetrez committed
128 129 130 131
          'template':'info-diverses',
          'values':{},
          'stylesheets':['accueil.css'],
        }
gdetrez's avatar
gdetrez committed
132
    info.exposed = True
133

gdetrez's avatar
gdetrez committed
134
    def send_error_repport(self, **kw):
135

136
        # on récupère tout de suite le traceback
137
        tb = crans.utils.exceptions.formatExc()
138
        # entêtes du mail
gdetrez's avatar
gdetrez committed
139 140 141 142 143 144
        exp = "intranet"
        dest = cherrypy.config.get("mail.bugreport", "nounous@crans.org")
        subject = "Rapport de Bug"
        text = """
Bonsoir,

145
Ceci est un rapport de bug envoye par l'intranet.
gdetrez's avatar
gdetrez committed
146 147 148

%s
        """ % "\n".join( [ "%s: %s" % (str(a), str(kw[a])) for a in kw] )
149 150
        
        #On ajoute des variables de cherrypy
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        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
        
169 170 171 172 173

        # on ajoute le traceback
        text += "\n= Traceback =\n"
        text += tb
        
174
        #on signe, quand même !
175 176
        text += "\n-- \nRoot.py pour l'intranet\n" 
        
gdetrez's avatar
gdetrez committed
177 178 179 180 181 182 183 184 185 186
        quickSend(exp, dest, subject, text)
        return self.index()
    
    send_error_repport.exposed = True
    
    def testErreur(self):
        raise Exception, "sdlfkjqmsdklj"
    
    testErreur.exposed = True

187 188 189
    def test(self):
        return cherrypy.request.remote_addr
    test.exposed = True
gdetrez's avatar
gdetrez committed
190

gdetrez's avatar
gdetrez committed
191
    def _cp_on_http_error(self, status, message):
192 193 194
        if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
    	    cherrypy._cputil._cp_on_http_error(status, message)
    	    return
195 196 197 198 199 200 201 202 203 204 205 206
        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,
                }
gdetrez's avatar
gdetrez committed
207
        elif status==500:
208
            self.send_error_repport(status = status, message = message )
209
            # les filtres ne sont pas appliqués, on le fait à la main...
gdetrez's avatar
gdetrez committed
210 211
            from plugins.templatesfilter import TemplatesFilter
            TemplatesFilter().goWithThisDict({'template':'error', 'values':{'status':status, 'message':message }})
212
        else:
213
            self.send_error_repport(status = status, message = message)
214 215
            cherrypy._cputil._cp_on_http_error(status, message)

gdetrez's avatar
gdetrez committed
216 217 218 219 220 221 222 223 224
    
# ######################################################## #
#                      LOGIN MAISON                        #
# ######################################################## #
# 
# Methode pour afficher la template de login
#
def login(from_page = '', login = None, password = '', error_msg=''):
    return {
gdetrez's avatar
gdetrez committed
225 226 227 228
     'template':'login',
     'values':{'login':login, 'password':password, 'from_page':from_page, 'message':error_msg},
     'standalone':True
    }
gdetrez's avatar
gdetrez committed
229 230 231 232 233
#
# methode qui verifie le login
#
def verifLogin(login = '', password = ''):
    message = None
gdetrez's avatar
gdetrez committed
234 235 236 237 238
    try:
        if login != '' and password != '':
            cherrypy.session['LDAP'] = crans_ldap()
            LDAP = cherrypy.session['LDAP']
            adh = LDAP.search('uid=' + login)['adherent'][0]
gdetrez's avatar
gdetrez committed
239 240 241 242
            if adh.checkPassword(password):
                cherrypy.session['uid'] = login
                cherrypy.session['session_key'] = True
                cherrypy.session['droits'] = adh.droits()
243
                cherrypy.log("User logged in : %s" % cherrypy.session['uid'], "LOGIN")
gdetrez's avatar
gdetrez committed
244 245
                return
            else:
gdetrez's avatar
gdetrez committed
246 247
                raise Exception, "Bad password"
        else:
gdetrez's avatar
gdetrez committed
248
            message = u"L'authentification a echoué."
gdetrez's avatar
gdetrez committed
249 250 251
            raise Exception, "Empty string"
    except Exception, e:
        cherrypy.log("%s (login:%s)" % (str(e), login), "LOGIN", 1)
gdetrez's avatar
gdetrez committed
252
        message = u"L'authentification a echoué."
253
    return message
gdetrez's avatar
gdetrez committed
254 255 256 257 258





gdetrez's avatar
gdetrez committed
259
# on indique tout ca a cherrypy
gdetrez's avatar
gdetrez committed
260 261 262 263 264 265 266 267
settings={'/': {
    'sessionAuthenticateFilter.checkLoginAndPassword': verifLogin,
    'sessionAuthenticateFilter.loginScreen': login
    }}
cherrypy.config.update(settings)


    
gdetrez's avatar
gdetrez committed
268 269 270 271 272
# ######################################################## #
#                 LANCEMENT DE CHERRYPY                    #
# ######################################################## #
cherrypy.root = Intranet()
cherrypy.server.start()