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)                                                                                                               
    

77 78
# import du CransLdap qu'il va bien (on utilise CransLdap et non crans_ldap car on veut
# forcer l'ouverture d'une nouvelle connexion  chaque login)
gdetrez's avatar
gdetrez committed
79
if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
80
    from ldap_crans_test import CransLdap
gdetrez's avatar
gdetrez committed
81
    cherrypy.log("settings : unsing test ldap : env=" + cherrypy.config.configMap["global"]["server.environment"], "LDAP")
gdetrez's avatar
gdetrez committed
82
else:
83
    from ldap_crans import CransLdap
gdetrez's avatar
gdetrez committed
84
    cherrypy.log("settings : unsing prod ldap : env=" + cherrypy.config.configMap["global"]["server.environment"], "LDAP")
gdetrez's avatar
gdetrez committed
85

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
# ######################################################## #
#                         SERVER                           #
# ######################################################## #
class Intranet:
    def __init__(self):
99
        from pages import monCompte, impression, factures, digicode, mesmachines
100
        from pages import gestionFactures
gdetrez's avatar
gdetrez committed
101 102 103
        
        # liste des modules disponibles
        self.monCompte = monCompte.monCompte()
104
        self.sous = factures.root()
gdetrez's avatar
gdetrez committed
105
        self.impression = impression.root()        
gdetrez's avatar
gdetrez committed
106
        self.digicode = digicode.root()
107
        self.mesMachines = mesmachines.root()
108 109
        self.gestionFactures = gestionFactures.root()

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

gdetrez's avatar
gdetrez committed
132
    def send_error_repport(self, **kw):
133

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

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

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

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

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

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

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





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


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