Example #1
0
    def execute_logout_others(self, request):
        request.user.token = "".join(random.choice(string.letters) for i in xrange(32))
        db.flush()

        response = redirect(request.referrer or "/")
        response.set_cookie("u", request.user.token, expires=datetime.now() + timedelta(days=365))
        return response
Example #2
0
 def execute_set_default_identity(self, request):
     target_identity_id = int(request.form["id"])
     for identity in request.user.identities:
         if identity.id == target_identity_id:
             request.user.default_identity = identity
             db.flush()
             break
     return redirect("/authorization/usercp/")
Example #3
0
    def set(self, directory, key, value):
        kv = db.query(KV).filter_by(directory=directory, key=key).first()
        if kv is None:
            kv = KV()
            kv.directory = directory
            kv.key = key
            db.add(kv)

        kv.value = value
        db.flush()
Example #4
0
    def execute_admin_new(self, request, type):
        c = ContentItem()
        c.type = type
        c.type_key = str(int(time.time()))
        c.created_at = datetime.now()
        c.permissions = ContentItem.permissions_NOT_READY
        c.data = self.types[c.type]["type"].get_editor().new_db()
        db.add(c)
        db.flush()

        return redirect("/admin/content/edit/%d/" % c.id)
Example #5
0
    def execute_save_settings(self, request):
        if request.user.settings is None:
            request.user.settings = {}
        for setting in all_settings:
            if setting.is_available(request.user):
                request.user.settings[setting.get_id()] = setting.accept_value(request.form)

        s = request.user.settings
        request.user.settings = None
        db.flush()
        request.user.settings = s
        db.flush()

        return redirect("/authorization/usercp/")
Example #6
0
    def execute_post_comment(self, request, **kwargs):
        content_item = db.query(ContentItem).get(kwargs["id"])
        if request.form["email"] == "" and request.form["text"].strip() != "":
            comment = Comment()
            if request.user:
                comment.identity_id = request.user.default_identity.id
            comment.text = request.form["text"]
            comment.analytics = {
                "ip" : request.remote_addr
            }
            content_item.comments.append(comment)
            db.flush()

        return redirect(self._item_dict(content_item)["url"] + "#last-comment")
Example #7
0
    def execute_edit_comment(self, request, **kwargs):
        comment = db.query(Comment).get(kwargs["id"])
        if request.user and request.user.id == comment.identity.user.id:
            if db.query(Comment).filter(Comment.content_item_id == comment.content_item_id, Comment.created_at > comment.created_at).count() > 0:
                response = {"error" : u"К сожалению, пока вы редактировали комментарий, его успели увидеть другие пользователи. Обновите страницу, чтобы увидеть их реакцию на ваш позор."}
            else:
                if (request.form["text"].strip() == ""):
                    db.delete(comment)
                    response = {"deleted" : True}
                else:
                    comment.text = request.form["text"]
                    response = {"text" : self._process_comment_text(comment.text)}
                db.flush()

            return Response(simplejson.dumps(response), mimetype="application/json")

        raise Forbidden()
Example #8
0
def middleware(request):
    request.user = None
    if "u" in request.cookies:
        request.user = db.query(User).filter(User.token == request.cookies["u"]).first()
        if request.user:
            if datetime.now() > request.user.last_activity + config.user_inactivity_till_leave:
                request.user.last_visit = request.user.last_activity
            request.user.last_activity = datetime.now()
            db.flush()

    request.anonymous = None
    if request.remote_addr != "127.0.0.1":
        if request.user is None:
            if "a" in request.cookies:
                request.anonymous = db.query(Anonymous).filter(Anonymous.token == request.cookies["a"]).first()

            if request.anonymous is None:
                request.anonymous = Anonymous()
                request.anonymous.token = "".join(random.choice(string.letters + string.digits + string.punctuation)
                                                  for i in xrange(32))
                db.add(request.anonymous)
                db.flush()

            if request.remote_addr not in request.anonymous.ip_addresses:
                request.anonymous.ip_addresses = {a: True for a in request.anonymous.ip_addresses.keys()}
                request.anonymous.ip_addresses[request.remote_addr] = True
                db.flush()

    return request
Example #9
0
    def execute_admin_edit(self, request, id):
        c = db.query(ContentItem).get(id)
        if c is None:
            raise NotFound()

        editor = self.types[c.type]["type"].get_editor()

        if request.method == "POST":
            c.type_key = request.form["type_key"]
            c.started_at = dateutil.parser.parse(request.form["started_at"]) if request.form.get("started_at", "").strip() else None
            c.created_at = dateutil.parser.parse(request.form["created_at"])
            c.permissions = ContentItem.permissions_PUBLIC if "public" in request.form else ContentItem.permissions_NOT_READY

            c.tags = []
            for tag in request.form["tags"].split(","):
                tag = tag.strip()
                db_tag = db.query(Tag).filter(Tag.title == tag).first()
                if db_tag is None:
                    db_tag = Tag()
                    db_tag.url = tag.split(":", 2)[0] if ":" in tag else tag
                    db_tag.title = tag.split(":", 2)[1] if ":" in tag else tag
                    db.add(db_tag)
                    db.flush()
                c.tags.append(db_tag)

            data = editor.form_to_db(request, c.data)
            c.data = None
            db.flush()
            c.data = data
            db.flush()

            cache.get_cache("content_item_%d" % c.id).remove_value(key="formatter_output")

            return redirect(request.path)
        else:
            form = editor.db_to_form(c.data)

            return self.render_to_response(request, [
                "content/type/%s/edit.html" % (c.type,),
                "content/type/%s/edit.html" % (self._base_type(c.type),),
            ], **{
                "breadcrumbs"       :   [u"Редактирование %s" % self.types[c.type]["type"].item_cases[1]],

                "form"              :   form,
                "content_item"      :   c,
                "tags"              :   u",".join([t.title for t in c.tags]),
            })
Example #10
0
            id = str(item.id)
            item_ids.append(id)

            content_item = db.query(ContentItem).filter_by(type=type, type_key=id).first()
            if content_item is None:
                content_item = ContentItem()
                content_item.type = type
                content_item.type_key = id
                content_item.started_at = item.started_at
                content_item.created_at = item.created_at
                content_item.permissions = content_types[type].get("permissions", 0)
                content_item.data = item.data

                for kv_directory in item.kv:
                    kv = item.kv[kv_directory]
                    for k, v in kv() if callable(kv) else kv:
                        if k not in kv_storage[kv_directory]:
                            kv_storage[kv_directory][k] = v() if callable(v) else v

                db.add(content_item)
                db.flush()

                provider.on_item_inserted(content_item)
        db.flush()

        for content_item in db.query(ContentItem).filter(ContentItem.type == type, ContentItem.permissions != ContentItem.permissions_DELETED).order_by(ContentItem.created_at.desc())[:len(item_ids)]:
            if content_item.type_key not in item_ids and provider.is_not_actual_item(content_item):
                content_item.permissions = ContentItem.permissions_DELETED
    
        db.flush()
Example #11
0
    def execute_callback(self, request, **kwargs):
        result = self.services[kwargs["service"]].oauth_callback(request)
        if result:
            identity = db.query(Identity).filter(Identity.service == kwargs["service"], Identity.service_id == result[0]).first()
            if identity is None:
                identity = Identity()
                identity.service = kwargs["service"]
                identity.service_id = result[0]
                identity.service_data = result[1]
                db.add(identity)
                db.flush()
            else:
                identity.service_data = result[1]
                db.flush()
            if not identity.trusted and (identity.trust_last_checked is None or
                    identity.trust_last_checked < datetime.now() - timedelta(minutes=10)):
                service = self.services[kwargs["service"]]
                identity.trusted = hasattr(service, "is_trusted") and service.is_trusted(identity.service_data)
                identity.trust_last_checked = datetime.now()
                db.flush()
            if identity.user is None:
                if request.user is None:
                    identity.user = User()
                    identity.user.default_identity_id = identity.id # identity.user.default_identity = identity causes CircularDependencyError
                    identity.user.token = "".join(random.choice(string.letters + string.digits + string.punctuation)
                                                  for i in xrange(32))
                    identity.user.url_token = "".join(random.choice(string.letters + string.digits + string.punctuation)
                                                      for i in xrange(32))
                    identity.user.settings = {}
                    db.add(identity.user)
                    db.flush()
                else:
                    identity.user = request.user
                    db.flush()
            else:
                if request.user is not None and request.user is not identity.user:
                    for other_identity in request.user.identities:
                        other_identity.user = identity.user
                    db.delete(request.user)
                    db.flush()

            response = redirect(request.args.get("from", "/"))
            response.set_cookie("u", identity.user.token, expires=datetime.now() + timedelta(days=365))
            return response
        else:
            raise Unauthorized()
Example #12
0
 def delete(self, directory, key):
     kv = db.query(KV).filter_by(directory=directory, key=key).first()
     if kv is None:
         raise KeyError
     db.delete(kv)
     db.flush()
Example #13
0
    def process_request(self, request):
        for middleware in all_middleware:
            request = middleware(request)

        if (request.user is not None and
            request.user.permissions == 0 and
            request.user.trusted and            
            any(request.environ["PATH_INFO"].startswith(p)
                for p in ("/blog/post/", "/gallery/view/", "/video/view/",
                          "/chatlogs/view/", "/library/view/", "/shop/view/"))):
            return redirect(self._encrypt_url(request.user.url_token, request.environ["PATH_INFO"]))

        if request.environ["PATH_INFO"].startswith("/private/"):
            path_info = request.environ["PATH_INFO"]
            path_info = path_info[len("/private/"):]
            url = db.query(Url).filter(Url.encrypted_url == path_info).first()
            if request.user is not None and request.user.trusted:
                if url is not None and url.user != request.user:
                    return redirect(self._encrypt_url(request.user.url_token, url.decrypted_url))

                path_info_encrypted = path_info
                path_info = AES.new(request.user.url_token).decrypt(unhexlify(path_info)).rstrip("@")

                url = db.query(Url).filter(Url.encrypted_url == path_info_encrypted).first()
                if url is None:
                    url = Url()
                    url.encrypted_url = path_info_encrypted
                    url.decrypted_url = path_info
                    url.user = request.user
                    db.add(url)
            else:
                if url is None:
                    raise Forbidden()
                if not any(url.decrypted_url.startswith(p)
                           for p in ("/blog/post/", "/gallery/view/", "/video/view/",
                                     "/chatlogs/view/", "/library/view/", "/shop/view/")):
                    raise Forbidden()

                auv = db.query(AnonymousUrlView).filter(AnonymousUrlView.anonymous == request.anonymous,
                                                        AnonymousUrlView.url == url).first()
                if auv is None:
                    auv = AnonymousUrlView()
                    auv.anonymous = request.anonymous
                    auv.url = url
                    db.add(auv)
                    db.flush()

                path_info = url.decrypted_url

            request.environ["PATH_INFO"] = path_info

            request = Request(request.environ)

            local.request = request

            for middleware in all_middleware:
                request = middleware(request)
        else:
            if request.user is None or not request.user.trusted:
                if not (request.host.startswith("i.") or
                        request.remote_addr == "127.0.0.1" or
                        any(request.environ["PATH_INFO"].startswith(p)
                            for p in ("/authorization/", "/content/post-comment/"))):
                    raise Forbidden()

        endpoint, values = self.url_map.bind_to_environ(request.environ, server_name=urlparse(config.url).netloc.split(":")[0]).match()
        controller, controller_endpoint = endpoint.split("/", 1)

        controller = self.controllers[int(controller)]
        controller_method = "execute_{0}".format(controller_endpoint)

        response = getattr(controller, controller_method)(request, **values)

        if request.anonymous is not None:
            response.set_cookie("a", request.anonymous.token, expires=datetime.now() + timedelta(days=365))

        if request.user is not None and request.user.permissions == 0:
            if isinstance(response.data, str):
                response.data = re.sub('(data-url|href)="(.+?)"',
                                       partial(self._hide_url_callback, request.user.url_token),
                                       response.data)

            if "Location" in response.headers:
                response.headers["Location"] = self._encrypt_url(request.user.url_token,
                                                                 response.headers["Location"])

        if request.anonymous:
            if "Location" in response.headers:
                parts = self._encrypt_url_parts(response.headers["Location"])
                if parts:
                    url_prefix, url, anchor = parts
                    url_view = db.query(AnonymousUrlView).\
                                  join(Url).\
                                  filter(AnonymousUrlView.anonymous == request.anonymous,
                                         Url.decrypted_url == url).\
                                  first()
                    if url_view:
                        response.headers["Location"] = self._build_url(url_prefix, url_view.url.encrypted_url, anchor)


        return response