def testLogoutWithRememberMe(self):
     form = BasicHtmlLoginForm(action='/action', loginPath='/login', home='/home', rememberMeCookie=True)
     observer = CallTrace(onlySpecifiedMethods=True)
     observer.returnValues['cookieName'] = 'remember-cookie'
     observer.returnValues['removeCookie'] = None
     form.addObserver(observer)
     session = {'user': '******', 'someother': 'value'}
     result = asString(form.logout(session=session, ignored='kwarg', Headers={'Cookie':'remember-cookie=cookieId;othercookie=value'}))
     self.assertEquals('HTTP/1.0 302 Found\r\nSet-Cookie: remember-cookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/\r\nLocation: /home\r\n\r\n', result)
     self.assertEqual({'someother': 'value'}, session)
     self.assertEqual(['cookieName', 'removeCookie'], observer.calledMethodNames())
     self.assertEquals(('cookieId',), observer.calledMethods[1].args)
    def testBroadcastAddUserToAllObservers(self):
        values = []
        dna = be(
            (Observable(),
                (BasicHtmlLoginForm(action="/action", loginPath="/"),
                    (CallTrace(methods={'addUser': lambda *args, **kwargs: values.append(("1st", args, kwargs))}),),
                    (CallTrace(methods={'addUser': lambda *args, **kwargs: values.append(("2nd", args, kwargs))}),),
                    (CallTrace(methods={'addUser': lambda *args, **kwargs: values.append(("3rd", args, kwargs))}),),
                )
            )
        )

        asString(dna.all.handleNewUser(session={'user': BasicHtmlLoginForm.User('admin')}, Body=urlencode(dict(password="******", retypedPassword="******", username='******'))))
        self.assertEquals(3, len(values))
    def testLoginWithPOSTsucceeds(self):
        observer = CallTrace(onlySpecifiedMethods=True, returnValues={'hasUser': True})
        self.form = BasicHtmlLoginForm(action='/action', loginPath='/login', home='/home')
        self.form.addObserver(observer)
        observer.returnValues['validateUser'] = True
        Body = urlencode(dict(username='******', password='******'))
        session = {}

        result = asString(self.form.handleRequest(path='/login', Client=('127.0.0.1', 3451), Method='POST', Body=Body, session=session))

        self.assertEquals('admin', session['user'].name)
        self.assertEquals(True, session['user'].isAdmin())
        header, body = result.split(CRLF*2)
        self.assertTrue('302' in header)
        self.assertTrue('Location: /home' in header)

        self.assertEquals(['validateUser', 'hasUser'], [m.name for m in observer.calledMethods])
        self.assertEquals({'username': '******', 'password':'******'}, observer.calledMethods[0].kwargs)
    def testSetRememberMeCookie(self):
        observer = CallTrace(
            methods={
                'validateUser': lambda username, password: True,
                'createCookie': lambda user: dict(
                    cookie='THIS IS THE COOKIE VALUE',
                    header='Set-Cookie: somevalue',
                )
            },
            onlySpecifiedMethods=True,
            returnValues={'hasUser': True})

        basicHtmlLoginForm = BasicHtmlLoginForm(
            action="/action",
            loginPath="/",
            home="/index",
            rememberMeCookie=True)
        basicHtmlLoginForm._now = lambda: 3600

        dna = be(
            (Observable(),
                (basicHtmlLoginForm,
                    (observer, )
                )
            )
        )

        session = {}
        header, _ = asString(dna.all.handleRequest(
            Method="POST",
            path="/",
            session=session,
            Body=urlencode(dict(username="******", password="******", rememberMe="on"))
        )).split('\r\n\r\n', 1)

        self.assertTrue('user' in session, session)
        headers = headerToDict(header)
        self.assertEquals("/index", headers['Location'])

        self.assertTrue('Set-Cookie' in headers, headers)
        self.assertEquals("somevalue", headers['Set-Cookie'])
    def testLoginForWithRememberMe(self):
        form = BasicHtmlLoginForm(
            action='/action',
            loginPath='/login',
            home='/home',
            rememberMeCookie=True)
        result = asString(form.loginForm(session={}, path='/page/login2'))
        self.assertEqualsWS("""<div id="login-form">
    <form method="POST" name="login" action="/action">
    <input type="hidden" name="formUrl" value="/page/login2"/>
        <dl>
            <dt>Username</dt>
            <dd><input type="text" name="username" value=""/></dd>
            <dt>Password</dt>
            <dd><input type="password" name="password"/></dd>
            <dt>&nbsp;</dt><dd class="rememberMe"><input type="checkbox" name="rememberMe" id="rememberMe" /><label for="rememberMe">Remember me</label></dd>
            <dd class="submit"><input type="submit" id="submitLogin" value="Login"/></dd>
        </dl>
    </form>
    <script type="text/javascript">
        document.getElementById("submitLogin").focus()
    </script>
</div>""", result)
Beispiel #6
0
def dna(reactor, port, dataPath, logPath, statePath, externalUrl, customerLogoUrl, deproxyIps=None, **ignored):
    environment = createEnvironment(dataPath)
    harvesterData = environment.createHarvesterData()
    harvesterDataRetrieve = environment.createHarvesterDataRetrieve()
    deproxy = Deproxy(deproxyForIps=deproxyIps)
    repositoryStatus = be(
        (RepositoryStatus(logPath, statePath),
            (harvesterData, )
        )
    )
    configDict = JsonDict(
        logPath=logPath,
        statePath=statePath,
        externaUrl=externalUrl,
        dataPath=dataPath,
    )
    print("Started Metastreams with configuration:\n" + configDict.pretty_print())

    userGroup = initializeUserGroupManagement(join(statePath, 'users'), harvesterData)
    basicHtmlLoginHelix = (BasicHtmlLoginForm(
        action="/login.action",
        loginPath="/login",
        home="/index",
        rememberMeCookie=False,
        lang="nl"),

        (userGroup.basicHtmlObserver,),
    )
    varWwwdataPath = join(statePath, 'www-data', 'var')
    isdir(varWwwdataPath) or makedirs(varWwwdataPath)

    staticFilePaths = []
    staticFiles = Transparent()
    for path, libdir in [
            ('/js/bootstrap', '/usr/share/javascript/bootstrap5/js'),
            ('/css/bootstrap', '/usr/share/javascript/bootstrap5/css'),
            ('/css/bootstrap-icons', '/usr/share/javascript/bootstrap-icons'),
            ('/js/jquery', '/usr/share/javascript/jquery'),
            ('/js/jquery-tablesorter', '/usr/share/javascript/jquery-tablesorter'),
            ('/css/jquery-tablesorter', '/usr/share/javascript/jquery-tablesorter/css'),
            ('/js/autosize', '/usr/share/javascript/autosize'),
            ('/static', staticHtmlPath),
            ('/var', varWwwdataPath),
            ]:
        staticFiles.addObserver(StaticFiles(libdir=libdir, path=path))
        staticFilePaths.append(path)

    return \
    (Observable(),
        (ObservableHttpServer(reactor, port),
            (LogCollector(),
                (ApacheLogWriter(stdout),),
                (deproxy,
                    (HandleRequestLog(),
                        (BasicHttpHandler(),
                            (SessionHandler(),
                                (CookieMemoryStore(name="meresco-harvester", timeout=2*60*60), ),
                                (UserFromSession(),
                                    (PathFilter("/info/version"),
                                        (StringServer(VERSION_STRING, ContentTypePlainText), )
                                    ),
                                    (PathFilter("/info/config"),
                                        (StringServer(configDict.dumps(), ContentTypeJson), )
                                    ),
                                    (PathFilter('/login.action'),
                                        basicHtmlLoginHelix
                                    ),
                                    (staticFiles,),
                                    (PathFilter('/', excluding=['/info/version', '/info/config', '/action', '/login.action'] + harvesterDataRetrieve.paths + staticFilePaths),
                                        (SecureZone("/login", excluding=["/index", "/invalid", "/rss", '/running.rss', '/showHarvesterStatus'], defaultLanguage="nl"),
                                            (PathFilter('/', excluding=userGroup.excludedPaths),
                                                (DynamicHtml(
                                                        [dynamicHtmlPath],
                                                        reactor=reactor,
                                                        additionalGlobals={
                                                            'externalUrl': externalUrl,
                                                            'escapeXml': escapeXml,
                                                            'compose': compose,
                                                            'dumps': dumps,
                                                            'VERSION': VERSION,
                                                            'CONFIG': configDict,
                                                            'Timeslot': Timeslot,
                                                            'ThroughputAnalyser': ThroughputAnalyser,
                                                            'dateSince': dateSince,
                                                            'callable': callable,
                                                            'OnlineHarvest': OnlineHarvest,
                                                            'StringIO': StringIO,
                                                            'okPlainText': okPlainText,
                                                            'ZuluTime': ZuluTime,
                                                            'xpathFirst': xpathFirst,
                                                            'customerLogoUrl': customerLogoUrl,
                                                            'uuid': lambda: str(uuid4()),
                                                        },
                                                        indexPage="/index",
                                                    ),
                                                    basicHtmlLoginHelix,
                                                    (harvesterData,),
                                                    (repositoryStatus,),
                                                    (userGroup.dynamicHtmlObserver,),
                                                )
                                            ),
                                            (userGroup.actions,),
                                        ),
                                    ),
                                    (PathFilter('/action'),
                                        (HarvesterDataActions(),
                                            (harvesterData,)
                                        ),
                                    ),
                                    (PathFilter(harvesterDataRetrieve.paths),
                                        (harvesterDataRetrieve,
                                            (FilterFields(),
                                                (harvesterData,),
                                            ),
                                            (repositoryStatus,),
                                        )
                                    )
                                )
                            )
                        )
                    )
                )
            )
        )
    )
    def setUp(self):
        SeecrTestCase.setUp(self)

        self.form = BasicHtmlLoginForm(action='/action', loginPath='/login', home='/home')