def make_url_parser(global_conf, directory, base_python_name, index_names=None, hide_extensions=None, ignore_extensions=None, **constructor_conf): """ Create a URLParser application that looks in ``directory``, which should be the directory for the Python package named in ``base_python_name``. ``index_names`` are used when viewing the directory (like ``'index'`` for ``'index.html'``). ``hide_extensions`` are extensions that are not viewable (like ``'.pyc'``) and ``ignore_extensions`` are viewable but only if an explicit extension is given. """ if index_names is None: index_names = global_conf.get( 'index_names', ('index', 'Index', 'main', 'Main')) index_names = converters.aslist(index_names) if hide_extensions is None: hide_extensions = global_conf.get( 'hide_extensions', ('.pyc', 'bak', 'py~')) hide_extensions = converters.aslist(hide_extensions) if ignore_extensions is None: ignore_extensions = global_conf.get( 'ignore_extensions', ()) ignore_extensions = converters.aslist(ignore_extensions) # There's no real way to set constructors currently... return URLParser({}, directory, base_python_name, index_names=index_names, hide_extensions=hide_extensions, ignore_extensions=ignore_extensions, **constructor_conf)
def make_proxy(global_conf, address, allowed_request_methods="", suppress_http_headers="", remote_user_header="HTTP_X_REMOTE_USER"): """ Make a WSGI application that proxies to another address: ``address`` the full URL ending with a trailing ``/`` ``allowed_request_methods``: a space seperated list of request methods (e.g., ``GET POST``) ``suppress_http_headers`` a space seperated list of http headers (lower case, without the leading ``http_``) that should not be passed on to target host ``remote_user_header`` the name of the header to be passed to the backend. defaulf: ``HTTP_X_REMOTE_USER`` """ allowed_request_methods = aslist(allowed_request_methods) suppress_http_headers = aslist(suppress_http_headers) return Proxy(address, allowed_request_methods=allowed_request_methods, suppress_http_headers=suppress_http_headers, remote_user_header=remote_user_header)
def make_proxy( global_conf, address, allowed_request_methods="", suppress_http_headers="", remote_user_header="HTTP_X_REMOTE_USER" ): """ Make a WSGI application that proxies to another address: ``address`` the full URL ending with a trailing ``/`` ``allowed_request_methods``: a space seperated list of request methods (e.g., ``GET POST``) ``suppress_http_headers`` a space seperated list of http headers (lower case, without the leading ``http_``) that should not be passed on to target host ``remote_user_header`` the name of the header to be passed to the backend. defaulf: ``HTTP_X_REMOTE_USER`` """ allowed_request_methods = aslist(allowed_request_methods) suppress_http_headers = aslist(suppress_http_headers) return Proxy( address, allowed_request_methods=allowed_request_methods, suppress_http_headers=suppress_http_headers, remote_user_header=remote_user_header, )
def __init__( self, global_conf, directory, base_python_name, index_names=NoDefault, hide_extensions=NoDefault, ignore_extensions=NoDefault, constructors=None, **constructor_conf ): """ Create a URLParser object that looks at `directory`. `base_python_name` is the package that this directory represents, thus any Python modules in this directory will be given names under this package. """ if global_conf: import warnings warnings.warn( "The global_conf argument to URLParser is deprecated; " "either pass in None or {}, or use make_url_parser", DeprecationWarning, ) else: global_conf = {} if os.path.sep != "/": directory = directory.replace(os.path.sep, "/") self.directory = directory self.base_python_name = base_python_name # This logic here should be deprecated since it is in # make_url_parser if index_names is NoDefault: index_names = global_conf.get("index_names", ("index", "Index", "main", "Main")) self.index_names = converters.aslist(index_names) if hide_extensions is NoDefault: hide_extensions = global_conf.get("hide_extensions", (".pyc", ".bak", ".py~", ".pyo")) self.hide_extensions = converters.aslist(hide_extensions) if ignore_extensions is NoDefault: ignore_extensions = global_conf.get("ignore_extensions", ()) self.ignore_extensions = converters.aslist(ignore_extensions) self.constructors = self.global_constructors.copy() if constructors: self.constructors.update(constructors) # @@: Should we also check the global options for constructors? for name, value in constructor_conf.items(): if not name.startswith("constructor "): raise ValueError( "Only extra configuration keys allowed are " "'constructor .ext = import_expr'; you gave %r " "(=%r)" % (name, value) ) ext = name[len("constructor ") :].strip() if isinstance(value, (str, unicode)): value = import_string.eval_import(value) self.constructors[ext] = value
def __init__(self, global_conf, directory, base_python_name, index_names=NoDefault, hide_extensions=NoDefault, ignore_extensions=NoDefault, constructors=None, **constructor_conf): """ Create a URLParser object that looks at `directory`. `base_python_name` is the package that this directory represents, thus any Python modules in this directory will be given names under this package. """ if global_conf: import warnings warnings.warn( 'The global_conf argument to URLParser is deprecated; ' 'either pass in None or {}, or use make_url_parser', DeprecationWarning) else: global_conf = {} if os.path.sep != '/': directory = directory.replace(os.path.sep, '/') self.directory = directory self.base_python_name = base_python_name # This logic here should be deprecated since it is in # make_url_parser if index_names is NoDefault: index_names = global_conf.get('index_names', ('index', 'Index', 'main', 'Main')) self.index_names = converters.aslist(index_names) if hide_extensions is NoDefault: hide_extensions = global_conf.get('hide_extensions', ('.pyc', '.bak', '.py~', '.pyo')) self.hide_extensions = converters.aslist(hide_extensions) if ignore_extensions is NoDefault: ignore_extensions = global_conf.get('ignore_extensions', ()) self.ignore_extensions = converters.aslist(ignore_extensions) self.constructors = self.global_constructors.copy() if constructors: self.constructors.update(constructors) # @@: Should we also check the global options for constructors? for name, value in constructor_conf.items(): if not name.startswith('constructor '): raise ValueError( "Only extra configuration keys allowed are " "'constructor .ext = import_expr'; you gave %r " "(=%r)" % (name, value)) ext = name[len('constructor '):].strip() if isinstance(value, (str, unicode)): value = import_string.eval_import(value) self.constructors[ext] = value
def make_cascade(loader, global_conf, catch='404', **local_conf): """ Expects configuration like: [composit:cascade] use = egg:Paste#cascade # all start with 'app' and are sorted alphabetically app1 = foo app2 = bar ... catch = 404 500 ... """ catch = map(int, converters.aslist(catch)) apps = [] for name, value in local_conf.items(): if not name.startswith('app'): raise ValueError( "Bad configuration key %r (=%r); all configuration keys " "must start with 'app'" % (name, value)) app = loader.get_app(value, global_conf=global_conf) apps.append((name, app)) apps.sort() apps = [app for name, app in apps] return Cascade(apps, catch=catch)
def make_cascade(loader, global_conf, catch='404', **local_conf): """ Entry point for Paste Deploy configuration Expects configuration like:: [composit:cascade] use = egg:Paste#cascade # all start with 'app' and are sorted alphabetically app1 = foo app2 = bar ... catch = 404 500 ... """ catch = map(int, converters.aslist(catch)) apps = [] for name, value in local_conf.items(): if not name.startswith('app'): raise ValueError( "Bad configuration key %r (=%r); all configuration keys " "must start with 'app'" % (name, value)) app = loader.get_app(value, global_conf=global_conf) apps.append((name, app)) apps.sort() apps = [app for name, app in apps] return Cascade(apps, catch=catch)
def raw_send_email(sender, recipients, message): if isinstance(recipients, basestring): recipients = [recipients] hold_emails = asbool(config.get('hold_emails', False)) force_emails_to = aslist(os.environ.get("ututi_force_emails_to", []), ',', strip=True) force_emails_to = [e for e in force_emails_to if e] if hold_emails and force_emails_to: recipients = [address for address in recipients if address in force_emails_to] if recipients: hold_emails = False log.debug("Recipients: %r" % recipients) log.debug("Hold emails: %r" % asbool(config.get('hold_emails', False))) # Send the message via SMTP to localhost:25 if not hold_emails: # send the email if we are not told to hold it server = config.get('smtp_host', 'localhost') smtp = SMTP(server) try: smtp.sendmail(config['ututi_email_from'], recipients, message) except SMTPRecipientsRefused: log.warn(sender) log.warn(recipients) log.warn(repr(message)) finally: smtp.quit() else: mail_queue.append(EmailInfo(sender, recipients, message))
def make_proxy(global_conf, address, allowed_request_methods="", suppress_http_headers=""): """ Make a WSGI application that proxies to another address: ``address`` the full URL ending with a trailing ``/`` ``allowed_request_methods``: a space seperated list of request methods (e.g., ``GET POST``) ``suppress_http_headers`` a space seperated list of http headers (lower case, without the leading ``http_``) that should not be passed on to target host """ allowed_request_methods = aslist(allowed_request_methods) suppress_http_headers = aslist(suppress_http_headers) return Proxy(address, allowed_request_methods=allowed_request_methods, suppress_http_headers=suppress_http_headers)
def __init__(self, application, global_conf=None, debug=NoDefault, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=NoDefault, from_address=None, smtp_server=None, smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix=None, error_message=None, xmlhttp_key=None): from paste.util import converters self.application = application # @@: global_conf should be handled elsewhere in a separate # function for the entry point if global_conf is None: global_conf = {} if debug is NoDefault: debug = converters.asbool(global_conf.get('debug')) if show_exceptions_in_wsgi_errors is NoDefault: show_exceptions_in_wsgi_errors = converters.asbool( global_conf.get('show_exceptions_in_wsgi_errors')) self.debug_mode = converters.asbool(debug) if error_email is None: error_email = (global_conf.get('error_email') or global_conf.get('admin_email') or global_conf.get('webmaster_email') or global_conf.get('sysadmin_email')) self.error_email = converters.aslist(error_email) self.error_log = error_log self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors if from_address is None: from_address = global_conf.get('error_from_address', 'errors@localhost') self.from_address = from_address if smtp_server is None: smtp_server = global_conf.get('smtp_server', 'localhost') self.smtp_server = smtp_server self.smtp_username = smtp_username or global_conf.get('smtp_username') self.smtp_password = smtp_password or global_conf.get('smtp_password') self.smtp_use_tls = smtp_use_tls or converters.asbool( global_conf.get('smtp_use_tls')) self.error_subject_prefix = error_subject_prefix or '' if error_message is None: error_message = global_conf.get('error_message') self.error_message = error_message if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key
def __init__( self, application, global_conf=None, debug=NoDefault, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=NoDefault, from_address=None, smtp_server=None, error_subject_prefix=None, error_message=None, xmlhttp_key=None, ): from paste.util import converters self.application = application # @@: global_conf should be handled elsewhere in a separate # function for the entry point if global_conf is None: global_conf = {} if debug is NoDefault: debug = converters.asbool(global_conf.get("debug")) if show_exceptions_in_wsgi_errors is NoDefault: show_exceptions_in_wsgi_errors = converters.asbool(global_conf.get("show_exceptions_in_wsgi_errors")) self.debug_mode = converters.asbool(debug) if error_email is None: error_email = ( global_conf.get("error_email") or global_conf.get("admin_email") or global_conf.get("webmaster_email") or global_conf.get("sysadmin_email") ) self.error_email = converters.aslist(error_email) self.error_log = error_log self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors if from_address is None: from_address = global_conf.get("error_from_address", "errors@localhost") self.from_address = from_address if smtp_server is None: smtp_server = global_conf.get("smtp_server", "localhost") self.smtp_server = smtp_server self.error_subject_prefix = error_subject_prefix or "" if error_message is None: error_message = global_conf.get("error_message") self.error_message = error_message if xmlhttp_key is None: xmlhttp_key = global_conf.get("xmlhttp_key", "_") self.xmlhttp_key = xmlhttp_key
def __init__(self, application, global_conf=None, debug=NoDefault, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=NoDefault, from_address=None, smtp_server=None, smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix=None, error_message=None, xmlhttp_key=None): from paste.util import converters self.application = application # @@: global_conf should be handled elsewhere in a separate # function for the entry point if global_conf is None: global_conf = {} if debug is NoDefault: debug = converters.asbool(global_conf.get('debug')) if show_exceptions_in_wsgi_errors is NoDefault: show_exceptions_in_wsgi_errors = converters.asbool(global_conf.get('show_exceptions_in_wsgi_errors')) self.debug_mode = converters.asbool(debug) if error_email is None: error_email = (global_conf.get('error_email') or global_conf.get('admin_email') or global_conf.get('webmaster_email') or global_conf.get('sysadmin_email')) self.error_email = converters.aslist(error_email) self.error_log = error_log self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors if from_address is None: from_address = global_conf.get('error_from_address', 'errors@localhost') self.from_address = from_address if smtp_server is None: smtp_server = global_conf.get('smtp_server', 'localhost') self.smtp_server = smtp_server self.smtp_username = smtp_username or global_conf.get('smtp_username') self.smtp_password = smtp_password or global_conf.get('smtp_password') self.smtp_use_tls = smtp_use_tls or converters.asbool(global_conf.get('smtp_use_tls')) self.error_subject_prefix = error_subject_prefix or '' if error_message is None: error_message = global_conf.get('error_message') self.error_message = error_message if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key
def check_conf_context(): """Check if a certain PIN exists""" pin = request.params.get('variable_conf_pin') retries = int(request.params.get('variable_retries', 0)) conf_profile = 'default' moderator = False flags = [] n = datetime.now() if pin: cPin = Session.query(ModeratorPin).get(pin) else: return default_context(request.params.get('Hunt-Context')) if cPin: conf_name = cPin.pin moderator = True record = cPin.record secure = cPin.secure username = cPin.username domain = cPin.domain userRecord = cPin.userRecord beeps = cPin.beeps else: cPin = Session.query(ParticipantPin).get(pin) if cPin: conf_name = cPin.moderator_pin record = cPin.ModeratorPin.record secure = cPin.ModeratorPin.secure username = cPin.ModeratorPin.username domain = cPin.ModeratorPin.domain userRecord = cPin.ModeratorPin.userRecord beeps = cPin.ModeratorPin.beeps hangup_str = '' if retries+1 == 3: log.info('User exceeded the maximum number of tries, hanging up.') hangup_str = '\n<action application="hangup" />\n' if not cPin: return ("""<?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="freeswitch/xml"> <section name="dialplan" description="RE Dial Plan For FreeSwitch"> <context name="check_conf"> <extension name="Conference"> <condition> <action application="set" data="retries=%s" inline="true"/> <action application="playback" data="ivr_prompts/conf-badpin-c.wav"/>%s <action application="transfer" data="${destination_number} XML default"/> </condition> </extension> </context> </section> </document>""" % (retries+1, hangup_str)) # Check to see if the user is enabled on the AD # Authenticate the user! Base = config.get('ldap.base') Scope = ldap.SCOPE_SUBTREE Filter = "(&(objectClass=user)(sAMAccountName="+username+")(objectCategory=Person)(userAccountControl:1.2.840.113556.1.4.803:=2))" Attrs = ["displayName", "mail"] # Set the LDAP timeout for the connection. ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, int(config.get('ldap.timeout'))) Server = 'ldap://' + aslist(config.get('ldap.hosts')).pop(0) log.info('Connecting to server: %s' % Server) l = ldap.initialize(Server) l.protocol_version = 3 l.set_option(ldap.OPT_REFERRALS, 0) try: l.simple_bind_s(config.get('ldap.username'), config.get('ldap.password')) user = l.search_ext_s(Base, Scope, Filter, Attrs, timeout=10) if (len(user) >= 2): log.info('User %s@%s is disabled. Check when entering conference %s.' % (username, domain, conf_name)) return ("""<?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="freeswitch/xml"> <section name="dialplan" description="RE Dial Plan For FreeSwitch"> <context name="check_conf"> <extension name="Conference"> <condition> <action application="playback" data="ivr_prompts/conf-badpin-c.wav"/> <action application="transfer" data="${destination_number} XML default"/> </condition> </extension> </context> </section> </document>""") else: log.info('User %s@%s is active. Allowing user to join conference %s.' % (username, domain, conf_name)) except ldap.SERVER_DOWN, e: log.warning('Server %s is down!' % Server)
def login(self): username = request.POST["username"] password = request.POST["password"] domain = request.POST["domain"] if username: # Authenticate the user! Base = config.get("ldap.base") Scope = ldap.SCOPE_SUBTREE Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))" Attrs = ["displayName", "mail"] # Set the LDAP timeout for the connection. ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, int(config.get("ldap.timeout"))) for Server in aslist(config.get("ldap.hosts"), sep=","): Server = "ldap://" + Server log.info("Connecting to server: %s" % Server) l = ldap.initialize(Server) l.protocol_version = 3 l.set_option(ldap.OPT_REFERRALS, 0) try: l.simple_bind_s(username + "@" + domain, password) r = l.search(Base, Scope, Filter, Attrs) Type, user = l.result(r, 10) Name, Attrs = user[0] if hasattr(Attrs, "has_key") and Attrs.has_key("mail"): email = Attrs["mail"][0] session["email"] = email if hasattr(Attrs, "has_key") and Attrs.has_key("displayName"): displayName = Attrs["displayName"][0] session["displayName"] = displayName session["username"] = username session["domain"] = domain session["logged_in"] = True session.save() except ldap.SERVER_DOWN, e: log.warning("Server %s is down!" % Server) if aslist(config.get("ldap.hosts"), sep=",").pop() in Server: # We are the last server, so ... log.critical("All LDAP servers are down. Last server tried was: %s" % Server) msg = "Active Directory server is down for the moment. Please try again later." h.flash(msg) location = url(controller="auth/login", action="index") redirect(location) else: continue except ldap.INVALID_CREDENTIALS, e: msg = "Invalid username/password" h.flash(msg) location = url(controller="auth/login", action="index") log.warning("User denied, redirecting to: %s. Error: %s" % (location, e)) redirect(location) except ldap.LDAPError, e: msg = "Server error. Try again later." h.flash(msg) location = url(controller="auth/login", action="index") log.critical("Redirecting to: %s because %s" % (location, e)) redirect(location)
def get_reporters(self, errorware): """ Both middleware objects support the concept of 'reporters'. This will create the email reporter that will send up webapp emails. """ from paste.util import converters error_email = errorware.get('error_email') error_email = converters.aslist(error_email) from_address = errorware.get('from_address') smtp_server = errorware.get('smtp_server', 'localhost') smtp_username = errorware.get('smtp_username') smtp_password = errorware.get('smtp_password') smtp_port= errorware.get('smtp_port') smtp_use_tls = converters.asbool(errorware.get('smtp_use_tls')) subject_prefix = errorware.get('error_subject_prefix') logger.info('ErrorWare %s' % errorware) class ComEmailReporter(reporter.EmailReporter): #TODO: using smtp_port from outside. Ghetto. def report(self, exc_data): logger.info('Sending email on %s:%s for %s, tls? %s' % ( self.smtp_server, smtp_port, self.smtp_username, self.smtp_use_tls) ) logger.info('Emailed about error %s' % exc_data) msg = self.assemble_email(exc_data) if smtp_port: server = smtplib.SMTP(self.smtp_server, int(smtp_port)) else: server = smtplib.SMTP(self.smtp_server) if self.smtp_use_tls: server.ehlo() server.starttls() server.ehlo() if self.smtp_username and self.smtp_password: server.login(self.smtp_username, self.smtp_password) ## FIXME: this should check the return value from this function: result = server.sendmail(self.from_address, self.to_addresses, msg.as_string()) logger.info('Result from sendmail %s' % result) try: server.quit() except sslerror: # sslerror is raised in tls connections on closing sometimes pass # emails will not be sent in dev. if error_email: return [ComEmailReporter( to_addresses=error_email, from_address=from_address, smtp_server=smtp_server, smtp_username=smtp_username, smtp_password=smtp_password, smtp_use_tls=smtp_use_tls, subject_prefix=subject_prefix)] return []
def __init__(self, application, global_conf=None, debug=NoDefault, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=NoDefault, from_address=None, smtp_server=None, smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix=None, error_message=None, xmlhttp_key=None, reporters=None): from paste.util import converters self.application = application # @@: global_conf should be handled elsewhere in a separate # function for the entry point if global_conf is None: global_conf = {} if debug is NoDefault: debug = converters.asbool(global_conf.get('debug')) if show_exceptions_in_wsgi_errors is NoDefault: show_exceptions_in_wsgi_errors = converters.asbool( global_conf.get('show_exceptions_in_wsgi_errors')) self.debug_mode = converters.asbool(debug) if error_email is None: error_email = (global_conf.get('error_email') or global_conf.get('admin_email') or global_conf.get('webmaster_email') or global_conf.get('sysadmin_email')) self.error_email = converters.aslist(error_email) self.error_log = error_log self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors if from_address is None: from_address = global_conf.get('error_from_address') if from_address is None: if self.error_email: from_address = self.error_email[0] else: from_address = 'errors@localhost' self.from_address = from_address if smtp_server is None: smtp_server = global_conf.get('smtp_server', 'localhost') self.smtp_server = smtp_server self.smtp_username = smtp_username or global_conf.get('smtp_username') self.smtp_password = smtp_password or global_conf.get('smtp_password') self.smtp_use_tls = smtp_use_tls or converters.asbool( global_conf.get('smtp_use_tls')) self.error_subject_prefix = error_subject_prefix or '' if error_message is None: error_message = global_conf.get('error_message') self.error_message = error_message if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key reporters = reporters or global_conf.get('error_reporters') if reporters and isinstance(reporters, basestring): reporter_strings = reporters.split() reporters = [] for reporter_string in reporter_strings: reporter = import_string.eval_import(reporter_string) if isinstance(reporter, (type, types.ClassType)): reporter = reporter() reporters.append(reporter) self.reporters = reporters or []
def __init__(self, application, global_conf=None, debug=NoDefault, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=NoDefault, from_address=None, smtp_server=None, smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix=None, error_message=None, xmlhttp_key=None, reporters=None, show_error_reason=None): from paste.util import converters self.application = application # @@: global_conf should be handled elsewhere in a separate # function for the entry point if global_conf is None: global_conf = {} if debug is NoDefault: debug = converters.asbool(global_conf.get('debug')) if show_exceptions_in_wsgi_errors is NoDefault: show_exceptions_in_wsgi_errors = converters.asbool(global_conf.get('show_exceptions_in_wsgi_errors')) self.debug_mode = converters.asbool(debug) if error_email is None: error_email = (global_conf.get('error_email') or global_conf.get('admin_email') or global_conf.get('webmaster_email') or global_conf.get('sysadmin_email')) self.error_email = converters.aslist(error_email) self.error_log = error_log self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors if from_address is None: from_address = global_conf.get('error_from_address') if from_address is None: if self.error_email: from_address = self.error_email[0] else: from_address = 'errors@localhost' self.from_address = from_address if smtp_server is None: smtp_server = global_conf.get('smtp_server', 'localhost') self.smtp_server = smtp_server self.smtp_username = smtp_username or global_conf.get('smtp_username') self.smtp_password = smtp_password or global_conf.get('smtp_password') self.smtp_use_tls = smtp_use_tls or converters.asbool(global_conf.get('smtp_use_tls')) self.error_subject_prefix = error_subject_prefix or '' if error_message is None: error_message = global_conf.get('error_message') self.error_message = error_message if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key reporters = reporters or global_conf.get('error_reporters') if reporters and isinstance(reporters, basestring): reporter_strings = reporters.split() reporters = [] for reporter_string in reporter_strings: reporter = import_string.eval_import(reporter_string) if isinstance(reporter, (type, types.ClassType)): reporter = reporter() reporters.append(reporter) self.reporters = reporters or [] if show_error_reason is None: show_error_reason = global_conf.get('show_error_reason') self.show_error_reason = converters.asbool(show_error_reason)
def sendEmail(config, f, confObj, owner_obj): log = logging.getLogger('sendEmail') """Send the email""" subject_tmpl = Template(config.get('email', 'subject'), input_encoding='utf-8', output_encoding='utf-8') email_tmpl = Template(filename=config.get('email', 'template'), input_encoding='utf-8', output_encoding='utf-8') email_from = config.get('email', 'from') # Authenticate the user! Base = config.get('ldap', 'base') Scope = ldap.SCOPE_SUBTREE Filter = "(&(objectClass=user)(sAMAccountName="+owner_obj.username+"))" Attrs = ["displayName", "mail"] # Set the LDAP timeout for the connection. ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, config.getint('ldap', 'timeout')) for Server in aslist(config.get('ldap','hosts'), sep=','): Server = 'ldap://' + Server log.info('Connecting to server: %s' % Server) l = ldap.initialize(Server) l.protocol_version = 3 l.set_option(ldap.OPT_REFERRALS, 0) try: l.simple_bind_s(config.get('ldap', 'username'), config.get('ldap', 'password')) user = l.search_ext_s(Base, Scope, Filter, Attrs, timeout=10) Name,Attrs = user[0] Name,Attrs = user[0] email_to = None displayName = None if hasattr(Attrs, 'has_key') and Attrs.has_key('mail'): email_to = Attrs['mail'][0] else: log.warning('User %s has not email set. Not sending email.' % owner_obj.username) return if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'): displayName = Attrs['displayName'][0] msg = MIMEText(email_tmpl.render(displayName=displayName, email_to=email_to, conf_name=confObj.name, conf_recording=confObj.recording, url=config.get('http', 'root')+'/main/reports/report_detail/'+confObj.id, conf_date=confObj.ended), 'html') msg['Subject'] = subject_tmpl.render(displayName=displayName, email_to=email_to, conf_name=confObj.name, conf_recording=confObj.recording, conf_date=confObj.ended) msg['From'] = email_from msg['To'] = email_to if config.getboolean('email', 'internal_server'): log.debug(msg.as_string()) p = subprocess.Popen(config.get('email', 'command'), stdin=subprocess.PIPE, shell=True) p.communicate(input=msg.as_string()) p.stdin.close() log.debug('Message sent.') else: s = smtplib.SMTP(config.get('email', 'server'), config.getint('email', 'port')) s.ehlo() s.starttls() s.ehlo() s.login(config.get('email', 'username'), config.get('email', 'password')) s.sendmail(email_from,[email_to],msg.as_string()) s.quit() return except ldap.SERVER_DOWN, e: log.warning('Server %s is down!' % Server) if aslist(config.get('ldap', 'hosts'), sep=',').pop() in Server: # We are the last server, so ... log.critical('All LDAP servers are down. Last server tried was: %s. Not sending email.' % Server) raise(e) else: continue except ldap.LDAPError, e: log.critical('Critical error while connecting to ldap %s. Error: %s' % (Server, e)) raise(e)