def testNewUserWithoutRights(self):
     session = {'user': BasicHtmlLoginForm.User('auser')}
     pf = PasswordFile(join(self.tempdir, 'passwd'))
     self.form.addObserver(pf)
     Body = urlencode(dict(username='******', password='******', retypedPassword='******', formUrl='/page/newUser', returnUrl='/return'))
     result = asString(self.form.handleRequest(path='/action/newUser', Client=('127.0.0.1', 3451), Method='POST', Body=Body, session=session))
     header, body = result.split(CRLF*2)
     self.assertEquals(['admin'], pf.listUsernames())
     self.assertTrue('401' in header)
예제 #2
0
 def testReadPasswordFile(self):
     passwdHash = poorHash('passwordsalt')
     data = dict(users={'John': {
         'salt': 'salt',
         'password': passwdHash
     }},
                 version=PasswordFile.version)
     jsonSave(data, open(self.filename, 'w'))
     pf = PasswordFile(filename=self.filename, hashMethod=poorHash)
     self.assertTrue(pf.validateUser('John', 'password'))
    def testNewUserWithPOSTFailsDifferentPasswords(self):
        pf = PasswordFile(join(self.tempdir, 'passwd'))
        self.form.addObserver(pf)
        pf.addUser('existing', 'password')
        Body = urlencode(dict(username='******', password='******', retypedPassword='******', formUrl='/page/newUser', returnUrl='/return'))
        session = {'user': BasicHtmlLoginForm.User('admin')}

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

        header, body = result.split(CRLF*2)
        self.assertTrue('302' in header)
        self.assertTrue('Location: /page/newUser' in header)

        self.assertEquals(set(['existing', 'admin']), set(pf.listUsernames()))
        self.assertEquals({'errorMessage':'Passwords do not match', 'username':'******'}, session['BasicHtmlLoginForm.newUserFormValues'])
예제 #4
0
 def testConvert(self):
     userstxt = join(self.tempdir, 'users.txt')
     with open(userstxt, 'w') as f:
         f.write('user1:{0}\nuser2:{1}'.format(md5Hash('secret1'),
                                               md5Hash('secret2')))
     pwd = PasswordFile.convert(userstxt, self.filename)
     self.assertTrue(pwd.validateUser('user1', 'secret1'))
예제 #5
0
    def testParameterizedStorage(self):
        args = []

        class Storage(object):
            def store(self, id_, data):
                args.append((id_, data))

            def retrieve(self, id_):
                if len(args) < 1 or args[-1][0] != id_:
                    raise KeyError
                data = args[-1][1]
                return data

        pwd = PasswordFile('a name', storage=Storage())
        pwd.addUser(username='******', password='******')
        id_, data = args[-1]
        self.assertEquals('a name', id_)
        self.assertTrue('erik'
                        in data)  # I believe. More elaborate tests above.
    def testShowUserList(self):
        pf = PasswordFile(join(self.tempdir, 'passwd'))
        self.form.addObserver(pf)
        pf.addUser('one', 'password')
        pf.addUser('two', 'password')
        pf.addUser('three', 'password')
        def enrichUser(user):
            user.title = lambda: user.name.title()
        o = CallTrace(onlySpecifiedMethods=True, methods=dict(enrichUser=enrichUser))
        self.form.addObserver(o)

        session = {'user': self.form.loginAsUser('two')}
        session['user'].canEdit = lambda username=None: username not in ['two', 'admin']

        result = asString(self.form.userList(session=session, path='/show/login'))

        self.assertEqualsWS("""<div id="login-user-list">
    <script type="text/javascript">
function deleteUser(username) {
    if (confirm("Are you sure?")) {
        document.removeUser.username.value = username;
        document.removeUser.submit();
    }
}
</script>
<form name="removeUser" method="POST" action="/action/remove">
    <input type="hidden" name="formUrl" value="/show/login"/>
    <input type="hidden" name="username"/>
</form>
    <ul>
        <li>Admin</li>
        <li>One <a href="javascript:deleteUser('one');">delete</a></li>
        <li>Three <a href="javascript:deleteUser('three');">delete</a></li>
        <li>Two</li>
    </ul>
</div>""", result)

        result = asString(self.form.userList(session=session, path='/show/login', userLink='/user'))

        self.assertEqualsWS("""<div id="login-user-list">
    <script type="text/javascript">
function deleteUser(username) {
    if (confirm("Are you sure?")) {
        document.removeUser.username.value = username;
        document.removeUser.submit();
    }
}
</script>
<form name="removeUser" method="POST" action="/action/remove">
    <input type="hidden" name="formUrl" value="/show/login"/>
    <input type="hidden" name="username"/>
</form>
    <ul>
        <li><a href="/user?user=admin">Admin</a></li>
        <li><a href="/user?user=one">One</a> <a href="javascript:deleteUser('one');">delete</a></li>
        <li><a href="/user?user=three">Three</a> <a href="javascript:deleteUser('three');">delete</a></li>
        <li><a href="/user?user=two">Two</a></li>
    </ul>
</div>""", result)
예제 #7
0
 def testCreateSaltAfterConversion(self):
     tmpfile = join(self.tempdir, 'passwdwithoutsalt')
     with open(tmpfile, 'w') as f:
         dump(
             dict(users=dict(
                 username=dict(salt='', password=md5Hash('secret'))),
                  version=PasswordFile.version), f)
     pwd = PasswordFile(tmpfile)
     self.assertTrue(pwd.validateUser('username', 'secret'))
     d = load(open(tmpfile))
     self.assertTrue(5, len(d['users']['username']['salt']))
     pwd = PasswordFile(tmpfile)
     self.assertTrue(pwd.validateUser('username', 'secret'))
    def testNewEmptyPassword(self):
        pf = PasswordFile(join(self.tempdir, 'passwd'))
        self.form.addObserver(pf)
        pf.addUser('existing', 'password')
        Body = urlencode(dict(username='******', oldPassword='******', newPassword='', retypedPassword='', formUrl='/page/newUser', returnUrl='/return'))
        session = {'user': BasicHtmlLoginForm.User('admin')}

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

        header, body = result.split(CRLF*2)
        self.assertTrue('302' in header)
        self.assertTrue('Location: /page/newUser' in header)

        self.assertEquals(set(['existing', 'admin']), set(pf.listUsernames()))
        self.assertTrue(pf.validateUser('existing', 'password'))
        self.assertEquals({'errorMessage':'New password is invalid.', 'username':'******'}, session['BasicHtmlLoginForm.formValues'])
    def testNewUserWithPOSTsucceeds(self):
        pf = PasswordFile(join(self.tempdir, 'passwd'))
        self.form.addObserver(pf)
        observer = CallTrace()
        self.form.addObserver(observer)
        pf.addUser('existing', 'password')
        Body = urlencode(dict(username='******', password='******', retypedPassword='******', formUrl='/page/newUser', returnUrl='/return'))
        session = {'user': BasicHtmlLoginForm.User('admin')}

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

        header, body = result.split(CRLF*2)
        self.assertTrue('302' in header)
        self.assertTrue('Location: /return' in header)

        self.assertEquals(set(['existing', 'newuser', 'admin']), set(pf.listUsernames()))
        self.assertTrue(pf.validateUser('newuser', 'secret'))
        self.assertEquals('Added user "newuser"', session['BasicHtmlLoginForm.newUserFormValues']['successMessage'])
        self.assertEqual(['addUser', 'handleNewUser'], observer.calledMethodNames())
        self.assertEqual({'username': '******', 'password': '******'}, observer.calledMethods[0].kwargs)
        self.assertEqual({'Body': 'username=newuser&formUrl=%2Fpage%2FnewUser&password=secret&returnUrl=%2Freturn&retypedPassword=secret', 'username': '******'}, observer.calledMethods[1].kwargs)
예제 #10
0
 def testAddUser(self):
     self.pwd.addUser(username='******', password='******')
     self.assertTrue(self.pwd.validateUser('John', 'password'))
     # reopen file.
     pf = PasswordFile(filename=self.filename, hashMethod=poorHash)
     self.assertTrue(pf.validateUser('John', 'password'))
예제 #11
0
 def setUp(self):
     SeecrTestCase.setUp(self)
     self.filename = join(self.tempdir, 'passwd')
     with stdout_replaced() as self.stdout:
         self.pwd = PasswordFile(filename=self.filename,
                                 hashMethod=poorHash)
예제 #12
0
class PasswordFileTest(SeecrTestCase):
    def setUp(self):
        SeecrTestCase.setUp(self)
        self.filename = join(self.tempdir, 'passwd')
        with stdout_replaced() as self.stdout:
            self.pwd = PasswordFile(filename=self.filename,
                                    hashMethod=poorHash)

    def testReadPasswordFile(self):
        passwdHash = poorHash('passwordsalt')
        data = dict(users={'John': {
            'salt': 'salt',
            'password': passwdHash
        }},
                    version=PasswordFile.version)
        jsonSave(data, open(self.filename, 'w'))
        pf = PasswordFile(filename=self.filename, hashMethod=poorHash)
        self.assertTrue(pf.validateUser('John', 'password'))

    def testAddUser(self):
        self.pwd.addUser(username='******', password='******')
        self.assertTrue(self.pwd.validateUser('John', 'password'))
        # reopen file.
        pf = PasswordFile(filename=self.filename, hashMethod=poorHash)
        self.assertTrue(pf.validateUser('John', 'password'))

    def testValidPassword(self):
        self.pwd.addUser(username='******', password='******')
        self.assertFalse(self.pwd.validateUser(username='******', password=''))
        self.assertFalse(self.pwd.validateUser(username='******', password='******'))
        self.assertFalse(self.pwd.validateUser(username='******',
                                               password='******'))
        self.assertTrue(
            self.pwd.validateUser(username='******', password='******'))
        self.assertFalse(
            self.pwd.validateUser(username='******', password='******'))

        self.assertFalse(self.pwd.validateUser(username='', password=''))
        self.assertFalse(self.pwd.validateUser(username='******', password=''))

    def testSetPassword(self):
        self.pwd.addUser(username='******', password='******')
        self.pwd.setPassword(username='******', password='******')
        self.assertTrue(
            self.pwd.validateUser(username='******', password='******'))

    def testSetPasswordWithBadUsername(self):
        self.assertRaises(ValueError,
                          self.pwd.setPassword,
                          username='******',
                          password='******')

    def testPasswordTest(self):
        self.assertTrue(self.pwd._passwordTest('something'))
        self.assertTrue(self.pwd._passwordTest('s om et hing'))
        self.assertTrue(self.pwd._passwordTest('ng'))
        self.assertTrue(self.pwd._passwordTest('SOMETHING'))
        self.assertTrue(self.pwd._passwordTest('123513'))
        self.assertFalse(self.pwd._passwordTest(''))
        self.assertFalse(self.pwd._passwordTest(' '))
        self.assertFalse(self.pwd._passwordTest('\t'))
        self.assertFalse(self.pwd._passwordTest('\t\n'))

    def testAddUserWithBadPassword(self):
        self.assertRaises(ValueError,
                          self.pwd.addUser,
                          username='******',
                          password='')

    def testAddUserWithBadname(self):
        self.assertRaises(ValueError,
                          self.pwd.addUser,
                          username='',
                          password='******')

    def testChangePasswordWithBadPassword(self):
        self.pwd.addUser(username='******', password='******')
        self.assertRaises(ValueError,
                          self.pwd.changePassword,
                          username='******',
                          oldPassword='******',
                          newPassword='')

    def testChangePasswordWithEmptyOldPassword(self):
        self.pwd.addUser(username='******', password='******')
        self.pwd.changePassword(username='******',
                                oldPassword=None,
                                newPassword='******')
        self.assertFalse(
            self.pwd.validateUser(username='******', password='******'))
        self.assertTrue(
            self.pwd.validateUser(username='******', password='******'))

    def testUsernameTest(self):
        self.assertTrue(self.pwd._usernameTest('name'))
        self.assertTrue(self.pwd._usernameTest('*****@*****.**'))
        self.assertTrue(self.pwd._usernameTest('name-1235'))
        self.assertFalse(self.pwd._usernameTest('name\t-1235'))
        self.assertFalse(self.pwd._usernameTest(''))
        self.assertFalse(self.pwd._usernameTest(' '))
        self.assertFalse(self.pwd._usernameTest(' name'))

    def testAddExistingUser(self):
        self.pwd.addUser(username='******', password='******')
        self.assertRaises(ValueError,
                          self.pwd.addUser,
                          username='******',
                          password='******')

    def testAddMultipleUsers(self):
        self.pwd.addUser(username='******', password='******')
        self.pwd.addUser(username='******', password='******')
        self.pwd.addUser(username='******', password='******')
        self.assertTrue(self.pwd.validateUser('John', 'password'))
        self.assertTrue(self.pwd.validateUser('Johnny', 'password2'))
        self.assertTrue(self.pwd.validateUser('Johann', 'password3'))

    def testRemoveUser(self):
        self.pwd.addUser(username='******', password='******')
        self.assertTrue(self.pwd.validateUser('John', 'password'))
        self.pwd.removeUser(username='******')
        self.assertFalse(self.pwd.validateUser('John', 'password'))

    def testListUsernames(self):
        self.pwd.addUser(username='******', password='******')
        self.pwd.addUser(username='******', password='******')
        self.pwd.addUser(username='******', password='******')
        self.assertEquals(set(['admin', 'hank', 'graham', 'john']),
                          set(self.pwd.listUsernames()))

    def testHasUser(self):
        self.pwd.addUser(username='******', password='******')
        self.assertTrue(self.pwd.hasUser(username='******'))
        self.assertFalse(self.pwd.hasUser(username='******'))

    def testCreateFileIfMissingWithDefaultAdmin(self):
        pw = self.stdout.getvalue().split('"')[3]
        self.assertTrue(self.pwd.validateUser(username='******', password=pw))

    def testConvert(self):
        userstxt = join(self.tempdir, 'users.txt')
        with open(userstxt, 'w') as f:
            f.write('user1:{0}\nuser2:{1}'.format(md5Hash('secret1'),
                                                  md5Hash('secret2')))
        pwd = PasswordFile.convert(userstxt, self.filename)
        self.assertTrue(pwd.validateUser('user1', 'secret1'))

    def testCreateSaltAfterConversion(self):
        tmpfile = join(self.tempdir, 'passwdwithoutsalt')
        with open(tmpfile, 'w') as f:
            dump(
                dict(users=dict(
                    username=dict(salt='', password=md5Hash('secret'))),
                     version=PasswordFile.version), f)
        pwd = PasswordFile(tmpfile)
        self.assertTrue(pwd.validateUser('username', 'secret'))
        d = load(open(tmpfile))
        self.assertTrue(5, len(d['users']['username']['salt']))
        pwd = PasswordFile(tmpfile)
        self.assertTrue(pwd.validateUser('username', 'secret'))

    def testEmptyPasswordfile(self):
        pwd = PasswordFile(join(self.tempdir, 'empty'),
                           createAdminUserIfEmpty=False)
        self.assertEqual([], pwd.listUsernames())

    @stdout_replaced
    def testParameterizedStorage(self):
        args = []

        class Storage(object):
            def store(self, id_, data):
                args.append((id_, data))

            def retrieve(self, id_):
                if len(args) < 1 or args[-1][0] != id_:
                    raise KeyError
                data = args[-1][1]
                return data

        pwd = PasswordFile('a name', storage=Storage())
        pwd.addUser(username='******', password='******')
        id_, data = args[-1]
        self.assertEquals('a name', id_)
        self.assertTrue('erik'
                        in data)  # I believe. More elaborate tests above.
예제 #13
0
 def testEmptyPasswordfile(self):
     pwd = PasswordFile(join(self.tempdir, 'empty'),
                        createAdminUserIfEmpty=False)
     self.assertEqual([], pwd.listUsernames())