Example #1
0
def del_user(config, u, p, remove_data):
    try:
        s = api.get_scoped_session(config.conf)
        with s.begin():
            user = api.user_get_by_username(s, u)
            if not user:
                sys.exit("Error: user does not exist!")
            if not utils.checkpw(p, user.password):
                sys.exit("Error: incorrect password!")

            if remove_data:
                printv(config, "Removing user's categories data ...")
                api.category_delete_all(s, user, True)
                printv(config, "Removing user's items data ...")
                api.item_delete_all(s, user)

            printv(config, "Removing user ...")
            api.user_delete(s, user)

            user = api.user_get_by_username(s, u)
            if user:
                print("Error: unable to delete user: '******'" % u)
            else:
                print("Successfully deleted user: '******'" % u)
    except Exception as e:
        sys.exit("Error: %s" % str(e))
Example #2
0
def update_user(config, u, p, new_username, new_password):
    if not (new_username or new_password):
        sys.exit("Error: at least one of: [--new_username, --new_password]"
                 " options must be specified!")
    try:
        s = api.get_scoped_session(config.conf)
        with s.begin():
            user = api.user_get_by_username(s, u)
            if not user:
                sys.exit("Error: user does not exist!")
            if not utils.checkpw(p, user.password):
                sys.exit("Error: incorrect password!")

            if new_username:
                new_user = api.user_get_by_username(s, new_username)
                if new_user:
                    sys.exit("Username: '******' already exists!" % new_username)

            printv(config, "Updating user information")
            if new_username:
                user.username = new_username
            if new_password:
                user.password = utils.hashpw(new_password)
            api.user_update(s, user)
            print("Successfully updated user %s" % user.username)
    except Exception as e:
        sys.exit("Error: %s" % str(e))
Example #3
0
    def test_update_phrase(self):
        config = opp_config.OppConfig(self.conf_filepath)

        # Add user
        utils.execute("opp-db --config_file %s add-user -uu -pp "
                      "--phrase=123456" % self.conf_filepath)

        old = aescipher.AESCipher("123456")
        new = aescipher.AESCipher("654321")

        # Add category and item using old passphrase
        session = api.get_scoped_session(config)
        category = models.Category(name=old.encrypt("cat1"))
        item = models.Item(name=old.encrypt("item1"),
                           url=old.encrypt("url1"),
                           account=old.encrypt("account1"),
                           username=old.encrypt("username1"),
                           password=old.encrypt("password1"),
                           blob=old.encrypt("blob1"))
        with session.begin():
            user = api.user_get_by_username(session, 'u')
            category.user = user
            item.user = user
            api.category_create(session, [category])
            api.item_create(session, [item])

        # Update passphrase
        utils.execute("opp-db --config_file %s update-phrase -uu -pp "
                      "--old_phrase=123456 --new_phrase=654321" %
                      self.conf_filepath)

        # Check data using new passphrase
        session = api.get_scoped_session(config)
        with session.begin():
            user = api.user_get_by_username(session, 'u')
            category = api.category_getall(session, user)[0]
            self.assertEqual(new.decrypt(category.name), "cat1")
            item = api.item_getall(session, user)[0]
            self.assertEqual(new.decrypt(item.name), "item1")
            self.assertEqual(new.decrypt(item.url), "url1")
            self.assertEqual(new.decrypt(item.account), "account1")
            self.assertEqual(new.decrypt(item.username), "username1")
            self.assertEqual(new.decrypt(item.password), "password1")
            self.assertEqual(new.decrypt(item.blob), "blob1")

        # Cleanup
        utils.execute("opp-db --config_file %s del-user -uu -pp"
                      " --remove_data" % self.conf_filepath)
        self._assert_user_does_not_exist('u')
Example #4
0
    def _do_put(self, phrase):
        request_body = self.request.get_json()

        # Check required username field
        try:
            username = request_body['username']
        except KeyError:
            return self.error("Missing username!")
        if not username:
            return self.error("Empty username!")

        # Extract required password field
        try:
            password = request_body['password']
        except KeyError:
            return self.error("Missing password!")
        if not password:
            return self.error("Empty password!")

        try:
            user = api.user_get_by_username(username, session=self.session)
            if user:
                return self.error("User already exists!")
            hashed = utils.hashpw(password)
            user = models.User(username=username, password=hashed)
            api.user_create(user, session=self.session)
            return {'result': "success"}
        except Exception:
            return self.error("Unable to add new user the database!")
Example #5
0
    def _do_delete(self):
        request_body = self.request.get_json()

        # Extract required username field
        try:
            username = request_body['username']
        except KeyError:
            return self.error("Missing username!")
        if not username:
            return self.error("Empty username!")

        # Extract required password field
        try:
            password = request_body['password']
        except KeyError:
            return self.error("Missing password!")
        if not password:
            return self.error("Empty password!")

        try:
            user = api.user_get_by_username(username, session=self.session)
            if not user:
                return self.error("User doesn't exist!")
            if not utils.checkpw(password, user.password):
                return self.error("Invalid password!")
            api.user_delete_by_username(username, session=self.session)
            return {'result': "success"}
        except Exception:
            return self.error("Unable to delete user from the database!")
Example #6
0
    def _do_put(self, phrase):
        """
        Create a new user.

        :param phrase: not used

        :returns: success result
        """
        payload_dicts = [{
            'name': "username",
            'is_list': False,
            'required': True
        }, {
            'name': "password",
            'is_list': False,
            'required': True
        }, {
            'name': "phrase",
            'is_list': False
        }]
        payload_objects = self._check_payload(payload_dicts)

        u = self._validate(payload_objects[0], 'username')
        p = self._validate(payload_objects[1], 'password')
        phrase = self._validate(payload_objects[2], 'phrase')
        if len(phrase) < 6:
            raise bh.OppError("Passphrase must be at least 6 characters long!")

        try:
            cipher = aescipher.AESCipher(phrase)
            ok = cipher.encrypt("OK")
            user = api.user_get_by_username(self.session, u)
            if user:
                raise bh.OppError("User already exists!")
            hashed = utils.hashpw(p)
            user = models.User(username=u, password=hashed, phrase_check=ok)
            api.user_create(self.session, user)
            user = api.user_get_by_username(self.session, u)
            if user:
                return {'result': 'success'}
            else:
                raise bh.OppError("Unable to add user: '******'" % u)
        except bh.OppError as e:
            raise bh.OppError(e.error, e.desc, e.status, e.headers)
        except Exception:
            raise bh.OppError("Unable to add user: '******'" % u)
Example #7
0
def login():
    if request.method == 'POST':
        user = api.user_get_by_username(request.form['username'])
        if user and utils.checkpw(request.form['password'], user.password):
            session['username'] = request.form['username']
            return redirect(url_for('index'))
        else:
            return redirect(url_for('login'))
    elif 'username' in session:
        return redirect(url_for('index'))
    return '''
Example #8
0
def add_user(config, u, p, phrase):
    if len(phrase) < 6:
        sys.exit("Error: passphrase must be at least 6 characters long!")
    try:
        cipher = aescipher.AESCipher(phrase)
        ok = cipher.encrypt("OK")
        s = api.get_scoped_session(config.conf)
        with s.begin():
            user = api.user_get_by_username(s, u)
            if user:
                sys.exit("Error: user already exists!")
            hashed = utils.hashpw(p)
            user = models.User(username=u, password=hashed, phrase_check=ok)
            api.user_create(s, user)
            user = api.user_get_by_username(s, u)
            if user:
                print("Successfully added new user: '******'" % u)
            else:
                print("Error: unable to add user: '******'" % u)
    except Exception as e:
        sys.exit("Error: %s" % str(e))
Example #9
0
    def _do_delete(self):
        """
        Delete a user.

        :returns: success result
        """
        payload_dicts = [{
            'name': "username",
            'is_list': False,
            'required': True
        }, {
            'name': "password",
            'is_list': False,
            'required': True
        }]
        payload_objects = self._check_payload(payload_dicts)

        u = self._validate(payload_objects[0], 'username')
        p = self._validate(payload_objects[1], 'password')

        try:
            user = api.user_get_by_username(self.session, u)
            if not user:
                raise bh.OppError("User does not exist!")
            if not utils.checkpw(p, user.password):
                raise bh.OppError("Incorrect password supplied!")

            api.category_delete_all(self.session, user, True)
            api.item_delete_all(self.session, user)
            api.user_delete(self.session, user)

            user = api.user_get_by_username(self.session, u)
            if user:
                bh.OppError("Unable to delete user: '******'" % u)
            else:
                return {'result': 'success'}
        except bh.OppError as e:
            raise bh.OppError(e.error, e.desc, e.status, e.headers)
        except Exception:
            raise bh.OppError("Unable to delate user: '******'" % u)
Example #10
0
    def test_categories_access_by_user(self):
        # Verify category list empty initially, add a category and some items
        with self.s.begin():
            categories = api.category_getall(self.s, self.u)
            self.assertEqual(categories, [])
            category = models.Category(name="name", user=self.u)
            api.category_create(self.s, [category])
            items = [
                models.Item(blob="item1", category_id=1, user=self.u),
                models.Item(blob="item2", category_id=1, user=self.u)
            ]
            api.item_create(self.s, items)

        # Retrieve and verify inserted category
        with self.s.begin():
            categories = api.category_getall(self.s, self.u)
            self.assertEqual(len(categories), 1)
            self.assertEqual(categories[0].name, "name")
            self.assertEqual(len(categories[0].items), 2)

        # Add another user and retrieve it
        utils.execute("opp-db --config_file %s add-user -uu2 -pp "
                      "--phrase=123456" % self.conf_filepath)
        new_u = api.user_get_by_username(self.s, "u2")
        self.assertEqual(new_u.username, "u2")

        # Attempt to retrieve categories with new user
        with self.s.begin():
            new_categories = api.category_getall(self.s, new_u)
            self.assertEqual(len(new_categories), 0)

        # Clean up
        with self.s.begin():
            api.category_delete(self.s, categories, True)

        # Verify clean up successful
        with self.s.begin():
            categories = api.category_getall(self.s, self.u)
            self.assertEqual(len(categories), 0)
Example #11
0
    def test_items_access_by_user(self):
        # Verify item list empty initially and add some items
        with self.s.begin():
            items = api.item_getall(self.s, self.u)
            self.assertEqual(items, [])
            items = [
                models.Item(blob="item1", user=self.u),
                models.Item(blob="item2", user=self.u)
            ]
            api.item_create(self.s, items)

        # Retrieve and verify inserted items
        with self.s.begin():
            items = api.item_getall(self.s, self.u)
            self.assertEqual(len(items), 2)
            self.assertEqual(items[0].blob, "item1")
            self.assertEqual(items[1].blob, "item2")

        # Add another user and retrieve it
        utils.execute("opp-db --config_file %s add-user -uu2 -pp "
                      "--phrase=123456" % self.conf_filepath)
        new_u = api.user_get_by_username(self.s, "u2")
        self.assertEqual(new_u.username, "u2")

        # Attempt to retrieve items with new user
        with self.s.begin():
            new_items = api.item_getall(self.s, new_u)
            self.assertEqual(len(new_items), 0)

        # Clean up
        with self.s.begin():
            items = api.item_getall(self.s, self.u)
            api.item_delete(self.s, items)

        # Verify clean up successful
        with self.s.begin():
            items = api.item_getall(self.s, self.u)
            self.assertEqual(len(items), 0)
Example #12
0
    def _do_post(self, phrase):
        request_body = self.request.get_json()

        # Extract required username field
        try:
            username = request_body['username']
        except KeyError:
            return self.error("Missing username!")
        if not username:
            return self.error("Empty username!")

        # Extract required old password field
        try:
            old_password = request_body['current_password']
        except KeyError:
            return self.error("Missing current password!")
        if not old_password:
            return self.error("Empty current password!")

        # Extract required new password field
        try:
            new_password = request_body['new_password']
        except KeyError:
            return self.error("Missing new password!")
        if not new_password:
            return self.error("Empty new password!")

        try:
            user = api.user_get_by_username(username, session=self.session)
            if not user:
                return self.error("User doesn't exist!")
            if not utils.checkpw(old_password, user.password):
                return self.error("Invalid password!")
            user.password = utils.hashpw(new_password)
            api.user_update(user, session=self.session)
            return {'result': "success"}
        except Exception:
            return self.error("Unable to update user in the database!")
Example #13
0
    def test_users_basic(self):
        # Insert and retrieve an user
        user = models.User(username="******", password="******")
        api.user_create(user, session=self.session)
        user = api.user_get_by_username(user.username, session=self.session)
        self.assertIsNotNone(user)
        self.assertEqual(user.username, "user")
        self.assertEqual(user.password, "pass")

        # Update and check the user
        user.username = "******"
        user.password = "******"
        api.user_update(user, session=self.session)
        new_user = api.user_get_by_id(user.id, session=self.session)
        self.assertIsNotNone(new_user)
        self.assertEqual(new_user.username, user.username)
        self.assertEqual(new_user.password, user.password)
        self.assertEqual(new_user.id, user.id)

        # Clean up and verify
        api.user_delete_by_username(user.username, session=self.session)
        user = api.user_get_by_id(user.id, session=self.session)
        self.assertIsNone(user)
Example #14
0
def update_phrase(config, u, p, old_phrase, new_phrase):
    if len(new_phrase) < 6:
        sys.exit("Error: passphrase must be at least 6 characters long!")
    try:
        old_cipher = aescipher.AESCipher(old_phrase)
        new_cipher = aescipher.AESCipher(new_phrase)
        s = api.get_scoped_session(config.conf)
        with s.begin():
            user = api.user_get_by_username(s, u)
            if not user:
                sys.exit("Error: user does not exist!")
            if not utils.checkpw(p, user.password):
                sys.exit("Error: incorrect password!")
            try:
                if old_cipher.decrypt(user.phrase_check) != "OK":
                    sys.exit("Error: incorrect old passphrase supplied!")
            except UnicodeDecodeError:
                sys.exit("Error: incorrect old passphrase supplied!")

            printv(config, "Updating user information")
            user.phrase_check = new_cipher.encrypt("OK")
            api.user_update(s, user)
            printv(config, "Updating user's categories")
            categories = api.category_getall(s, user)
            for category in categories:
                category.recrypt(old_cipher, new_cipher)
            api.category_update(s, categories)
            printv(config, "Updating user's items")
            items = api.item_getall(s, user)
            for item in items:
                item.recrypt(old_cipher, new_cipher)
            api.item_update(s, items)
            print("All of user's data has been successfuly "
                  "re-encrypted with the new passphrase.")
    except Exception as e:
        sys.exit("Error: %s" % str(e))
Example #15
0
    def _do_post(self, phrase):
        """
        Update a user.

        :param phrase: not used

        :returns: success result
        """
        payload_dicts = [{
            'name': "username",
            'is_list': False,
            'required': True
        }, {
            'name': "password",
            'is_list': False,
            'required': True
        }, {
            'name': "new_username",
            'is_list': False,
            'required': False
        }, {
            'name': "new_password",
            'is_list': False,
            'required': False
        }]
        payload_objects = self._check_payload(payload_dicts)

        u = self._validate(payload_objects[0], 'username')
        p = self._validate(payload_objects[1], 'password')
        new_u = payload_objects[2].strip()
        new_p = payload_objects[3].strip()
        if not (new_u or new_p):
            raise bh.OppError("at least one of: "
                              "[--new_username, --new_password] is required!")

        try:
            user = api.user_get_by_username(self.session, u)
            if not user:
                raise bh.OppError("User does not exist!")
            if not utils.checkpw(p, user.password):
                raise bh.OppError("Incorrect password supplied!")

            if new_u:
                new_user = api.user_get_by_username(self.session, new_u)
                if new_user:
                    raise bh.OppError("Username: '******' already exists!" % new_u)

            if new_u:
                user.username = new_u
            if new_p:
                user.password = utils.hashpw(new_p)

            api.user_update(self.session, user)
            user = api.user_get_by_username(self.session, user.username)
            if user:
                return {'result': 'success'}
            else:
                raise bh.OppError("Unable to add user: '******'" % u)
        except bh.OppError as e:
            raise bh.OppError(e.error, e.desc, e.status, e.headers)
        except Exception:
            raise bh.OppError("Unable to update user: '******'" % u)
Example #16
0
def authenticate(username, password):
    user = api.user_get_by_username(username)
    if user and utils.checkpw(password, user.password):
        return user
    return None
Example #17
0
 def setUp(self):
     conf = opp_config.OppConfig(self.conf_filepath)
     self.s = api.get_scoped_session(conf)
     self.u = api.user_get_by_username(self.s, "u")