コード例 #1
0
    def __action_user(self, language, pw_hash_iterations):
        """ Handle user actions. Returns users or redirects. """
        _ = translator.Translator.instance(language)

        action = self.get_form('action')
        if action == 'edit-profile':
            password = self.get_form('password', False)
            password_confirm = self.get_form('password-confirm', False)
            if not password:
                hint_text = _('Please provide the password.')
                self.hints.append(hint.Hint(hint_text))
            elif password != password_confirm:
                hint_text = _('Both passwords are not the same.')
                self.hints.append(hint.Hint(hint_text))
            else:
                user = self.current_user()
                user.salt = self.__generate_salt()
                user.pw_hash = self.__generate_pw_hash(password, user.salt,
                                                       pw_hash_iterations)
                user.session = None
                user.save(self.db)
                hint_text = _('Your profile has been updated. Please login '
                              'again.')
                self.hints.append(hint.Hint(hint_text))
        return []
コード例 #2
0
    def __name_ok(self, name, language):
        """ Validates the name. Returns True if ok. """
        _ = translator.Translator.instance(language)

        if not name:
            hint_text = _('Name must not be empty.').format(name)
            self.hints.append(hint.Hint(hint_text))
            return False

        exists = category.Category.name_exists(self.db, name)
        if exists:
            hint_text = _('Category "{}" already exists.').format(name)
            self.hints.append(hint.Hint(hint_text))
        return not exists
コード例 #3
0
    def __finalize_recipe(self, recipe, is_new, indexer):
        """ Final steps in saving a new or updated recipe. Returns recipe
        or redirects. """
        if is_new:
            manager = user_manager.UserManager(self.db)
            recipe.author = manager.current_user()

        if not recipe.title:
            hint_text = _('Title must not be empty.')
            self.hints.append(hint.Hint(hint_text))
        else:
            # First check if the recipe already exists and is new.
            new_exists = is_new and \
                recipe_entity.Recipe.title_exists(self.db, recipe.title)

            # Save the recipe.
            recipe.save(self.db)

            # Update search index.
            scheme = indexer.scheme()
            writer = indexer.open_index(scheme)
            indexer.fill_index(writer, [recipe])
            indexer.close_index()

            if new_exists:
                type = self.HINT_NEW_EXISTS
            elif is_new:
                type = self.HINT_NEW
            else:
                type = self.HINT_EDIT
            self.set_cookie(self.HINT_COOKIE, type)
            self.set_cookie(self.HINT_NAME, recipe.title)
            redirect(url.Url.from_path(['manage', 'recipe', str(recipe.id)]))

        return recipe
コード例 #4
0
    def login(self, language, pw_hash_iterations, admin_user):
        """ Handle login. Returns hints or redirects. """
        _ = translator.Translator.instance(language)

        if self.get_form('action') == 'login':
            user_name = self.get_form('name')
            password = self.get_form('password', False)
            if not user_name or not password:
                hint_text = _('Please provide your user name and password.')
                self.hints.append(hint.Hint(hint_text))
                return self.hints

            user = user_entity.User.find_name(self.db, user_name)
            hint_text = _('Given user name or password is wrong. Please '
                          'try again.')
            redirect_url = url.Url.from_path([''])
            if not user:
                user_count = user_entity.User.count_all(self.db)
                if not user_count and user_name == admin_user:
                    admin_hash = self.__admin_hash(admin_user,
                                                   pw_hash_iterations)
                    self.set_cookie(self.SESSION_COOKIE, admin_hash)
                    redirect(redirect_url)
                else:
                    self.hints.append(hint.Hint(hint_text))
                    return self.hints

            pw_hash = self.__generate_pw_hash(password, user.salt,
                                              pw_hash_iterations)
            if pw_hash != user.pw_hash:
                self.hints.append(hint.Hint(hint_text))
                return self.hints
            else:
                session_salt = self.__generate_salt()
                session = self.__generate_pw_hash(session_salt, user.salt,
                                                  pw_hash_iterations)
                expires = datetime.datetime.now() + datetime.timedelta(
                    days=365)
                self.set_cookie(self.USER_NAME_COOKIE,
                                user.name,
                                expires=expires)
                self.set_cookie(self.SESSION_COOKIE, session, expires=expires)
                user.session = session
                user.save(self.db)
                redirect(redirect_url)

        return self.hints
コード例 #5
0
    def __action_admin(self, language, pw_hash_iterations):
        """ Handle admin actions. Returns users or redirects. """
        _ = translator.Translator.instance(language)

        action = self.get_form('action')
        if action == 'new':
            user_name = self.get_form('name')
            password = self.get_form('password', False)
            password_confirm = self.get_form('password-confirm', False)
            if not user_name or not password:
                hint_text = _('Please provide user name and password.')
                self.hints.append(hint.Hint(hint_text))
            elif password != password_confirm:
                hint_text = _('Both passwords are not the same.')
                self.hints.append(hint.Hint(hint_text))
            elif user_entity.User.find_name(self.db, user_name):
                hint_text = _('User name is already taken.')
                self.hints.append(hint.Hint(hint_text))
            else:
                user = user_entity.User(name=user_name)
                user.salt = self.__generate_salt()
                user.pw_hash = self.__generate_pw_hash(password, user.salt,
                                                       pw_hash_iterations)
                user.save(self.db)
                hint_text = _('User "{}" has been created.').format(user_name)
                self.hints.append(hint.Hint(hint_text))

        elif action == 'edit':
            id = self.get_form('id')
            user = user_entity.User.find_pk(self.db, id)
            is_delete = self.get_form('delete') is not None
            if is_delete:
                hint_text = _('User "{}" has been deleted.').format(user.name)
                user.delete(self.db)
                self.hints.append(hint.Hint(hint_text))
            else:
                password = self.get_form('password', False)
                password_confirm = self.get_form('password-confirm', False)
                if not password:
                    hint_text = _('Please provide the password.')
                    self.hints.append(hint.Hint(hint_text))
                elif password != password_confirm:
                    hint_text = _('Both passwords are not the same.')
                    self.hints.append(hint.Hint(hint_text))
                else:
                    user.salt = self.__generate_salt()
                    user.pw_hash = self.__generate_pw_hash(
                        password, user.salt, pw_hash_iterations)
                    user.session = None
                    user.save(self.db)
                    hint_text = _('User "{}" has been updated.').format(
                        user.name)
                    self.hints.append(hint.Hint(hint_text))

        return user_entity.User.find_all(self.db)
コード例 #6
0
    def action(self, language):
        """ Handle action for given class name. Returns found entities. """
        _ = translator.Translator.instance(language)

        # Handle actions.
        action = self.get_form('action') or 'show'

        if action == 'new':
            name = self.get_form('name')
            if self.__name_ok(name, language):
                tag = tag_entity.Tag(name=name)
                tag.save(self.db)
                hint_text = _('New tag "{}" has been created.').format(name)
                self.hints.append(hint.Hint(hint_text))

        elif action == 'new-synonym':
            parent = self.get_form('id')
            name = self.get_form('name')
            if self.__name_ok(name, language):
                tag = tag_entity.Tag(name=name, synonym_of=parent)
                tag.save(self.db)
                hint_text = _('New synonym "{}" has been created.').format(
                    name)
                self.hints.append(hint.Hint(hint_text))

        elif action == 'edit':
            is_delete = self.get_form('delete') is not None
            id = int(self.get_form('id'))
            name = self.get_form('name')
            entity = tag_entity.Tag.find_pk(self.db, id)
            entity.name = name

            if is_delete:
                entity.delete(self.db)
                hint_text = _('Tag "{}" has been removed.').format(name)
                self.hints.append(hint.Hint(hint_text))
            else:
                if self.__name_ok(name, language):
                    entity.save(self.db)
                    hint_text = _('Tag "{}" has been updated.').format(name)
                    self.hints.append(hint.Hint(hint_text))

        # Load content.
        return tag_entity.Tag.find_all(self.db)
コード例 #7
0
 def __check_img_extension(self, extension, language):
     """ Checks the given extension. Returns true if extension
      is valid else false.  """
     _ = translator.Translator.instance(language)
     result = True
     if extension.lower() not in ('.png', '.jpg', '.jpeg', '.gif'):
         text = _('Extension "{}" is not an allowed image type.')\
             .format(extension)
         self.hints.append(hint.Hint(text))
         result = False
     return result
コード例 #8
0
    def action(self, language):
        """ Handle action for given class name. Returns found entities. """
        _ = translator.Translator.instance(language)

        # Handle actions.
        action = self.get_form('action') or 'show'

        if action == 'new':
            name = self.get_form('name')
            if self.__name_ok(name, language):
                cat = category.Category(name=name)
                cat.save(self.db)
                hint_text = _('New category "{}" has been created.').format(
                    name)
                self.hints.append(hint.Hint(hint_text))

        elif action == 'edit':
            is_delete = self.get_form('delete') is not None
            id = int(self.get_form('id'))
            name = self.get_form('name')
            entity = category.Category.find_pk(self.db, id)
            entity.name = name

            if is_delete:
                entity.delete(self.db)
                hint_text = _('Category "{}" has been removed.').format(name)
                self.hints.append(hint.Hint(hint_text))
            else:
                if self.__name_ok(name, language):
                    entity.save(self.db)
                    hint_text = _('Category "{}" has been updated.').format(
                        name)
                    self.hints.append(hint.Hint(hint_text))

        # Load content.
        return category.Category.find_all(self.db)
コード例 #9
0
    def __show_hints(self, language):
        """ Show hints if cookies are set. """
        _ = translator.Translator.instance(language)

        hint_cookie = self.get_cookie(self.HINT_COOKIE)
        name_cookie = self.get_cookie(self.HINT_NAME)
        if hint_cookie and name_cookie:
            if hint_cookie == self.HINT_NEW:
                hint_text = _('New recipe "{}" has been created.')
            elif hint_cookie == self.HINT_EDIT:
                hint_text = _('Recipe "{}" has been updated.')
            elif hint_cookie == self.HINT_NEW_EXISTS:
                hint_text = _('New recipe "{}" has been created. '
                              'A recipe with the same title already exists.')
            else:
                hint_text = _('Recipe "{}" has been removed.')
            hint_text = hint_text.format(name_cookie)
            self.hints.append(hint.Hint(hint_text))
            self.delete_cookie(self.HINT_COOKIE)
            self.delete_cookie(self.HINT_NAME)
コード例 #10
0
    def action(self,
               language,
               indexer,
               static_path,
               image_path,
               recipe_json,
               id=None):
        """ Handle actions. If id is given it is assumed that an existing
         recipe is edited. Returns recipe to show. """
        _ = translator.Translator.instance(language)

        is_new = id is None
        is_edit = self.get_form('edit') is not None
        is_delete = self.get_form('delete') is not None
        is_import = self.get_form('import') is not None

        # Actions
        result = None
        if is_edit:
            categories = self.__read_categories()
            images = self.__read_images(language, static_path, image_path)
            synonyms = self.__read_synonyms()
            tags = self.__read_tags()
            urls = self.__read_urls()

            result = recipe_entity.Recipe()
            if not is_new:
                result = recipe_entity.Recipe.find_pk(self.db, id)

            result.categories = categories
            result.description = self.get_form('description')
            result.images = images
            result.info = self.get_form('info')
            result.ingredients = self.get_form('ingredients')
            result.rating = int(self.get_form('rating'))
            result.serving_size = self.get_form('serving-size')
            result.synonyms = synonyms
            result.tags = tags
            result.title = self.get_form('title')
            result.urls = urls

            result = self.__finalize_recipe(result, is_new, indexer)

        elif is_delete:
            recipe = recipe_entity.Recipe.find_pk(self.db, id)

            # Update search index.
            scheme = indexer.scheme()
            writer = indexer.open_index(scheme)
            indexer.remove_from_index(writer, [recipe])
            indexer.close_index()

            recipe.delete(self.db)

            self.set_cookie(self.HINT_COOKIE, self.HINT_DELETE)
            self.set_cookie(self.HINT_NAME, recipe.title)
            redirect(url.Url.from_path(['manage', 'recipe']))

        elif is_import:
            result = recipe_entity.Recipe()
            import_file = request.files.get('import-file')
            if not import_file:
                hint_text = _('Please select an import file.')
                self.hints.append(hint.Hint(hint_text))
            else:
                with zipfile.ZipFile(import_file.file) as zip:
                    json_bytes = zip.read(recipe_json)
                    recipe_dict = json.loads(json_bytes.decode('utf-8'))

                    synonyms = []
                    for synonym_name in recipe_dict['synonyms']:
                        synonym = synonym_entity.Synonym(name=synonym_name)
                        synonyms.append(synonym)

                    urls = []
                    for url_dict in recipe_dict['urls']:
                        u = url_entity.Url(name=url_dict['name'],
                                           url=url_dict['url'])
                        urls.append(u)

                    self.__create_img_dir(static_path, image_path)
                    images = []
                    for image_name in recipe_dict['images']:
                        # Check file extension.
                        name, extension = os.path.splitext(image_name)
                        if self.__check_img_extension(extension, language):
                            # Save image.
                            path = self.__get_image_path(
                                static_path, image_path, name, extension)
                            image = self.__save_image(static_path, path,
                                                      zip.read(image_name))
                            images.append(image)

                    result.description = recipe_dict['description']
                    result.images = images
                    result.info = recipe_dict['info']
                    result.ingredients = recipe_dict['ingredients']
                    result.serving_size = recipe_dict['serving_size']
                    result.synonyms = synonyms
                    result.title = recipe_dict['title']
                    result.urls = urls

                result = self.__finalize_recipe(result, True, indexer)

        elif is_new:
            result = recipe_entity.Recipe()

        else:
            result = recipe_entity.Recipe.find_pk(self.db, id)

        self.__show_hints(language)
        return result