def __init__(self, context): self.context = context self.__addCommandLineOptions() self.context.addService(PluginManager("bonsai.cfg")) self.controllers = [] self.services = [] self.logger = Logger("Server") self.context.addService(self.logger) self.__loadServices() self.__loadControllers() self.mountControllers()
def decorator(function): context = Context() context.addService(Logger("SECURITY_MODULE")) def wrapper(self, *__args, **__kw): # Check if there is a user. token = SecurityToken() context.Logger().message("Checking authentication for user %s" % (token.dn)) # NOTE: this part should be clarified once front-end/back-end # certificate-based auth. rules will be in place # so we we should just fail over to login/pw schema ### If user browser provide cert, extract this info and update token userDN = "" try: import cherrypy, time # print "###",cherrypy.request.headers # userDN = cherrypy.request.headers['Ssl-Client-S-Dn'] # access = cherrypy.request.headers['Ssl-Client-Verify'] # if userDN!='(null)' and access=='SUCCESS': userDN = cherrypy.request.headers['Cms-Client-S-Dn'] access = cherrypy.request.headers['Cms-Auth-Status'] if userDN != '(null)' and access == 'OK': context.Logger().message("Found DN in user certificate") # SiteDB usees token.dn as username rather then DN itself, so name is misleading userName = self.securityApi.getUsernameFromDN( userDN)[0]['username'] token.impl.dn = userName # token.impl.dn = userDN aTime = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) token.impl.authenticationTime = aTime except: # traceback.print_exc() # redirect to https://cmsweb.cern.ch/sitedb/people/showAllEntries # return redirectionToSiteDB(userDN) pass if token.dn in (None, "guest"): return onFail(self) # Check that the session has not expired. if not token.authenticationTime: return onFail(self) authenticationTime = datetime( *strptime(token.authenticationTime, "%Y-%m-%dT%H:%M:%S")[0:6]) currentTime = datetime.now() # TODO: this should come from the configuration file. maxPeriod = timedelta(seconds=3600 * 24) if authenticationTime + maxPeriod < currentTime: context.Logger().message( "Cookie has expired, authorisation failed.") return onFail(self) return function(self, *__args, **__kw) return wrapper
def __init__(self, context): self.context = context childContext = Context(context) childContext.addService(Logger("SecurityDBApi")) self.securityApi = SecurityDBApi(childContext) self.securityTokenFactory = SecurityTokenFactory( childContext, CherryPySecurityTokenImpl) self.siteDBApi = self.securityApi.api context.addService(self.securityApi) context.addService(self.siteDBApi) context.addService(self.securityTokenFactory) RedirectorToLogin.context = staticmethod(lambda: self.context) RedirectToLocalPage.context = staticmethod(lambda: self.context) RedirectAway.context = staticmethod(lambda: self.context)
def __loadControllers(self): for plugin in self.context.PluginManager().plugins("/Controllers"): # Each plugin lives in his own context, with his own logger. pluginContext = Context(self.context) name = plugin.implementation.__name__ self.logger.message("Controller %s loaded." % name) pluginContext.addService(Logger(name)) try: controller = plugin.createInstance(pluginContext) controller.options = plugin.options self.controllers.append(controller) except Exception, e: message = "An error was found while loading the controller: %s." % name exceptionStrings = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback) self.logger.debug(message + "\t".join(exceptionStrings)) self.logger.warning("Controller %s not activated." % name)
from os.path import exists, join, isdir from os import getenv, listdir from os import environ from pickle import load import sys from Framework.Logger import Logger import traceback g_pluginRegistry = {} g_pluginLogger = Logger ("Plugin Engine") class PluginContainer (object): def __init__ (self, implementation, options={}, name=""): self.implementation = implementation self.options = options self.name = name def createInstance (self, *args, **kwds): return self.implementation (*args, **kwds) def plugin (name, options={}): def decorator (function): def wrapper (self, *__args, **__kw): global g_pluginRegistry g_pluginLogger.debug ("Declaring plugin %s with implementation %s" % (name, function)) g_pluginRegistry [name] = PluginContainer (function, options, name=name) return function (*__args, **__kw) return wrapper return decorator
def __init__ (self, context): self.context = context Controller.__init__ (self, context, __file__) self.security_api = SecurityDBApi (context) self.context.addService (self.security_api) self.context.addService (Logger ("SECURITY_MODULE_CONTROLLER"))
import codecs if __name__ == "__main__": parser = OptionParser() parser.add_option("-f", "--file", help="input HN shadow passwd", default="passwd", dest="source") parser.add_option("-d", "--db", help="target SiteDB database", default="sitedb_test.db", dest="db") options, args = parser.parse_args() context = Context() context.addService(Logger("importHNShadow")) api = SecurityDBApi(context) context.Logger().message("HN file is " + options.source) shadowFile = codecs.open(options.source, "r", "ascii", "replace") for line in shadowFile: contact = line.split(":") if " " in contact[4]: forename, surname = contact[4].split(" ", 1) else: forename, surname = (contact[4], contact[4]) api.importHNAccount(username=contact[0].encode("ascii", "replace"), passwd=contact[1], forename=forename.encode("ascii", "replace"), email=contact[7].strip(), surname=surname.encode("ascii", "replace"))
from Framework import Context from Framework.Logger import Logger from Tools.SiteDBCore import SiteDBApi context = Context() context.addService(Logger("sitedbtest")) api = SiteDBApi(context) api.connect() print api.getTierList()
from Framework.Logger import Logger from StringIO import StringIO buf = StringIO() logger = Logger("Foo", buf, standalone=True) logger.log("message", priority=1, format="[%(stream_name)s]") assert (buf.getvalue() == "[Foo]message\n") logger.log("message", priority=1, format="[%(stream_name)s]") assert (buf.getvalue() == "[Foo]message\n[Foo]message\n") logger.log("message", priority=90, format="[%(stream_name)s]") assert (buf.getvalue() == "[Foo]message\n[Foo]message\n") logger.detailLevel = 100 logger.log("message", priority=90, format="[%(stream_name)s]") assert (buf.getvalue() == "[Foo]message\n[Foo]message\n[Foo]message\n") logger.detailFilter = [80] logger.log("message", priority=90, format="[%(stream_name)s]") assert (buf.getvalue() == "[Foo]message\n[Foo]message\n[Foo]message\n") logger.detailFilter = [90] logger.log("message", priority=90, format="[%(stream_name)s]") assert (buf.getvalue() == "[Foo]message\n[Foo]message\n[Foo]message\n[Foo]message\n") logger.error("error") logger.warning("warning") logger.debug("debug") logger.log("log") anotherLogger = Logger("Bar", buf, parent=logger) anotherLogger.log("message", priority=90, format="[%(stream_name)s]") anotherLogger.detailLevel = 200 assert (logger.detailLevel == 100)
class BonsaiServer(object): def __init__(self, context): self.context = context self.__addCommandLineOptions() self.context.addService(PluginManager("bonsai.cfg")) self.controllers = [] self.services = [] self.logger = Logger("Server") self.context.addService(self.logger) self.__loadServices() self.__loadControllers() self.mountControllers() def __addCommandLineOptions(self): parser = self.context.OptionParser() parser.add_option( "-s", "--secure", help="redirects to URL if the connection is not secure", dest="secureRedirect", metavar="URL", default="") parser.add_option( "--ssl", help= "start bonsai server in SSL mode, host CA/KEY can be setup via BONSAI_CA/BONSAI_KEY environment", dest="ssl", action="store_true", default=False) parser.add_option("-p", "--port", help="server listening on port PORT", dest="port", metavar="PORT", default="8030") parser.add_option("-e", "--environment", help="server environment (production|development)", dest="environment", metavar="ENV", default="production") parser.add_option("--default-page", dest="defaultPage", metavar="URL", default="/Studio/login") def stripTrailingSlash(option, opt_str, value, parser, *args, **kwargs): setattr(parser.values, option.dest, value.rstrip("/")) parser.add_option( "--base-url", help="Base URL for the server (for usage behind a proxy).", default="http://localhost:8030", dest="baseUrl", action="callback", callback=stripTrailingSlash, type="str", nargs=1) def __loadServices(self): for plugin in self.context.PluginManager().plugins("/Services"): # Services are loaded before /Controllers to provide them with # general utilities. serviceName = plugin.implementation.__name__ self.logger.debug("Loading service: %s" % serviceName) try: service = plugin.createInstance(self.context) self.services.append(service) except Exception, e: message = "An error was found while loading the service: %s.\n" % serviceName exceptionStrings = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback) self.logger.debug(message + "\t".join(exceptionStrings)) self.logger.warning("Service %s skipped." % serviceName)
from Framework.Logger import Logger from StringIO import StringIO buf = StringIO () logger = Logger ("Foo", buf, standalone=True) logger.log ("message", priority=1, format="[%(stream_name)s]") assert (buf.getvalue () == "[Foo]message\n") logger.log ("message", priority=1, format="[%(stream_name)s]") assert (buf.getvalue () == "[Foo]message\n[Foo]message\n") logger.log ("message", priority=90, format="[%(stream_name)s]") assert (buf.getvalue () == "[Foo]message\n[Foo]message\n") logger.detailLevel = 100 logger.log ("message", priority=90, format="[%(stream_name)s]") assert (buf.getvalue () == "[Foo]message\n[Foo]message\n[Foo]message\n") logger.detailFilter = [80] logger.log ("message", priority=90, format="[%(stream_name)s]") assert (buf.getvalue () == "[Foo]message\n[Foo]message\n[Foo]message\n") logger.detailFilter = [90] logger.log ("message", priority=90, format="[%(stream_name)s]") assert (buf.getvalue () == "[Foo]message\n[Foo]message\n[Foo]message\n[Foo]message\n") logger.error ("error") logger.warning ("warning") logger.debug ("debug") logger.log ("log") anotherLogger = Logger ("Bar", buf, parent=logger) anotherLogger.log ("message", priority=90, format="[%(stream_name)s]") anotherLogger.detailLevel = 200 assert (logger.detailLevel == 100) assert (buf.getvalue () == "[Foo]message\n[Foo]message\n[Foo]message\n[Foo]message\n[Bar]message\n")
from Framework import Context from Framework.Logger import Logger from Crypto.Cipher import Blowfish from base64 import b64encode, b64decode import crypt import time, calendar, datetime from Tools.SecurityModuleCore.SecurityDBApi import SecurityDBApi print "**** Security Module tests ****" context = Context() context.addService(Logger("securitymoduletest")) api = SecurityDBApi(context) context.Logger().message("Test roles:") context.Logger().message( " swakef as prod operator: %s" % api.hasGroupResponsibility("swakef", "production", "Production Operator")) context.Logger().message( " metson as RAL DM: %s" % api.hasSiteResponsibility("metson", "RAL", "Data Manager")) context.Logger().message( " metson as site 1 Site Admin: %s" % api.hasSiteResponsibility("metson", "1", "Site Admin")) context.Logger().message("hasGroup:") context.Logger().message(" swakef as member of production group: %s" % api.hasGroup("swakef", "production")) context.Logger().message(" metson as member of production group: %s" %
class BonsaiServer(object): def __init__(self, context): self.context = context self.__addCommandLineOptions() self.context.addService(PluginManager("bonsai.cfg")) self.controllers = [] self.services = [] self.logger = Logger("Server") self.context.addService(self.logger) self.__loadServices() self.__loadControllers() self.mountControllers() def __addCommandLineOptions(self): parser = self.context.OptionParser() parser.add_option( "-s", "--secure", help="redirects to URL if the connection is not secure", dest="secureRedirect", metavar="URL", default="", ) parser.add_option( "--ssl", help="start bonsai server in SSL mode, host CA/KEY can be setup via BONSAI_CA/BONSAI_KEY environment", dest="ssl", action="store_true", default=False, ) parser.add_option( "-p", "--port", help="server listening on port PORT", dest="port", metavar="PORT", default="8030" ) parser.add_option( "-e", "--environment", help="server environment (production|development)", dest="environment", metavar="ENV", default="production", ) parser.add_option("--default-page", dest="defaultPage", metavar="URL", default="/Studio/login") def stripTrailingSlash(option, opt_str, value, parser, *args, **kwargs): setattr(parser.values, option.dest, value.rstrip("/")) parser.add_option( "--base-url", help="Base URL for the server (for usage behind a proxy).", default="http://localhost:8030", dest="baseUrl", action="callback", callback=stripTrailingSlash, type="str", nargs=1, ) def __loadServices(self): for plugin in self.context.PluginManager().plugins("/Services"): # Services are loaded before /Controllers to provide them with # general utilities. serviceName = plugin.implementation.__name__ self.logger.debug("Loading service: %s" % serviceName) try: service = plugin.createInstance(self.context) self.services.append(service) except Exception, e: message = "An error was found while loading the service: %s.\n" % serviceName exceptionStrings = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback) self.logger.debug(message + "\t".join(exceptionStrings)) self.logger.warning("Service %s skipped." % serviceName)