Exemplo n.º 1
0
    def run(self):
        task.LoopingCall(self.status_check).start(0.5)
        root = File('www')
        root.putChild('st', StatusHandler(self))
        root.putChild('upd', self.updateHandler)
        root.putChild('cfg', ConfigHandler(self))
        root.putChild('upt', UptimeHandler(self))

        if self.config['config']['use_auth']:
            clk = ClickHandler(self)
            args = {
                self.config['site']['username']:
                self.config['site']['password']
            }
            checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**args)
            realm = HttpPasswordRealm(clk)
            p = portal.Portal(realm, [checker])
            credentialFactory = BasicCredentialFactory(
                "Garage Door Controller")
            protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory])
            root.putChild('clk', protected_resource)
            cla = CloseHandler(self)
            cla_args = {
                self.config['site']['username']:
                self.config['site']['password']
            }
            cla_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(
                **cla_args)
            cla_realm = HttpPasswordRealm(cla)
            cla_p = portal.Portal(cla_realm, [cla_checker])
            credentialFactory = BasicCredentialFactory(
                "Garage Door Controller")
            cla_protected_resource = HTTPAuthSessionWrapper(
                cla_p, [credentialFactory])
            root.putChild('cla', cla_protected_resource)
        else:
            root.putChild('clk', ClickHandler(self))
            root.putChild('cla', CloseHandler(self))

        if self.config['config']['allow_api']:
            root.putChild('api', APIHandler(self))

        site = server.Site(root)

        if not self.get_config_with_default(self.config['config'], 'use_https',
                                            False):
            reactor.listenTCP(self.config['site']['port'],
                              site)  # @UndefinedVariable
            reactor.run()  # @UndefinedVariable
        else:
            sslContext = ssl.DefaultOpenSSLContextFactory(
                self.config['site']['ssl_key'],
                self.config['site']['ssl_cert'])
            reactor.listenSSL(self.config['site']['port_secure'], site,
                              sslContext)  # @UndefinedVariable
            reactor.run()  # @UndefinedVariable
Exemplo n.º 2
0
 def __init__(self, portal, credentialFactories, redirectTo, keyPath,
              db):
     HTTPAuthSessionWrapper.__init__(self, portal, credentialFactories)
     self.openIDStore = MemoryStore()
     self.loginSemaphore = DeferredSemaphore(1)
     self.redirectTo = redirectTo
     self.db = db
     if keyPath.exists():
         self.fernet = Fernet(keyPath.getContent())
     else:
         key = Fernet.generate_key()
         keyPath.setContent(key)
         self.fernet = Fernet(key)
Exemplo n.º 3
0
def getAuthResource(in_resource,
                    sname,
                    config,
                    password_checker=AnchorePasswordChecker()):
    if not password_checker:
        # explicitly passed in null password checker obj
        return (in_resource)

    if sname in config['services']:
        localconfig = config['services'][sname]
    else:
        # no auth required
        return in_resource

    do_auth = True
    if localconfig and 'require_auth' in localconfig and not localconfig[
            'require_auth']:
        do_auth = False

    if do_auth:
        # if localconfig and 'require_auth' in localconfig and localconfig['require_auth']:
        # if 'require_auth_file' not in localconfig or not os.path.exists(localconfig['require_auth_file']):
        #    raise Exception("require_auth is set for service, but require_auth_file is not set/invalid")

        realm = HTTPAuthRealm(resource=in_resource)
        portal = Portal(realm, [password_checker])

        credential_factory = BasicCredentialFactory(b'Authentication required')
        resource = HTTPAuthSessionWrapper(portal, [credential_factory])
    else:
        resource = in_resource

    return resource
Exemplo n.º 4
0
def require_digest_auth(resource):
    p = portal.Portal(TestAuthRealm(DIGEST_AUTH_PAGE))
    c = checkers.InMemoryUsernamePasswordDatabaseDontUse()
    c.addUser("digestuser", "digestuser")
    p.registerChecker(c)
    cred_factory = DigestCredentialFactory("md5", "Digest Auth protected area")
    return HTTPAuthSessionWrapper(p, [cred_factory])
Exemplo n.º 5
0
def require_basic_auth(resource):
    p = portal.Portal(TestAuthRealm())
    c = checkers.InMemoryUsernamePasswordDatabaseDontUse()
    c.addUser("john", "john")
    p.registerChecker(c)
    cred_factory = BasicCredentialFactory("Basic Auth protected area")
    return HTTPAuthSessionWrapper(p, [cred_factory])
Exemplo n.º 6
0
def addBasicAuth(resource, desc, **users):
    """Add basic auth for a resource.
    Twisteds modulation of everything makes this quite.. messy."""
    realm = SimpleResourceRealm(resource)
    portal = Portal(realm, [InMemoryUsernamePasswordDatabaseDontUse(**users)])
    credentialFactory = BasicCredentialFactory(desc)
    return HTTPAuthSessionWrapper(portal, [credentialFactory])
Exemplo n.º 7
0
 def get_protected_resource(self, resource):
     checker = RapidSMSRelayAccessChecker(self.get_avatar_id)
     realm = RapidSMSRelayRealm(resource)
     p = portal.Portal(realm, [checker])
     factory = BasicCredentialFactory("RapidSMS Relay")
     protected_resource = HTTPAuthSessionWrapper(p, [factory])
     return protected_resource
Exemplo n.º 8
0
def setupRootResource(facade, development=None):
    """Get the root resource to use for the API service.

    @param facade: A L{Facade} instance.
    @return: An C{HTTPAuthSessionWrapper} instance.
    """
    from fluiddb.web.root import WSFERealm, IFacadeRealm
    from fluiddb.web.checkers import (AnonymousChecker, FacadeChecker,
                                      FacadeOAuthChecker, FacadeOAuth2Checker,
                                      IFacadeChecker)

    portal = Portal(WSFERealm(), [
        FacadeChecker(),
        FacadeOAuthChecker(),
        FacadeOAuth2Checker(),
        AnonymousChecker()
    ])
    realm = IFacadeRealm(portal.realm)
    realm.facadeClient = facade
    for checker in portal.checkers.values():
        if IFacadeChecker.providedBy(checker):
            checker.facadeClient = facade

    factories = [
        BasicCredentialFactory('fluidinfo.com'),
        OAuthCredentialFactory('fluidinfo.com'),
        OAuth2CredentialFactory('fluidinfo.com', development)
    ]
    return HTTPAuthSessionWrapper(portal, factories)
Exemplo n.º 9
0
def getResource(app, sname, config):
    if sname in config['services']:
        localconfig = config['services'][sname]
    else:
        # no auth required
        return(app.resource())

    if localconfig and 'require_auth' in localconfig and localconfig['require_auth']:
        #if 'require_auth_file' not in localconfig or not os.path.exists(localconfig['require_auth_file']):
        #    raise Exception("require_auth is set for service, but require_auth_file is not set/invalid")
            
        realm = HTTPAuthRealm(resource=app.resource())
        portal = Portal(realm, [AnchorePasswordChecker()])

        #portal = Portal(realm, [FilePasswordDB(localconfig['require_auth_file'])])
        #portal = Portal(realm, [FilePasswordDB(localconfig['require_auth_file'], hash=hellothere)])

        #
        # for route-based auth, need anon and auth
        #
        #from twisted.cred.checkers import AllowAnonymousAccess
        #portal = Portal(
        #    realm, [
        #        FilePasswordDB('./configs/server-auth.db'),
        #        AllowAnonymousAccess(),
        #    ],
        #)
        
        credential_factory = BasicCredentialFactory('Authentication required')
        #credential_factory = DigestCredentialFactory('md5', 'anchore')
        resource = HTTPAuthSessionWrapper(portal, [credential_factory])
    else:
        resource = app.resource()

    return (resource)
    def run(self):
        task.LoopingCall(self.status_check).start(0.5)
        root = File('www')
        root.putChild('upd', self.updateHandler)
        root.putChild('cfg', ConfigHandler(self))

        if self.config['config']['use_auth']:
            clk = ClickHandler(self)
            args = {
                self.config['site']['username']:
                self.config['site']['password']
            }
            checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**args)
            realm = HttpPasswordRealm(clk)
            p = portal.Portal(realm, [checker])
            credentialFactory = BasicCredentialFactory(
                "Garage Door Controller")
            protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory])
            root.putChild('clk', protected_resource)
        else:
            root.putChild('clk', ClickHandler(self))
        site = server.Site(root)
        reactor.listenTCP(self.config['site']['port'],
                          site)  # @UndefinedVariable
        reactor.run()  # @UndefinedVariable
Exemplo n.º 11
0
    def run(self):
        """
        Start the server and listen on host:port
        """
        f = None
        unix_prefix = 'unix://'

        if self.http_enabled:
            rpc = JsonRpcHttpResource()
            rpc.rpcprocessor = self.rpcprocessor
            rpc.tls_client_auth_enabled = self.tls_client_auth_enabled

            if self.http_basic_auth_enabled:
                checker = PasswordChecker(self.passwdCheckFunction)
                realm = HttpPasswordRealm(rpc)
                p = portal.Portal(realm, [checker])

                realm_name = 'Reflect RPC'

                if sys.version_info.major == 2:
                    realm_name = realm_name.encode('utf-8')

                credentialFactory = BasicCredentialFactory(realm_name)
                rpc = HTTPAuthSessionWrapper(p, [credentialFactory])

            root = RootResource(rpc)

            f = server.Site(root)
        else:
            f = JsonRpcProtocolFactory(self.rpcprocessor,
                                       self.tls_client_auth_enabled)

        if self.tls_enabled:
            if not self.tls_client_auth_enabled:
                reactor.listenSSL(self.port,
                                  f,
                                  self.cert.options(),
                                  interface=self.host)
            else:
                reactor.listenSSL(self.port,
                                  f,
                                  self.cert.options(self.client_auth_ca),
                                  interface=self.host)
        else:
            if self.host.startswith(unix_prefix):
                path = self.host[len(unix_prefix):]
                reactor.listenUNIX(path,
                                   f,
                                   backlog=self.unix_socket_backlog,
                                   mode=self.unix_socket_mode,
                                   wantPID=self.unix_socket_want_pid)
            else:
                reactor.listenTCP(self.port, f, interface=self.host)

        if self.host.startswith(unix_prefix):
            print("Listening on %s" % (self.host))
        else:
            print("Listening on %s:%d" % (self.host, self.port))

        reactor.run()
Exemplo n.º 12
0
    def on_load(self):
        self.config = self.server.config.web
        with open('./web/js/init.js', 'w') as f:
            port = self.config.web_interface_port2
            auth = self.config.auth_key
            f.write('var server_port = "%s";\n var auth_key = "%s"' % (port,
                                                                       auth))
        root = File('./web')
        root.indexNames = ['index.html']
        root.putChild('css', static.File("./web/css"))
        root.putChild('js', static.File("./web/js"))
        root.putChild('img', static.File("./web/img"))

        checker = PasswordDictChecker(self.config)
        realm = HttpPasswordRealm(root)
        p = portal.Portal(realm, [checker])

        credentialFactory = DigestCredentialFactory("md5",
                                                    "Cuwo Interface Login")
        protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory])

        auth_resource = resource.Resource()
        auth_resource.putChild("", protected_resource)
        site = SiteOverride(auth_resource)

        reactor.listenTCP(self.config.web_interface_port1, site)
        self.web_factory = WebFactory(self)
        reactor.listenTCP(self.config.web_interface_port2,
                          WebSocketFactory(self.web_factory))
Exemplo n.º 13
0
def build_sharing_resource():
    passwd_file = os.path.join(os.path.dirname(__file__), "httpd.password")
    root = build_shared_folder_resource()
    portal = Portal(PublicHTMLRealm(root), [FilePasswordDB(passwd_file)])

    credentialFactory = BasicCredentialFactory("Realm Description....")
    return HTTPAuthSessionWrapper(portal, [credentialFactory])
Exemplo n.º 14
0
def resource():
    """Initialize the HTTP Authentication."""
    resthandle = RestIntf()
    realm = CheckRealm(resource=resthandle.app.resource())
    portal = Portal(realm, [FilePasswordDB('./server-auth.db')])
    credential_factory = BasicCredentialFactory(b"http auth realm")
    return HTTPAuthSessionWrapper(portal, [credential_factory])
Exemplo n.º 15
0
 def authed_resource(self, resource):
     """
     See HTTPInterface.register_resource()
     """
     return HTTPAuthSessionWrapper(
         Portal(EnDroidRealm(resource), self._creds),
         [BasicCredentialFactory("EnDroid")])
Exemplo n.º 16
0
def wrap_with_auth(resource, passwdF, realm="Auth"):
    """
    @param resource: resource to protect
    """
    checkers = [PasswordDictCredentialChecker(passwdF)]

    return HTTPAuthSessionWrapper(Portal(PublicHTMLRealm(resource), checkers),
                                  [BasicCredentialFactory(realm)])
Exemplo n.º 17
0
def wrap_with_auth(resource, passwords, realm="Auth"):
    """
    @param resource: resource to protect
    @param passwords: a dict-like object mapping usernames to passwords
    """
    portal = Portal(PublicHTMLRealm(resource),
                    [PasswordDictCredentialChecker(passwords)])
    credentialFactory = BasicCredentialFactory(realm)
    return HTTPAuthSessionWrapper(portal, [credentialFactory])
Exemplo n.º 18
0
    def setUp(self):
        checker = InMemoryUsernamePasswordDatabaseDontUse(user='******')
        portal = Portal(AuthDummyServer(), [checker])
        credentialFactory = BasicCredentialFactory('localhost')
        resource = HTTPAuthSessionWrapper(portal, [credentialFactory])
        site = Site(resource)

        self.port = reactor.listenTCP(0, site)
        self.portNumber = self.port._realPortNumber
Exemplo n.º 19
0
def run_server(project):
    portal = Portal(ProjectRealm(project), [DatabaseAuth(project.userbase)])

    credentialFactory = BasicCredentialFactory(project.description())
    resource = HTTPAuthSessionWrapper(portal, [credentialFactory])

    factory = Site(resource)
    reactor.listenTCP(8880, factory)
    reactor.run()
Exemplo n.º 20
0
    def _authorizedResource(self, request):
        token = request.getCookie(self.cookieName)
        if token is None:
            return HTTPAuthSessionWrapper._authorizedResource(self, request)

        try:
            username = self.decryptToken(token)
        except InvalidToken:
            request.addCookie(self.cookieName, '',
                  path=b'/', max_age=0)
            return HTTPAuthSessionWrapper._authorizedResource(self, request)

        def _cb((interface, avatar, logout)):
            return avatar

        credentials = Preauthenticated(username)
        d = self._portal.login(credentials, None, IResource)
        d.addCallback(_cb)
        return DeferredResource(d)
Exemplo n.º 21
0
def boot(listen_addr='127.0.0.1',
         port=8080,
         session_bus=False,
         sage_www_root=DEFAULT_SAGE_ROOT,
         auth_realm=None,
         auth_passwd=None,
         allow_ga=None,
         deny_ga=None,
         no_www=False):

    assert not (
        allow_ga and deny_ga
    ), 'Must not specify both deny and allow rules for group addresses'
    global api
    global factory
    DBusGMainLoop(set_as_default=True)

    if session_bus:
        bus = dbus.SessionBus()
    else:
        bus = dbus.SystemBus()

    obj = bus.get_object(DBUS_SERVICE, DBUS_PATH)
    api = dbus.Interface(obj, DBUS_INTERFACE)

    uri = createWsUrl(listen_addr, port)
    factory = SageProtocolFactory(uri,
                                  debug=False,
                                  api=api,
                                  allow_ga=allow_ga,
                                  deny_ga=deny_ga)
    factory.setProtocolOptions(allowHixie76=True, webStatus=False)
    factory.protocol = SageProtocol
    factory.clients = []

    resource = WebSocketResource(factory)

    if no_www:
        root = resource
    else:
        root = File(sage_www_root)
        root.putChild('saged', resource)

    if auth_realm != None and auth_passwd != None:
        portal = Portal(SageRealm(root), [ApachePasswordDB(auth_passwd)])
        credentialFactories = [
            BasicCredentialFactory(auth_realm),
        ]
        root = HTTPAuthSessionWrapper(portal, credentialFactories)

    site = Site(root)
    site.protocol = HTTPChannelHixie76Aware
    reactor.listenTCP(port, site, interface=listen_addr)

    reactor.run()
Exemplo n.º 22
0
def get_web_app(config, controller):
    auth = config.get_bool('web', 'auth', False)
    if auth:
        auth_file = config.get_string('web', 'auth-db')
        portal = Portal(PublicHTMLRealm(config, controller),
                        [FilePasswordDB(auth_file)])
        credential_factory = DigestCredentialFactory('md5', b'scrapy-do')
        resource = HTTPAuthSessionWrapper(portal, [credential_factory])
        return resource

    return WebApp(config, controller)
Exemplo n.º 23
0
 def get_authenticated_resource(self, resource):
     if not self.web_username:
         return resource
     realm = HttpRpcRealm(resource)
     checkers = [
         StaticAuthChecker(self.web_username, self.web_password),
     ]
     portal = Portal(realm, checkers)
     cred_factories = [
         BasicCredentialFactory(self.web_auth_domain),
     ]
     return HTTPAuthSessionWrapper(portal, cred_factories)
Exemplo n.º 24
0
def main():
    readIniFile()
    LOGGING['handlers']['file']['filename'] = logpath + '/mpexagent.log'
    logging.config.dictConfig(LOGGING)
    observer = twlog.PythonLoggingObserver()
    observer.start()

    args = parse_args()
    try:
        if args.mpex_url:
            mpexagent = MPExAgent(replaycheck=True, mpexurl=args.mpex_url)
        else:
            mpexagent = MPExAgent(replaycheck=True)
        mpexagent.passphrase = getpass("Enter your GPG passphrase: ")
        root = JSON_RPC().customize(RPCServer)
        root.eventhandler.agent = mpexagent

        if (mode != 'noweb'):
            webroot = static.File(webpath)
            webroot.putChild('jsonrpc', root)
            root = webroot
            if (auth != 'noauth'):
                if (auth == 'md5'):
                    hashfunc = hashmd5
                if (auth == 'sha1'):
                    hashfunc = hashsha1
                if (auth == 'plain'):
                    hashfunc = hashplain

                realm = HttpPasswordRealm(root)
                p = portal.Portal(realm, [
                    checkers.FilePasswordDB(passpath, delim=":", hash=hashfunc)
                ])
                credentialFactory = BasicCredentialFactory("MpexAgent")
                protected_resource = HTTPAuthSessionWrapper(
                    p, [credentialFactory])
                root = protected_resource

        site = server.Site(root)
        bindaddr = '*:' if args.listen_addr == '' else args.listen_addr + ':'
        log.info('Listening on %s%d...', bindaddr, args.port)

        if (mode != 'https'):
            reactor.listenTCP(args.port, site, interface=args.listen_addr)
        else:
            reactor.listenSSL(
                args.port, site,
                ssl.DefaultOpenSSLContextFactory(keypath, certpath))
        reactor.run()

    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()
Exemplo n.º 25
0
 def getChildWithDefault(self, name, request):
     if name == 'openid':
         return OpenIDEndpoint('https://steamcommunity.com/openid',
                               self.openIDStore, self.loginSemaphore,
                               self._steamLogin)
     if name == 'logout':
         # Delete auth cookie
         request.addCookie(self.cookieName, '',
                           path=b'/', max_age=0)
         request.getSession().expire()
         return Redirect(self.redirectTo)
     return HTTPAuthSessionWrapper.getChildWithDefault(self, name, request)
Exemplo n.º 26
0
    def startService(self):
        service.Service.startService(self)
        if self.broker:
            # daemon mode - print init message
            log.debug("fileserver init")
            self.storage = self.broker.storage
            self.db = self.broker.db
            self.keyring = self.broker.keyring
        else:
            # standalone - print version
            self.print_version()
            # create storage and database connection on our own
            self.storage = storage.__dict__[self.config['broker']['storage'][0]](*self.config['broker']['storage'][1:])
            self.db = database.connect_config(self.config)
            self.storage.set_datasource(self.db)
            self.keyring = keyring.Keyring(database.servers(self.db), str(self.config['server']['fingerprint']))

        credFactory = utils.AuthKontalkTokenFactory(str(self.config['server']['fingerprint']), self.keyring)

        # setup upload endpoint
        portal = Portal(FileUploadRealm(self), [utils.AuthKontalkToken()])
        resource = HTTPAuthSessionWrapper(portal, [credFactory])
        self.putChild('upload', resource)

        # setup download endpoint
        portal = Portal(FileDownloadRealm(self), [utils.AuthKontalkToken()])
        resource = HTTPAuthSessionWrapper(portal, [credFactory])
        self.putChild('download', resource)

        # setup serverlist endpoint
        self.putChild('serverlist', ServerlistDownload(self))

        # create http service
        factory = server.Site(self)
        fs_service = internet.TCPServer(port=self.config['server']['fileserver.bind'][1],
            factory=factory, interface=self.config['server']['fileserver.bind'][0])
        fs_service.setServiceParent(self.parent)

        # old attachments entries purger
        self._loop(self.config['fileserver']['attachments_purger.delay'], self._purge_attachments, True)
Exemplo n.º 27
0
def makeAgentService(store):
    """
    Returns a service which will process GatewayAMPCommands, using a socket
    file descripter acquired by launchd

    @param store: an already opened store
    @returns: service
    """
    from twisted.internet import reactor

    sockets = launchActivateSocket("AgentSocket")
    fd = sockets[0]

    family = socket.AF_INET
    endpoint = AdoptedStreamServerEndpoint(reactor, fd, family)

    directory = store.directoryService()

    def becameInactive():
        log.warn("Agent inactive; shutting down")
        reactor.stop()

    from twistedcaldav.config import config
    inactivityDetector = InactivityDetector(
        reactor, config.AgentInactivityTimeoutSeconds, becameInactive
    )
    root = Resource()
    root.putChild(
        "gateway",
        AgentGatewayResource(
            store, directory, inactivityDetector
        )
    )

    # We need this service to be able to return com.apple.calendarserver,
    # so tell it not to suppress system accounts.
    directory = OpenDirectoryDirectoryService(
        "/Local/Default", suppressSystemRecords=False
    )

    portal = Portal(
        AgentRealm(root, [u"com.apple.calendarserver"]),
        [HTTPDigestCredentialChecker(directory)]
    )
    credentialFactory = NoQOPDigestCredentialFactory(
        "md5", "/Local/Default"
    )
    wrapper = HTTPAuthSessionWrapper(portal, [credentialFactory])

    site = Site(wrapper)

    return StreamServerEndpointService(endpoint, site)
Exemplo n.º 28
0
    def getChild(self, conversation_key, request):
        if conversation_key:
            res = self.resource_class(self.worker, conversation_key)
            checker = ConversationAccessChecker(self.worker, conversation_key)
            realm = ConversationRealm(res)
            p = portal.Portal(realm, [checker])

            factory = BasicCredentialFactory("Conversation Realm")
            protected_resource = HTTPAuthSessionWrapper(p, [factory])

            return protected_resource
        else:
            return resource.NoResource()
Exemplo n.º 29
0
def protectResource(resource, accessKey, secretKey, realm=None):

    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    from twisted.web.guard import HTTPAuthSessionWrapper
    from twisted.cred.portal import Portal

    portal_realm = _SingleResourceRealm(resource)

    cred_checker = InMemoryUsernamePasswordDatabaseDontUse()
    cred_checker.addUser(accessKey, secretKey)
    portal = Portal(portal_realm, [cred_checker])

    cred_factory = AuthHMACCredentialFactory(realm or 'twoost-app')
    return HTTPAuthSessionWrapper(portal, [cred_factory])
Exemplo n.º 30
0
    def __init__(self, server, filename):
        """
        Initialisation. Read saved data from disk, start looping calls that check system resources and read SIM card
        data and serve the dashboard webpage.

        @param   server (Olof)   Reference to the main Olof server instance.
        """
        olof.core.Plugin.__init__(self, server, filename)
        self.base_path = self.server.paths['plugins'] + '/dashboard'

        self.root = RootResource(self)
        status_resource = self.root
        self.root.putChild("dashboard", status_resource)

        authFile = self.base_path + '/data/auth.password'
        if os.path.isfile(authFile):
            portal = Portal(AuthenticationRealm(self),
                            [FilePasswordDB(authFile)])
            credfac = BasicCredentialFactory("Gyrid Server")
            rsrc = HTTPAuthSessionWrapper(portal, [credfac])
            status_resource.putChild("content", rsrc)
        else:
            status_resource.putChild("content", ContentResource(self))

        status_resource.putChild("static",
                                 StaticResource(self.base_path + "/static/"))

        self.scanners = self.storage.loadObject('scanners', {})
        for s in self.scanners.values():
            s.init(self)
            for sens in s.sensors.values():
                sens.init()

        try:
            import multiprocessing
            self.cpuCount = multiprocessing.cpu_count()
        except:
            self.cpuCount = 1

        self.connectionLagProcessing = True

        self.parseMVNumbers()
        self.updateConnectionLagConfig()

        self.checkResourcesCall = task.LoopingCall(self.checkResources)
        self.checkResourcesCall.start(10)

        reactor.callLater(2, self.startListening)
Exemplo n.º 31
0
def application(config):
    app = Application("Scrapyd")
    http_port = config.getint('http_port', 6800)
    bind_address = config.get('bind_address', '127.0.0.1')
    poll_interval = config.getfloat('poll_interval', 5)

    poller = QueuePoller(config)
    eggstorage = FilesystemEggStorage(config)
    scheduler = SpiderScheduler(config)
    environment = Environment(config)

    app.setComponent(IPoller, poller)
    app.setComponent(IEggStorage, eggstorage)
    app.setComponent(ISpiderScheduler, scheduler)
    app.setComponent(IEnvironment, environment)

    laupath = config.get('launcher', 'scrapyd.launcher.Launcher')
    laucls = load_object(laupath)
    launcher = laucls(config, app)

    timer = TimerService(poll_interval, poller.poll)

    webpath = config.get('webroot', 'scrapyd.website.Root')
    webcls = load_object(webpath)

    username = config.get('username', '')
    password = config.get('password', '')
    if username and password:
        if ':' in username:
            sys.exit("The `username` option contains illegal character ':', "
                     "check and update the configuration file of Scrapyd")
        portal = Portal(PublicHTMLRealm(webcls(config, app)),
                        [StringCredentialsChecker(username, password)])
        credential_factory = BasicCredentialFactory("Auth")
        resource = HTTPAuthSessionWrapper(portal, [credential_factory])
        log.msg("Basic authentication enabled")
    else:
        resource = webcls(config, app)
        log.msg("Basic authentication disabled as either `username` or `password` is unset")
    webservice = TCPServer(http_port, server.Site(resource), interface=bind_address)
    log.msg(format="Scrapyd web console available at http://%(bind_address)s:%(http_port)s/",
            bind_address=bind_address, http_port=http_port)

    launcher.setServiceParent(app)
    timer.setServiceParent(app)
    webservice.setServiceParent(app)

    return app
Exemplo n.º 32
0
    def _get_auth_resource(self,
                           in_resource,
                           password_checker=AnchorePasswordChecker()):
        assert (self.anchore_service is not None)
        assert (hasattr(self.anchore_service, 'configuration'))

        if not password_checker or not self.anchore_service.configuration or not self.anchore_service.configuration.get(
                'require_auth', False):
            # no auth required
            return in_resource

        realm = HTTPAuthRealm(resource=in_resource)
        portal = Portal(realm, [password_checker])

        credential_factory = BasicCredentialFactory(b'Authentication required')
        return HTTPAuthSessionWrapper(portal, [credential_factory])
Exemplo n.º 33
0
    def secure_resource(self, api_resource):
        """
        Wrap the provide API resource with an HTTP Authentication Session Wrapper

        :param api_resource: API resource to wrap

        :return: Resource, wrapped as requested
        """
        checkers = [self._checker]
        realm = Realm(api_resource, self._checker.users)
        portal = Portal(realm, checkers)

        credentials_factory = DigestCredentialFactory(self._algorithm,
                                                      self._auth_realm)
        resource = HTTPAuthSessionWrapper(portal, [credentials_factory])
        return resource
Exemplo n.º 34
0
 def _login(self, creds):
     log.msg("Logging in: {0!r}".format(creds))
     return HTTPAuthSessionWrapper._login(self, creds)