Root.py 9.63 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 30 31


import cherrypy, sys, os, datetime
sys.path.append('/usr/scripts/gestion/')

gdetrez's avatar
gdetrez committed
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
            
# ######################################################## #
#                 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")
62
    cherrypy.config.update(file=os.getcwd() + "/conf/dev.cfg") 
gdetrez's avatar
gdetrez committed
63 64 65 66 67
    settings={'global': { 'rootDir': os.getcwd() } }                                                                                                                                         
    cherrypy.config.update(settings)                                                                                                               
                
else:
    cherrypy.config.update(file="/usr/scripts/intranet/conf/intranet.cfg") 
68
    cherrypy.config.update(file="/usr/scripts/intranet/conf/prod.cfg") 
gdetrez's avatar
gdetrez committed
69 70 71 72 73 74 75

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

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

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

from plugins.domfilter import DOMFilter
from plugins.templatesfilter import TemplatesFilter
from plugins.verifdroitsfilter import VerifDroitsFilter
gdetrez's avatar
gdetrez committed
92
from crans.mail import quickSend                    
gdetrez's avatar
gdetrez committed
93 94 95 96 97 98
# ######################################################## #
#                         SERVER                           #
# ######################################################## #
class Intranet:
    __ldap = None
    def __init__(self):
99
        from pages import monCompte, impression, factures, digicode, mesmachines
gdetrez's avatar
gdetrez committed
100 101 102 103
        self.__ldap = cherrypy.config.configMap["global"]["crans_ldap"]
        
        # 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
        
gdetrez's avatar
gdetrez committed
109
        # liste des modules en developpement
110 111
        #if (cherrypy.config.configMap["global"]["server.environment"] == "development"):
        
gdetrez's avatar
gdetrez committed
112

gdetrez's avatar
gdetrez committed
113 114 115 116 117 118 119 120
            
            
    _cpFilterList = [TemplatesFilter(), DOMFilter(), VerifDroitsFilter()]
    
    def index(self):
        return {
            'template':'accueil',
            'values':{},
gdetrez's avatar
gdetrez committed
121
            'stylesheets':['accueil.css'],
gdetrez's avatar
gdetrez committed
122 123 124 125 126
            }
    index.exposed= True
    
    def info(self):
        return {
gdetrez's avatar
gdetrez committed
127 128 129 130
          'template':'info-diverses',
          'values':{},
          'stylesheets':['accueil.css'],
        }
gdetrez's avatar
gdetrez committed
131
    info.exposed = True
132

gdetrez's avatar
gdetrez committed
133 134 135 136 137 138 139 140 141 142 143
    def send_error_repport(self, **kw):
        exp = "intranet"
        dest = cherrypy.config.get("mail.bugreport", "nounous@crans.org")
        subject = "Rapport de Bug"
        text = """
Bonsoir,

Ceci est un rapport de bug envoye depuis l'intranet.        

%s
        """ % "\n".join( [ "%s: %s" % (str(a), str(kw[a])) for a in kw] )
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
        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 += "request_line: %s\n" % cherrypy.request.request_line
        except:
            pass
        try:
            text += "query_string: %s\n" % cherrypy.request.query_string
        except:
            pass
        try:
            text += "path: %s\n" % cherrypy.request.path
        except:
            pass
        
gdetrez's avatar
gdetrez committed
166 167 168 169 170 171 172 173 174 175
        quickSend(exp, dest, subject, text)
        return self.index()
    
    send_error_repport.exposed = True
    
    def testErreur(self):
        raise Exception, "sdlfkjqmsdklj"
    
    testErreur.exposed = True

176 177 178
    def test(self):
        return cherrypy.request.remote_addr
    test.exposed = True
gdetrez's avatar
gdetrez committed
179

gdetrez's avatar
gdetrez committed
180
    def _cp_on_http_error(self, status, message):
181 182 183 184 185 186 187 188 189 190 191 192
        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
193
        elif status==500:
194 195
            self.send_error_repport(status = status, message = message )
            # les filtres ne sont pas appliqués, on le fait à la main...
gdetrez's avatar
gdetrez committed
196 197
            from plugins.templatesfilter import TemplatesFilter
            TemplatesFilter().goWithThisDict({'template':'error', 'values':{'status':status, 'message':message }})
198
        else:
199
            self.send_error_repport(status = status, message = message)
200 201
            cherrypy._cputil._cp_on_http_error(status, message)

gdetrez's avatar
gdetrez committed
202 203 204 205 206 207 208 209 210
    
# ######################################################## #
#                      LOGIN MAISON                        #
# ######################################################## #
# 
# Methode pour afficher la template de login
#
def login(from_page = '', login = None, password = '', error_msg=''):
    return {
gdetrez's avatar
gdetrez committed
211 212 213 214
     'template':'login',
     'values':{'login':login, 'password':password, 'from_page':from_page, 'message':error_msg},
     'standalone':True
    }
gdetrez's avatar
gdetrez committed
215 216 217 218 219
#
# methode qui verifie le login
#
def verifLogin(login = '', password = ''):
    message = None
gdetrez's avatar
gdetrez committed
220 221 222 223 224
    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
225 226 227 228
            if adh.checkPassword(password):
                cherrypy.session['uid'] = login
                cherrypy.session['session_key'] = True
                cherrypy.session['droits'] = adh.droits()
229
                cherrypy.log("User logged in : %s" % cherrypy.session['uid'], "LOGIN")
gdetrez's avatar
gdetrez committed
230 231
                return
            else:
gdetrez's avatar
gdetrez committed
232 233
                raise Exception, "Bad password"
        else:
gdetrez's avatar
gdetrez committed
234
            message = u"L'authentification a echoué."
gdetrez's avatar
gdetrez committed
235 236 237
            raise Exception, "Empty string"
    except Exception, e:
        cherrypy.log("%s (login:%s)" % (str(e), login), "LOGIN", 1)
gdetrez's avatar
gdetrez committed
238
        message = u"L'authentification a echoué."
239
    return message
gdetrez's avatar
gdetrez committed
240 241 242 243 244





gdetrez's avatar
gdetrez committed
245
# on indique tout ca a cherrypy
gdetrez's avatar
gdetrez committed
246 247 248 249 250 251 252 253
settings={'/': {
    'sessionAuthenticateFilter.checkLoginAndPassword': verifLogin,
    'sessionAuthenticateFilter.loginScreen': login
    }}
cherrypy.config.update(settings)


    
gdetrez's avatar
gdetrez committed
254 255 256 257 258
# ######################################################## #
#                 LANCEMENT DE CHERRYPY                    #
# ######################################################## #
cherrypy.root = Intranet()
cherrypy.server.start()