Esempio n. 1
0
        def login(self):
            """ Login page """

            self._login_enabled()
            logout_user()
            self.tmp_data = None
            self.meta_tags(title="Login")

            if request.method == "POST":
                email = request.form.get("email").strip()
                password = request.form.get("password").strip()

                if not email or not password:
                    flash("Email or Password is empty", "error")
                    return redirect(url_for(login_view, next=request.form.get("next")))

                user = User.get_by_email(email)
                if user and user.password_hash and user.password_matched(password):
                    self.login_user(user)
                    return redirect(request.form.get("next") or url_for(on_signin_view))
                else:
                    flash("Email or Password is invalid", "error")
                    return redirect(url_for(login_view, next=request.form.get("next")))

            return dict(login_url_next=request.args.get("next", ""),
                        login_url_default=url_for(on_signin_view),
                        signup_enabled=self._package_conf.get("enable_signup"),
                        oauth_enabled=self._package_conf.get("enable_oauth_login"))
Esempio n. 2
0
        def setup_login(self):
            """
            Allows to setup a email password if it's not provided specially
            coming from oauth-login
            :return:
            """
            self._login_enabled()
            self.meta_tags(title="Setup  Login")

            # Only user without email can set email
            if current_user.is_authenticated() and current_user.email:
                return redirect(url_for(endpoint_namespace % "account_settings"))

            if self.tmp_data:
                if request.method == "POST":
                    if not self.tmp_data["is_oauth"]:
                        return redirect(endpoint_namespace % "login")

                    try:
                        email = request.form.get("email")
                        password = request.form.get("password")
                        password2 = request.form.get("password2")

                        if not utils.is_valid_email(email):
                            raise UserError("Invalid email address '%s'" % email)
                        elif User.get_by_email(email):
                            raise UserError("An account exists already with this email address '%s' " % email)
                        elif not password.strip() or password.strip() != password2.strip():
                            raise UserError("Passwords don't match")
                        elif not utils.is_valid_password(password):
                            raise UserError("Invalid password")
                        else:
                            user = User.new(email=email,
                                            password=password.strip(),
                                            name=self.tmp_data["name"],
                                            profile_image_url=self.tmp_data["picture"],
                                            signup_method=self.tmp_data["provider"])

                            user.add_oauth(self.tmp_data["provider"],
                                           self.tmp_data["id"],
                                           name=self.tmp_data["name"],
                                           email=email,
                                           profile_image_url=self.tmp_data["picture"],
                                           link=self.tmp_data["link"])

                            self.login_user(user)
                            self.tmp_data = None

                        return redirect(request.form.get("next") or url_for(on_signin_view))
                    except ApplicationError as ex:
                        flash(ex.message, "error")
                        return redirect(url_for(endpoint_namespace % "login"))

                return dict(provider=self.tmp_data)

            else:
                return redirect(url_for(endpoint_namespace % "login"))
Esempio n. 3
0
        def lost_password(self):
            self._login_enabled()
            logout_user()

            self.meta_tags(title="Lost Password")

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

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

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

                    flash("A new password has been sent to '%s'" % email, "success")
                else:
                    flash("Invalid email address", "error")
                return redirect(url_for(login_view))
            else:
                return {}
Esempio n. 4
0
        def publisher_admin_images(self):
            self.meta_tags(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("Image deleted successfully!", "success")
                        else:
                            image.update(description=description)
                            flash("Image updated successfully!", "success")
                else:
                    abort(404, "No image ID provided")
                return redirect(url_for("PublisherAdmin:images"))

            else:
                page = request.args.get("page", 1)
                per_page = self.get_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 dict(images=images)
Esempio n. 5
0
 def publisher_admin_types(self):
     self.meta_tags(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("New type '%s' added" % name, "success")
             else:
                 post_type = PostModel.Type.get(id)
                 if post_type:
                     if action == "delete":
                         post_type.delete()
                         flash("Type '%s' deleted successfully!" % post_type.name, "success")
                     else:
                         post_type.update(name=name, slug=slug)
                         flash("Type '%s' updated successfully!" % post_type.name, "success")
         except Exception as ex:
             flash("Error: %s" % ex.message, "error")
         return redirect(url_for("PublisherAdmin:types"))
     else:
         types = PostModel.Type.all().order_by(PostModel.Type.name.asc())
         return dict(types=types)
Esempio n. 6
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 UserError("Invalid User")

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

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

                flash("Password Reset instruction is sent to email", "success")
            except ApplicationError as ex:
                flash("Error: %s " % ex.message, "error")
            return redirect(url_for("UserAdmin:get", id=id))
Esempio n. 7
0
        def signup(self):
            """
            For Email Signup
            :return:
            """
            self._login_enabled()
            self._signup_enabled()
            self.meta_tags(title="Signup")

            if request.method == "POST":
                # reCaptcha
                if not recaptcha.verify():
                    flash("Invalid Security code", "error")
                    return redirect(url_for(endpoint_namespace % "signup",
                                            next=request.form.get("next")))
                try:
                    name = request.form.get("name")
                    email = request.form.get("email")
                    password = request.form.get("password")
                    password2 = request.form.get("password2")
                    profile_image_url = request.form.get("profile_image_url", None)

                    if not name:
                        raise UserError("Name is required")
                    elif not utils.is_valid_email(email):
                        raise UserError("Invalid email address '%s'" % email)
                    elif not password.strip() or password.strip() != password2.strip():
                        raise UserError("Passwords don't match")
                    elif not utils.is_valid_password(password):
                        raise UserError("Invalid password")
                    else:
                        new_account = User.new(email=email,
                                        password=password.strip(),
                                        first_name=name,
                                        profile_image_url=profile_image_url,
                                        signup_method="email")

                        self.login_user(new_account)
                        return redirect(request.form.get("next") or url_for(on_signin_view))
                except ApplicationError as ex:
                    flash(ex.message, "error")
                return redirect(url_for(endpoint_namespace % "signup",
                                        next=request.form.get("next")))

            logout_user()
            return dict(login_url_next=request.args.get("next", ""))
Esempio n. 8
0
        def user_admin_roles(self):
            """
            Only admin and super admin can add/remove roles
            RESTRICTED ROLES CAN'T BE CHANGED
            """
            roles_max_range = 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 UserError("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("Role '%s' deleted successfully!" % role.name, "success")
                                    elif action == "update":
                                        if role.level != level and Role.get_by_level(level):
                                            raise UserError("Role Level '%s' exists already" % level)
                                        elif role.name != name and Role.get_by_name(name):
                                            raise UserError("Role Name '%s'  exists already" % name)
                                        else:
                                            role.update(name=name, level=level)
                                            flash("Role '%s (%s)' updated successfully" % (name, level), "success")
                                else:
                                    raise UserError("Role doesn't exist")
                            else:
                                if Role.get_by_level(level):
                                    raise UserError("Role Level '%s' exists already" % level)
                                elif Role.get_by_name(name):
                                    raise UserError("Role Name '%s'  exists already" % name)
                                else:
                                    Role.new(name=name, level=level)
                                    flash("New Role '%s (%s)' addedd successfully" % (name, level), "success")
                except ApplicationError as ex:
                    flash("Error: %s" % ex.message, "error")
                return redirect(url_for("UserAdmin:roles"))
            else:
                self.meta_tags(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_max_range) if l not in allocated_levels]

                return dict(roles=roles,
                            levels_options=levels_options)
Esempio n. 9
0
        def account_settings(self):
            self.meta_tags(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("Account info updated successfully!", "success")
                    #
                    elif action == "login":
                        confirm_password = request.form.get("confirm-password").strip()
                        if current_user.password_matched(confirm_password):
                            self.change_login_handler()
                            flash("Login Info updated successfully!", "success")
                        else:
                            flash("Invalid password", "error")
                    #
                    elif action == "password":
                        confirm_password = request.form.get("confirm-password").strip()
                        if current_user.password_matched(confirm_password):
                            self.change_password_handler()
                            flash("Password updated successfully!", "success")
                        else:
                            flash("Invalid password", "error")

                    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("Profile Image updated successfully!", "success")
                    else:
                        raise UserError("Invalid action")

                except Exception as e:
                    flash(e.message, "error")

                return redirect(url_for(endpoint_namespace % "account_settings"))

            return {}
Esempio n. 10
0
        def reset_password(self, token):
            self._login_enabled()
            logout_user()

            self.meta_tags(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("Password updated successfully!", "success")
                        return redirect(url_for(on_signin_view))
                    except Exception as ex:
                        flash("Error: %s" % ex.message, "error")
                        return redirect(url_for(endpoint_namespace % "reset_password",
                                                token=token))
                else:
                    return dict(token=token)
            else:
                abort(404, "Invalid token")
Esempio n. 11
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 UserError("Invalid role")

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

                if not first_name:
                    raise UserError("First Name is required")
                elif not email:
                    raise UserError("Email is required")
                elif not utils.is_valid_email(email):
                    raise UserError("Invalid email address")
                if User.get_by_email(email):
                    raise UserError("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("User created successfully!", "success")
                        return redirect(url_for("UserAdmin:get", id=user.id))
                    else:
                        raise UserError("Couldn't create new user")
            except ApplicationError as ex:
                flash("Error: %s" % ex.message, "error")
            return redirect(url_for("UserAdmin:index"))
Esempio n. 12
0
    def upload(self):

        self.meta_tags(title="Upload Demo")

        if request.method == "POST":
            try:
                _file = request.files.get('file')
                if _file:
                    my_object = storage.upload(_file,
                                               prefix="demo/",
                                               public=True,
                                               allowed_extensions=["gif", "jpg", "jpeg", "png"])
                    if my_object:
                        return redirect(url_for("Account:upload", object_name=my_object.name))
            except Exception as e:
                flash_error(e.message)
            return redirect(url_for("Account:upload"))

        my_object = None
        object_name = request.args.get("object_name")
        if object_name:
            my_object = storage.get(object_name=object_name)

        return {"my_object": my_object}
Esempio n. 13
0
        def oauth_connect(self):
            """ To login via social """
            email = request.form.get("email").strip()
            name = request.form.get("name").strip()
            provider = request.form.get("provider").strip()
            provider_user_id = request.form.get("provider_user_id").strip()
            image_url = request.form.get("image_url").strip()
            next = request.form.get("next", "")
            try:
                current_user.oauth_connect(provider=provider,
                                         provider_user_id=provider_user_id,
                                         email=email,
                                         name=name,
                                         image_url=image_url)
            except Exception as ex:
                flash("Unable to link your account", "error")

            return redirect(url_for(endpoint_namespace % "account_settings"))
Esempio n. 14
0
        def publisher_admin_tags(self):
            self.meta_tags(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("New Tag '%s' added" % name, "success")
                    else:
                        post_tag = PostModel.Tag.get(id)
                        if post_tag:
                            if action == "delete":
                                post_tag.delete()
                                flash("Tag '%s' deleted successfully!" % post_tag.name, "success")
                            else:
                                post_tag.update(name=name, slug=slug)
                                flash("Tag '%s' updated successfully!" % post_tag.name, "success")
                except Exception as ex:
                    if ajax:
                        return jsonify({
                            "error": True,
                            "error_message": ex.message
                        })

                    flash("Error: %s" % ex.message, "error")
                return redirect(url_for("PublisherAdmin:tags"))

            else:
                tags = PostModel.Tag.all().order_by(PostModel.Tag.name.asc())
                return dict(tags=tags)
Esempio n. 15
0
        def publisher_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="publisher-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("Image '%s' uploaded successfully!" % upload_object.name, "success")
                else:
                    flash("Error: Upload object file is invalid or doesn't exist", "error")
            except Exception as e:
                flash("Error: %s" % e.message, "error")
            return redirect(url_for("PublisherAdmin:images"))
Esempio n. 16
0
        def publisher_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("Post Title is missing ", "error")
                if not type_id:
                    flash("Post type is missing", "error")

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

                if id:
                    url = url_for("PublisherAdmin:edit", id=id, error=1)
                else:
                    url = url_for("PublisherAdmin: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("Post deleted successfully!", "success")
                    return redirect(url_for("PublisherAdmin: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("Post saved successfully!", "success")

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

            else:
                abort(400, "Invalid post status")
Esempio n. 17
0
 def logout(self):
     logout_user()
     return redirect(url_for(on_signout_view or login_view))
Esempio n. 18
0
        def user_admin_post(self):
            try:
                id = request.form.get("id")
                user = User.get(id, include_deleted=True)
                if not user:
                    flash("Can't change user info. Invalid user", "error")
                    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 UserError("Invalid role")

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

                    if action == "activate":
                        user.update(active=True)
                        flash("User has been ACTIVATED", "success")
                    elif action == "deactivate":
                        user.update(active=False)
                        flash("User is now DEACTIVATED", "success")
                    elif action == "delete":
                        user.delete()
                        flash("User has been deleted", "success")
                    elif action == "undelete":
                        user.delete(False)
                        flash("User is now active", "success")
                    else:
                        if email and email != user.email:
                            if not utils.is_valid_email(email):
                                raise UserError("Invalid email address '%s'" % email)
                            else:
                                if User.get_by_email(email):
                                    raise UserError("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 UserError("Invalid email address '%s'" % email)
                        else:
                            if User.get_by_email(email):
                                raise UserError("Email exists already '%s'" % email)
                            user.update(email=email)
                    user.update(first_name=first_name,
                                last_name=last_name)

                    flash("User's Info updated successfully!", "success")
            except ApplicationError as ex:
                flash("Error: %s " % ex.message, "error")
            return redirect(url_for("UserAdmin:get", id=id))