Exemplo n.º 1
0
        def lost_password(self):
            self._login_enabled()
            logout_user()

            self.meta_(title="Lost Password")

            if request.method == "POST":
                email = request.form.get("email")
                user = User.get_by_email(email)
                if user:
                    delivery = self.config_("MODULE_USER_ACCOUNT_RESET_PASSWORD_METHOD")

                    new_password = None
                    if delivery.upper() == "TOKEN":
                        token = user.set_temp_login()
                        url = url_for("UserAccount:reset_password", token=token, _external=True)
                    else:
                        new_password = user.set_password(password=None, random=True)
                        url = url_for("UserAccount:login", _external=True)

                    mailer.send_template(
                        "reset-password.txt",
                        method_=delivery,
                        to=user.email,
                        name=user.email,
                        url=url,
                        new_password=new_password,
                    )

                    flash_success("A new password has been sent to '%s'" % email)
                else:
                    flash_error("Invalid email address")
                return redirect(url_for(login_view))
            else:
                return self.render_(view_template_=template_page % "lost_password")
Exemplo n.º 2
0
        def cms_admin_images(self):
            self.meta_(title="Images")
            if request.method == "POST":
                id = request.form.get("id", None)
                action = request.form.get("action")
                description = request.form.get("description")
                if id:
                    image = PostModel.UploadObject.get(id)
                    if image:
                        if action == "delete":
                            image.delete()
                            obj = storage.get(image.name)
                            if obj:
                                obj.delete()
                            flash_success("Image deleted successfully!")
                        else:
                            image.update(description=description)
                            flash_success("Image updated successfully!")
                else:
                    abort(404, "No image ID provided")
                return redirect(url_for("CmsAdmin:images"))

            else:
                page = request.args.get("page", 1)
                per_page = self.config_("PAGINATION_PER_PAGE", 25)
                images = PostModel.UploadObject.all()\
                    .filter(PostModel.UploadObject.type == "IMAGE")\
                    .order_by(PostModel.UploadObject.name.asc())
                images = images.paginate(page=page, per_page=per_page)
                return self.render_(images=images,
                                   view_template_=template_page % "images")
Exemplo n.º 3
0
        def user_admin_reset_password(self):
            """
            Reset the password
            :returns string: The new password string
            """
            try:
                id = request.form.get("id")
                user = User.get(id)
                if not user:
                    raise ViewError("Invalid User")

                method_ = self.config_("LOGIN_RESET_PASSWORD_METHOD", "").upper()
                new_password = None
                if method_ == "TOKEN":
                    token = user.set_temp_login()
                    url = url_for("UserAccount:temp_login_token", token=token, _external=True)
                else:
                    new_password = user.set_password(password=None, random=True)
                    url = url_for("UserAccount:login", _external=True)

                mailer.send_template(
                    "reset-password.txt",
                    method_=method_,
                    to=user.email,
                    name=user.email,
                    url=url,
                    new_password=new_password,
                )

                flash_success("Password Reset instruction is sent to email")
            except Exception as ex:
                flash_error("Error: %s " % ex.message)
            return redirect(url_for("UserAdmin:get", id=id))
Exemplo n.º 4
0
        def cms_admin_upload_image(self):
            """
            Placeholder for markdown
            """
            try:
                ajax = request.form.get("ajax", False)
                allowed_extensions = ["gif", "png", "jpg", "jpeg"]

                if request.files.get("file"):
                    _file = request.files.get('file')
                    obj = storage.upload(_file,
                                         prefix="cms-uploads/",
                                         allowed_extensions=allowed_extensions,
                                         public=True)

                    if obj:
                        description = os.path.basename(obj.name)
                        description = description.replace(".%s" % obj.extension, "")
                        description = description.split("__")[0]
                        upload_object = PostModel.UploadObject.create(name=obj.name,
                                                                      provider=obj.provider_name,
                                                                      container=obj.container.name,
                                                                      extension=obj.extension,
                                                                      type=obj.type,
                                                                      object_path=obj.path,
                                                                      object_url=obj.url,
                                                                      size=obj.size,
                                                                      description=description)
                        if ajax:
                            return jsonify({
                                "id": upload_object.id,
                                "url": upload_object.object_url
                            })
                        else:
                            flash_success("Image '%s' uploaded successfully!" % upload_object.name)

                else:
                    flash_error("Error: Upload object file is invalid or doesn't exist")
            except Exception as e:
                flash_error("Error: %s" % e.message)
            return redirect(url_for("CmsAdmin:images"))
Exemplo n.º 5
0
        def account_settings(self):
            self.meta_(title="Account Settings")

            if request.method == "POST":
                action = request.form.get("action")
                try:
                    action = action.lower()
                    #
                    if action == "info":
                        first_name = request.form.get("first_name").strip()
                        last_name = request.form.get("last_name", "").strip()

                        data = {"first_name": first_name, "last_name": last_name}
                        current_user.update(**data)
                        flash_success("Account info updated successfully!")
                    #
                    elif action == "login":
                        confirm_password = request.form.get("confirm-password").strip()
                        if current_user.password_matched(confirm_password):
                            self.change_login_handler()
                            flash_success("Login Info updated successfully!")
                        else:
                            flash_error("Invalid password")
                    #
                    elif action == "password":
                        confirm_password = request.form.get("confirm-password").strip()
                        if current_user.password_matched(confirm_password):
                            self.change_password_handler()
                            flash_success("Password updated successfully!")
                        else:
                            flash_error("Invalid password")

                    elif action == "profile-photo":
                        file = request.files.get("file")
                        if file:
                            prefix = "profile-photos/%s/" % current_user.id
                            extensions = ["jpg", "jpeg", "png", "gif"]
                            my_photo = storage.upload(file, prefix=prefix, allowed_extensions=extensions)
                            if my_photo:
                                url = my_photo.url
                                current_user.update(profile_image_url=url)
                                flash_success("Profile Image updated successfully!")
                    else:
                        raise ViewError("Invalid action")

                except Exception as e:
                    flash_error(e.message)

                return redirect(url_for("UserAccount:account_settings"))

            return self.render_(view_template_=template_page % "account_settings")
Exemplo n.º 6
0
 def cms_admin_types(self):
     self.meta_(title="Post Types")
     if request.method == "POST":
         try:
             id = request.form.get("id", None)
             action = request.form.get("action")
             name = request.form.get("name")
             slug = request.form.get("slug", None)
             if not id:
                 PostModel.Type.new(name=name, slug=slug)
                 flash_success("New type '%s' added" % name)
             else:
                 post_type = PostModel.Type.get(id)
                 if post_type:
                     if action == "delete":
                         post_type.delete()
                         flash_success("Type '%s' deleted successfully!" % post_type.name)
                     else:
                         post_type.update(name=name, slug=slug)
                         flash_success("Type '%s' updated successfully!" % post_type.name)
         except Exception as ex:
             flash_error("Error: %s" % ex.message)
         return redirect(url_for("CmsAdmin:types"))
     else:
         types = PostModel.Type.all().order_by(PostModel.Type.name.asc())
         return self.render_(types=types,
                            view_template_=template_page % "types")
Exemplo n.º 7
0
        def reset_password(self, token):
            self._login_enabled()
            logout_user()

            self.meta_(title="Reset Password")
            user = User.get_by_temp_login(token)
            if user:
                if not user.has_temp_login:
                    return redirect(url_for(on_signin_view))
                if request.method == "POST":
                    try:
                        self.change_password_handler(user_context=user)
                        user.clear_temp_login()
                        flash_success("Password updated successfully!")
                        return redirect(url_for(on_signin_view))
                    except Exception as ex:
                        flash_error("Error: %s" % ex.message)
                        return redirect(url_for("UserAccount:reset_password", token=token))
                else:
                    return self.render_(token=token, view_template_=template_page % "reset_password")
            else:
                abort(404, "Invalid token")
Exemplo n.º 8
0
    def contact_page(self):

        if not self.config_("MAILER_URI") \
                or not self.config_("MODULE_CONTACT_PAGE_EMAIL"):
            abort(500, "Mailer Error. Invalid [ MAILER_URI ] "
                       "or [ MODULE_CONTACT_PAGE_EMAIL ] is missing or empty")

        contact_email = self.config_("MODULE_CONTACT_PAGE_EMAIL")

        if request.method == "POST":
            error_message = None
            email = request.form.get("email")
            subject = request.form.get("subject")
            message = request.form.get("message")
            name = request.form.get("name")

            if recaptcha.verify():
                if not email or not subject or not message:
                    error_message = "All fields are required"
                elif not utils.is_valid_email(email):
                    error_message = "Invalid email address"
                if error_message:
                    flash_error(error_message)
                else:
                    mailer.send_template("contact-us.txt",
                                         to=contact_email,
                                         reply_to=email,
                                         mail_from=email,
                                         mail_subject=subject,
                                         mail_message=message,
                                         mail_name=name)
                    flash_success("Message sent. Thank you!")
            else:
                flash_error("Security code is invalid")
            return redirect(url_for("ContactPage"))
        else:
            self.meta_(title="Contact Us")
            return dict(view_template_=template_page % "contact_page")
Exemplo n.º 9
0
        def user_admin_create(self):
            try:
                email = request.form.get("email")
                first_name = request.form.get("first_name")
                last_name = request.form.get("last_name")
                user_role = request.form.get("user_role")

                _role = Role.get(user_role)
                if not _role:
                    raise ViewError("Invalid role")

                if current_user.role.level < _role.level:
                    raise ViewError("Can't be assigned a greater user role")

                if not first_name:
                    raise ViewError("First Name is required")
                elif not email:
                    raise ViewError("Email is required")
                elif not utils.is_valid_email(email):
                    raise ViewError("Invalid email address")
                if User.get_by_email(email):
                    raise ViewError("Email '%s' exists already" % email)
                else:
                    user = User.new(
                        email=email,
                        first_name=first_name,
                        last_name=last_name,
                        signup_method="email-from-admin",
                        role_id=_role.id,
                    )
                    if user:
                        flash_success("User created successfully!")
                        return redirect(url_for("UserAdmin:get", id=user.id))
                    else:
                        raise ViewError("Couldn't create new user")
            except Exception as ex:
                flash_error("Error: %s" % ex.message)
            return redirect(url_for("UserAdmin:index"))
Exemplo n.º 10
0
        def user_admin_roles(self):
            """
            Only admin and super admin can add/remove roles
            RESTRICTED ROLES CAN'T BE CHANGED
            """
            roles_rage_max = 11
            if request.method == "POST":
                try:
                    id = request.form.get("id")
                    name = request.form.get("name")
                    level = request.form.get("level")
                    action = request.form.get("action")

                    if name and level:
                        level = int(level)
                        name = name.upper()
                        _levels = [r[0] for r in Role.PRIMARY]
                        _names = [r[1] for r in Role.PRIMARY]
                        if level in _levels or name in _names:
                            raise ViewError("Can't modify PRIMARY Roles - name: %s, level: %s " % (name, level))
                        else:
                            if id:
                                role = Role.get(id)
                                if role:
                                    if action == "delete":
                                        role.delete()
                                        flash_success("Role '%s' deleted successfully!" % role.name)
                                    elif action == "update":
                                        if role.level != level and Role.get_by_level(level):
                                            raise ViewError("Role Level '%s' exists already" % level)
                                        elif role.name != name and Role.get_by_name(name):
                                            raise ViewError("Role Name '%s'  exists already" % name)
                                        else:
                                            role.update(name=name, level=level)
                                            flash_success("Role '%s (%s)' updated successfully" % (name, level))
                                else:
                                    raise ViewError("Role doesn't exist")
                            else:
                                if Role.get_by_level(level):
                                    raise ViewError("Role Level '%s' exists already" % level)
                                elif Role.get_by_name(name):
                                    raise ViewError("Role Name '%s'  exists already" % name)
                                else:
                                    Role.new(name=name, level=level)
                                    flash_success("New Role '%s (%s)' addedd successfully" % (name, level))
                except Exception as ex:
                    flash_error("Error: %s" % ex.message)
                return redirect(url_for("UserAdmin:roles"))
            else:
                self.meta_(title="User Roles - Users Admin")
                roles = Role.all().order_by(Role.level.desc())

                allocated_levels = [r.level for r in roles]
                levels_options = [(l, l) for l in range(1, roles_rage_max) if l not in allocated_levels]

                return self.render_(roles=roles, levels_options=levels_options, view_template_=template_page % "roles")
Exemplo n.º 11
0
        def cms_admin_tags(self):
            self.meta_(title="Post Tags")
            if request.method == "POST":
                id = request.form.get("id", None)
                action = request.form.get("action")
                name = request.form.get("name")
                slug = request.form.get("slug", None)
                ajax = request.form.get("ajax", False)
                try:
                    if not id:
                        tag = PostModel.Tag.new(name=name, slug=slug)
                        if ajax:
                            return jsonify({
                                "id": tag.id,
                                "name": tag.name,
                                "slug": tag.slug,
                                "status": "OK"
                            })
                        flash_success("New Tag '%s' added" % name)
                    else:
                        post_tag = PostModel.Tag.get(id)
                        if post_tag:
                            if action == "delete":
                                post_tag.delete()
                                flash_success("Tag '%s' deleted successfully!" % post_tag.name)
                            else:
                                post_tag.update(name=name, slug=slug)
                                flash_success("Tag '%s' updated successfully!" % post_tag.name)
                except Exception as ex:
                    if ajax:
                        return jsonify({
                            "error": True,
                            "error_message": ex.message
                        })

                    flash_error("Error: %s" % ex.message)
                return redirect(url_for("CmsAdmin:tags"))

            else:
                tags = PostModel.Tag.all().order_by(PostModel.Tag.name.asc())
                return self.render_(tags=tags,
                                   view_template_=template_page % "tags")
Exemplo n.º 12
0
        def cms_admin_post(self):
            id = request.form.get("id")
            title = request.form.get("title")
            slug = request.form.get("slug")
            content = request.form.get("content")
            description = request.form.get("description")
            type_id = request.form.get("type_id")
            post_categories = request.form.getlist("post_categories")
            published_date = request.form.get("published_date")
            status = request.form.get("status", "draft")
            is_published = True if status == "publish" else False
            is_draft = True if status == "draft" else False
            is_public = True if request.form.get("is_public") == "y" else False
            is_sticky = True if request.form.get("is_sticky") == "y" else False
            is_featured = True if request.form.get("is_featured") == "y" else False
            featured_image = request.form.get("featured_image")
            featured_embed = request.form.get("featured_embed")
            featured_media_top = request.form.get("featured_media_top", "")
            social_options = request.form.getlist("social_options")
            tags = list(set(request.form.get("tags", "").split(",")))

            now_dt = datetime.datetime.now()
            data = {
                "title": title,
                "content": content,
                "description": description,
                "featured_image": featured_image,
                "featured_embed": featured_embed,
                "featured_media_top": featured_media_top,
                "type_id": type_id,
                "is_sticky": is_sticky,
                "is_featured": is_featured,
                "is_public": is_public
            }

            if status in ["draft", "publish"] and (not title or not type_id):
                if not title:
                    flash_error("Post Title is missing ")
                if not type_id:
                    flash_error("Post type is missing")

                data.update({
                    "published_date": published_date,
                    "post_categories": post_categories,
                    "options": {"social_options": social_options},
                })
                flash_data(data)

                if id:
                    url = url_for("CmsAdmin:edit", id=id, error=1)
                else:
                    url = url_for("CmsAdmin:new", error=1)
                return redirect(url)

            published_date = datetime.datetime.strptime(published_date, "%Y-%m-%d %H:%M:%S") \
                if published_date else now_dt

            if id and status in ["delete", "revision"]:
                post = PostModel.Post.get(id)
                if not post:
                    abort(404, "Post '%s' doesn't exist" % id)

                if status == "delete":
                    post.delete()
                    flash_success("Post deleted successfully!")
                    return redirect(url_for("CmsAdmin:index"))

                elif status == "revision":
                    data.update({
                        "user_id": current_user.id,
                        "parent_id": id,
                        "is_revision": True,
                        "is_draft": False,
                        "is_published": False,
                        "is_public": False
                    })
                    post = PostModel.Post.create(**data)
                    return jsonify({"revision_id": post.id})

            elif status in ["draft", "publish"]:
                data.update({
                    "is_published": is_published,
                    "is_draft": is_draft,
                    "is_revision": False,
                    "is_public": is_public
                })

                if id:
                    post = PostModel.Post.get(id)
                    if not post:
                        abort(404, "Post '%s' doesn't exist" % id)
                    elif post.is_revision:
                        abort(403, "Can't access this post")
                    else:
                        if is_sticky and not post.is_sticky:
                            data["sticky_at"] = now_dt
                        if is_featured and not post.is_featured:
                            data["featured_at"] = now_dt
                        post.update(**data)
                else:
                    data["user_id"] = current_user.id
                    if is_published:
                        data["published_at"] = published_date
                    if is_sticky:
                        data["sticky_at"] = now_dt
                    if is_featured:
                        data["featured_at"] = now_dt
                    post = PostModel.Post.create(**data)

                # prepare tags
                _tags = []
                for tag in tags:
                    tag = tag.strip().lower()
                    _tag = PostModel.Tag.get_by_slug(name=tag)
                    if tag and not _tag:
                        _tag = PostModel.Tag.new(name=tag)
                    if _tag:
                        _tags.append(_tag.id)
                post.update_tags(_tags)

                post.set_slug(slug or title)
                post.update_categories(map(int, post_categories))
                post.set_options("social", social_options)

                if post.is_published and not post.published_at:
                        post.update(published_at=published_date)

                flash_success("Post saved successfully!")

                return redirect(url_for("CmsAdmin:edit", id=post.id))

            else:
                abort(400, "Invalid post status")
Exemplo n.º 13
0
        def user_admin_post(self):
            try:
                id = request.form.get("id")
                user = User.get(id, include_deleted=True)
                if not user:
                    flash_error("Can't change user info. Invalid user")
                    return redirect(url_for("UserAdmin:index"))

                if current_user.role.level < user.role.level:
                    abort(403, "Not enough rights to update this user info")

                email = request.form.get("email", "").strip()
                first_name = request.form.get("first_name")
                last_name = request.form.get("last_name")
                user_role = request.form.get("user_role")
                action = request.form.get("action")

                if user.id != current_user.id:
                    _role = Role.get(user_role)
                    if not _role:
                        raise ViewError("Invalid role")

                    if current_user.role.name.lower() not in PRIVILEDGED_ROLES:
                        raise ViewError("Not Enough right to change user's info")

                    if action == "activate":
                        user.update(active=True)
                        flash_success("User has been ACTIVATED")
                    elif action == "deactivate":
                        user.update(active=False)
                        flash_success("User is now DEACTIVATED")
                    elif action == "delete":
                        user.delete()
                        flash_success("User has been deleted")
                    elif action == "undelete":
                        user.delete(False)
                        flash_success("User is now active")
                    else:
                        if email and email != user.email:
                            if not utils.is_valid_email(email):
                                raise ViewError("Invalid email address '%s'" % email)
                            else:
                                if User.get_by_email(email):
                                    raise ViewError("Email exists already '%s'" % email)
                                user.update(email=email)

                        user.update(first_name=first_name, last_name=last_name, role_id=_role.id)

                else:
                    if email and email != user.email:
                        if not utils.is_valid_email(email):
                            raise ViewError("Invalid email address '%s'" % email)
                        else:
                            if User.get_by_email(email):
                                raise ViewError("Email exists already '%s'" % email)
                            user.update(email=email)
                    user.update(first_name=first_name, last_name=last_name)

                    flash_success("User's Info updated successfully!")
            except Exception as ex:
                flash_error("Error: %s " % ex.message)
            return redirect(url_for("UserAdmin:get", id=id))