Ejemplo n.º 1
0
def login(request):
    body = TemplateIO(html=True)
    
    body += H('<h1>Imagestore Login</h1>')

    session = request.session

    if request.form:
        username = request.form.get('username')
        password = request.form.get('password')
        referer = request.form.get('referer')

        failed = False
        try:
            user = db.User.byUsername(username)

            if password == '':
                password = None

            if user.password != password:
                failed = True
        except SQLObjectNotFound, x:
            failed = True

        if failed:
            body += page.error(request, 'User unknown or password incorrect', 'Please try again.')
            body += user_page.login_form(request, username=username)
        else:
            body += H('<p>Hi, %s, you\'ve logged in' % user.fullname)
            session.setuser(user.id)
            if referer is not None and referer != '':
                ret = quixote.redirect(referer)
            else:
                ret = quixote.redirect(path(user))
            return ret
Ejemplo n.º 2
0
    def editdetails(self, request, p):
        form = form2.Form(name='editdetails')

        form.add(form2.StringWidget, name='title', size=50,
                 value=p.title or '', title='Title')
        form.add(form2.StringWidget, name='keywords', size=40,
                 value=', '.join([ k.word for k in p.keywords]),
                 title='Keywords')
        form.add(form2.StringWidget, name='description', size=50,
                 value=p.description, title='Description')
# FIXME form layout
#        form.add(form2.TextWidget, name='description', cols=50, rows=10,
#                 value=p.description, title='Description')

        form.add(form2.SingleSelectWidget, name='owner', value=p.ownerID, title='Picture owner',
                 options=imagestore.form.userOptList())
        form.add(form2.SingleSelectWidget, name='visibility',
                 value=p.visibility, title='Visibility',
                 options=[ s for s in ['public', 'restricted', 'private']])

        (prev,next) = request.session.get_results_neighbours(p.id)

        if next is not None:
            form.add_submit('submit-next', H('Update picture and go to next >>'))
        else:
            form.add_submit('submit', 'Update picture details')
        form.add_reset('reset', 'Revert changes')

        if not form.is_submitted() or form.has_errors():
            from image_page import detail_table
            
            self.image.set_prevnext(request, p.id,
                                    urlfn=lambda pic, size, s=self.image: s.edit.path(pic))
            
            ret = TemplateIO(html=True)
            
            ret += page.pre(request, 'Edit details', 'editdetails', trail=False)
            ret += page.menupane(request)
            ret += self.image.view_rotate_link(request, p, wantedit=True)
            ret += detail_table(p)
            ret += form.render()
            ret += page.post()

            ret = ret.getvalue()
        else:
            keywords = form['keywords']
            keywords = imagestore.form.splitKeywords(keywords)

            p.setKeywords(keywords)

            p.visibility = form['visibility']

            if form.get_submit() == 'submit-next' and next:
                ret = quixote.redirect(self.image.edit.path(db.Picture.get(next)))
            else:
                ret = quixote.redirect(request.get_path())

        return ret
Ejemplo n.º 3
0
    def delete_image(self):
        request = quixote.get_request()

        try:
            i = int(request.form['num'])
        except:
            i = -1

        image.delete_image(i)
        quixote.redirect("./")
Ejemplo n.º 4
0
def selector(songs):
    global player, song
    chosen = get_field("select")
    if chosen:
        song = chosen
        player = play(song)
        redirect("stopper") # works with Mozilla, but not with lynx/elinks
    else:
        f = Form()
        f.add_single_select("select", options=songs)
        f.add_submit("play", "Play!")
        return f.render()
Ejemplo n.º 5
0
 def loginsubmit(self):
     request = quixote.get_request()
     response = quixote.get_response()
     u = request.form['username']
     p = request.form['password']
     a = userDB.cursor()
     a.execute('SELECT username, password FROM users WHERE password = ? AND username = ?', (p, u))
     if a.fetchone():
     	response.set_cookie(str('user'+u), str(u), path='/')
     	return quixote.redirect('./')
     else:
     	print "LOGIN FAILED"
     	return quixote.redirect('./login')
Ejemplo n.º 6
0
    def formpostredirect(self):
        """
        Test redirect after a form POST.  This tests a specific bug in
        mechanize...
        """
        request = get_request()

        if not request.form:
            return """\
<form method=POST enctype=multipart/form-data>
<input type=text name=test>
<input type=submit value=submit name=submit>
</form>
"""
        redirect(get_path(1) + '/')
Ejemplo n.º 7
0
 def created(self):
     request = quixote.get_request()
     response = quixote.get_response()
     u = request.form['username']
     p = request.form['password']
     a = userDB.cursor()
     a.execute('SELECT username, password FROM users WHERE 1 = ? AND username = ?', (1, u))
     if a.fetchone():
     	print "CREATE FAILED"
     	return quixote.redirect('./create')
     else:
     	userDB.execute('INSERT INTO users (username, password) VALUES (?, ?)', (u, p))
     	userDB.commit()
     	response.set_cookie(str('user'+u), str(u), path='/')
     	return quixote.redirect('./')
Ejemplo n.º 8
0
    def formpostredirect(self):
        """
        Test redirect after a form POST.  This tests a specific bug in
        mechanize...
        """
        request = get_request()

        if not request.form:
            return """\
<form method=POST enctype=multipart/form-data>
<input type=text name=test>
<input type=submit value=submit name=submit>
</form>
"""
        redirect(get_path(1) + '/')
Ejemplo n.º 9
0
    def _q_index(self, request):
        sess_user = auth.login_user(quiet=True)

        if sess_user is None:
            return quixote.redirect(path(sess_user))

        return user_page.user_page(request)
Ejemplo n.º 10
0
    def handle(self):
        """handle() -> string

        Master method for handling forms.  It should be called after
        initializing a form.  Controls form action based on a request.  You
        probably should override 'process' and 'action' instead of
        overriding this method.
        """
        request = get_request()
        if not self.is_submitted():
            return self.render(self.action_url)
        submit = self.get_submit()
        if submit == "cancel":
            return redirect(self.cancel_url)
        values = self.process()
        if submit == True:
            # The form was submitted by an unregistered submit button, assume
            # that the submission was required to update the layout of the form.
            self.clear_errors()
            return self.render(self.action_url)

        if self.has_errors():
            return self.render(self.action_url)
        else:
            return self.action(submit, values)
Ejemplo n.º 11
0
    def login(self):
        request = get_request()

        username_widget = widget.StringWidget(name='username',
                                              value='')
        submit_widget = widget.SubmitWidget(name='submit',
                                            value='submit me')
        submit_widget2 = widget.SubmitWidget(name='nosubmit2',
                                             value="don't submit")
        
        if request.form:
            assert not submit_widget2.parse(request)
            username = username_widget.parse(request)
            if username:
                session = get_session()
                session.set_user(username)
                return redirect('./')

        image_submit = '''<input type=image name='submit you' src=DNE.gif>'''
                
        return "<form method=POST>Log in: %s<p>%s<p>%s<p>%s</form>" % \
               (username_widget.render(),
                submit_widget2.render(),
                submit_widget.render(),
                image_submit)
Ejemplo n.º 12
0
 def new(self):
     """docstring for new"""
     if not get_user():
         body = Template.Kind_Body % (Template.Kind_Top,"Not Login!","")
         html = Template.HTML % ("Not login!",body)
         return html
     if get_field('action') != 'new':
         form = """
                <form action="new" method="POST" accept-charset="utf-8">
                    <input type="hidden" name="action" value="new">
                    <div><input type="text" name="kind_name" value=""><span>Kind Name</span></div>
                    <div><input type="text" name="kind_shortname" value=""><span>Kind Short Name</span></div>
                <p><input type="submit" value="新增"></p>
                </form>
                """
         body = Template.Kind_Body %(Template.Kind_Top,form,"")
         html = Template.HTML % ("New Kind",body)
         return html
     else:
         kind_name = get_field('kind_name')
         kind_shortname = get_field('kind_shortname')
         kind_id = int(get_time_str())
         kind_count = 0
         sql = """insert into kind values (%s,%s,%s,%s)"""
         execute_sql_in_4bbs(sql,[kind_id,kind_name,kind_count,kind_shortname])
         return redirect("/kind")
Ejemplo n.º 13
0
    def upload_receive(self):
        request = quixote.get_request()
        print request.form.keys()

        the_file = request.form['file']
        print dir(the_file)
        print 'received file with name:', the_file.base_filename
        data = the_file.read(the_file.get_size())

        image.add_image(the_file.base_filename, data)


        ### sql metadata insertion ###
        metadata = {}
        metadata['title'] = request.form['title'];
        metadata['description'] = request.form['description']

        resp_doc = get_doc('meta')


        resp_doc['metadata'][str(the_file)] = metadata
      
        print "post doc"
        print resp_doc

        resp = post_doc(resp_doc)

        return quixote.redirect('./')
Ejemplo n.º 14
0
    def handle(self):
        """handle() -> string

        Master method for handling forms.  It should be called after
        initializing a form.  Controls form action based on a request.  You
        probably should override 'process' and 'action' instead of
        overriding this method.
        """
        request = get_request()
        if not self.is_submitted():
            return self.render(self.action_url)
        submit = self.get_submit()
        if submit == "cancel":
            return redirect(self.cancel_url)
        values = self.process()
        if submit == True:
            # The form was submitted by an unregistered submit button, assume
            # that the submission was required to update the layout of the form.
            self.clear_errors()
            return self.render(self.action_url)

        if self.has_errors():
            return self.render(self.action_url)
        else:
            return self.action(submit, values)
Ejemplo n.º 15
0
    def edit(self):
        if not get_user():
            body = Template.Kind_Body % (Template.Kind_Top,"Not Login!","")
            html = Template.HTML % ("Not login!",body)
            return html
        
        if get_field('action') != 'edit':
            kind_id = get_field('kind_id')
            if not kind_id:
                Body = Template.Kind_Body % (Template.Kind_Top,"Error Parameters!","")
                return Template.HTML % ("Error!",Body)
            sql = """select * from kind where kind_id=%s""" % kind_id
            count,res = execute_sql_in_4bbs(sql,"SHOW")
            kind_name = res[0][1]
            kind_shortname= res[0][3]
            form = """
                    <form action="edit" method="POST" accept-charset="utf-8">
                       <input type="hidden" name="action" value="edit">
                       <div><input type="text" name="kind_name" value="%s"><span>Kind Name</span></div>
                       <div><input type="text" name="kind_shortname" value="%s"><span>Kind Short Name</span></div>
                       <input type="hidden" name="kind_id" value="%s">
                   <p><input type="submit" value="编辑"></p>
                   </form>
                   """ % (kind_name,kind_shortname,kind_id)
            body = Template.Kind_Body % (Template.Kind_Top,form,"")
            html = Template.HTML % ("Edit Kind",body)
            return html

        else:
            kind_id = int(get_field('kind_id'))
            kind_name = get_field('kind_name')
            kind_shortname = get_field('kind_shortname')
            sql = """UPDATE kind SET kind_name=%s,kind_shortname=%s where kind_id=%s"""
            execute_sql_in_4bbs(sql,[kind_name,kind_shortname,kind_id])
            return redirect("/kind")
Ejemplo n.º 16
0
 def add_comment(self):
     response = quixote.get_response()
     request = quixote.get_request()
     number = request.form['id']
     comment = request.form['comment']
     image.add_comment(number, comment)
     return quixote.redirect('./image?id='+str(number))
Ejemplo n.º 17
0
    def login(self):
        request = get_request()

        username_widget = widget.StringWidget(name='username',
                                              value='')
        submit_widget = widget.SubmitWidget(name='submit',
                                            value='submit me')
        submit_widget2 = widget.SubmitWidget(name='nosubmit2',
                                             value="don't submit")
        
        if request.form:
            assert not submit_widget2.parse(request)
            username = username_widget.parse(request)
            if username:
                session = get_session()
                session.set_user(username)
                return redirect('./')

        image_submit = '''<input type=image name='submit you' src=DNE.gif>'''
                
        return "<form method=POST>Log in: %s<p>%s<p>%s<p>%s</form>" % \
               (username_widget.render(),
                submit_widget2.render(),
                submit_widget.render(),
                image_submit)
Ejemplo n.º 18
0
    def logout(self):
        # expire session
        session_manager = get_session_manager()
        session_manager.expire_session()

        # redirect to index page.
        return redirect(get_path(1) + '/')
Ejemplo n.º 19
0
    def logout(self):
        # expire session
        session_manager = get_session_manager()
        session_manager.expire_session()

        # redirect to index page.
        return redirect(get_path(1) + '/')
Ejemplo n.º 20
0
    def upload_receive(self):
        request = quixote.get_request()
        print request.form.keys()

        the_file = request.form['file']
        filetype = the_file.orig_filename.split('.')[1]
        filetype = filetype.lower()
        if (filetype == 'tif' or filetype == 'tiff'):
            filetype = 'tiff'
        elif filetype == 'jpeg' or filetype == 'jpg':
            filetype = 'jpg'
        else:
            filetype = 'png'
        print 'Received a file that is of type: ' + filetype
        print 'received file with name:', the_file.base_filename
        data = the_file.read(int(1e9))

        title = request.form['title']
        description = request.form['description']
        date = request.form['date']
        metadata = {'title':title, 'description':description, 'date':date}

        thumbnail = image.generate_thumbnail(data)
        
        image.add_image(data, filetype, metadata, thumbnail)

        return quixote.redirect('./')
Ejemplo n.º 21
0
    def request_build(self):
        request = quixote.get_request()
        key = request.form["result_key"]
        receipt, client_info, results = self.coord.db_get_result_info(key)

        self.coord.set_request_build(client_info, True)

        return quixote.redirect("./")
Ejemplo n.º 22
0
 def delete(self):
     current_user = quixote.get_request().get_cookie('user')
     if (current_user is not None):
         request = quixote.get_request()
         key = request.form['key']
         if (current_user == image.get_owner(key)[0]):
             image.delete_image(key)
     return quixote.redirect('./')
Ejemplo n.º 23
0
    def login_receive(self):
        request = quixote.get_request()
        username = request.form['username']
        password = request.form['password']

        if(self.authenticate(username, password)):
            return self.set_cookie(username)
        return quixote.redirect("./")
Ejemplo n.º 24
0
 def delete(self):
     if not get_user():
         body = Template.Kind_Body % (Template.Kind_Top,"Not Login!","")
         html = Template.HTML % ("Not login!",body)
         return html
     kind_id = get_field('kind_id')
     sql = """DELETE FROM kind where kind_id=%s"""
     execute_sql_in_4bbs(sql,[kind_id])
     return redirect("/kind")
Ejemplo n.º 25
0
	def add_comment(self):
		request = quixote.get_request()
		imageId = request.form['imageId']
		username = request.form['username']
		comment = request.form['comment']

		image.add_comment_to_image(imageId, username, comment)
		
		return quixote.redirect('./image?id=' + imageId)
Ejemplo n.º 26
0
 def __call__(self):
     if "" in self._q_exports and not quixote.get_request().form:
         # Fix missing trailing slash.
         path = quixote.get_path()
         print("Adding slash to: %r " % path)
         return quixote.redirect(path + "/", permanent=True)
     else:
         raise TraversalError(private_msg=('directory %r is not '
                                           'callable' % self))
Ejemplo n.º 27
0
    def keep(self):
        """
        Set the session to persist.
        """
        session = get_session()
        session.keep = True

        # redirect to index page.
        return redirect(get_path(1) + '/')
Ejemplo n.º 28
0
 def __call__(self):
     if "" in self._q_exports and not quixote.get_request().form:
         # Fix missing trailing slash.
         path = quixote.get_path()
         print "Adding slash to: %r " % path
         return quixote.redirect(path + "/", permanent=True)
     else:
         raise TraversalError(private_msg=('directory %r is not '
                                           'callable' % self))
Ejemplo n.º 29
0
    def request_build(self):
        key = self.result_key
        receipt = self.receipt
        client_info = self.client_info
        results = self.results
        package = self.package

        self.coord.set_request_build(client_info, True)

        return quixote.redirect("../")
Ejemplo n.º 30
0
    def request_build(self):
        key = self.result_key
        receipt = self.receipt
        client_info = self.client_info
        results = self.results
        package = self.package

        self.coord.set_request_build(client_info, True)

        return quixote.redirect('../')
Ejemplo n.º 31
0
    def set_defaults(self, request=None):
        for k in self.__properties__:
            delattr(self, k)

        back = request.get_environ('HTTP_REFERER')
        if back is not None:
            response.set_status(204) # no content
            return quixote.redirect(back)
        else:
            return 'prefs set to defaults\n';
Ejemplo n.º 32
0
 def create_account(self):
     request = quixote.get_request()
     user = request.form['username']
     password = request.form['password']
     account = Account(user, password)
     if accountmanager.exists_username(user):
         return self.account_name_taken()
     accountmanager.add_account(account)
     quixote.get_response().set_cookie('user', user, path='/')
     return quixote.redirect('./')
Ejemplo n.º 33
0
    def logout(self):
        """
        Expire the session, redirect back to index page.
        """
        # expire session
        session_manager = get_session_manager()
        session_manager.expire_session()

        # redirect to index page.
        return redirect(get_path(1) + '/')
Ejemplo n.º 34
0
 def delete_latest(self):
     current_user = quixote.get_request().get_cookie('user')
     if (current_user is not None):
         print 'OWNER: '
         print image.get_owner_latest()[0]
         print 'CURRENT USER: '******'./')
Ejemplo n.º 35
0
 def login(self):
     request = quixote.get_request()
     user = request.form['username']
     password = request.form['password']
     account = Account(user, password)
     if accountmanager.is_valid_login(account):
         response = quixote.get_response()
         response.set_cookie('user', user, path='/')
         return quixote.redirect('./')
     return self.invalid_login()
Ejemplo n.º 36
0
def _q_index(request):
    session = request.session

    user = admin.login_user(quiet=True)

    if user is None:
        path = login_path()
    else:
        path = user_path(user)

    return quixote.redirect(path)
Ejemplo n.º 37
0
    def handle(self, request):
        """handle(request : HTTPRequest) -> string

        Master method for handling forms.  It should be called after
        initializing a form.  Controls form action based on a request.  You
        probably should override 'process' and 'action' instead of
        overriding this method.
        """
        action_url = self.get_action_url(request)
        if not self.form_submitted(request):
            return self.render(request, action_url)
        submit = self.get_submit_button(request)
        if submit == "cancel":
            return redirect(self.cancel_url)
        values = self.process(request)
        if submit == "":
            # The form was submitted by unknown submit button, assume that
            # the submission was required to update the layout of the form.
            # Clear the errors and re-render the form.
            self.error.clear()
            return self.render(request, action_url)

        if self.use_form_tokens:
            # before calling action() ensure that there is a valid token
            # present
            token = values.get(self.TOKEN_NAME)
            if not request.session.has_form_token(token):
                if not self.error:
                    # if there are other errors then don't show the token
                    # error, the form needs to be resubmitted anyhow
                    self.error[self.TOKEN_NAME] = (
                        "The form you have submitted is invalid.  It has "
                        "already been submitted or has expired. Please "
                        "review and resubmit the form.")
            else:
                request.session.remove_form_token(token)

        if self.error:
            return self.render(request, action_url)
        else:
            return self.action(request, submit, values)
Ejemplo n.º 38
0
Archivo: nextbus.py Proyecto: ctb/meep
 def _q_index(self):
     request = quixote.get_request()
     return quixote.redirect('./html/index.html')
Ejemplo n.º 39
0
def _traverse_url(root_namespace, path_components, request, namespace_stack):
    """(root_namespace : any, path_components : [string],
        request : HTTPRequest, namespace_stack : list) -> (object : any)

    Perform traversal based on the provided path, starting at the root
    object.  It returns the script name and path info values for
    the arrived-at object, along with the object itself and
    a list of the namespaces traversed to get there.

    It's expected that the final object is something callable like a
    function or a method; intermediate objects along the way will
    usually be packages or modules.

    To prevent crackers from writing URLs that traverse private
    objects, every package, module, or object along the way must have
    a _q_exports attribute containing a list of publicly visible
    names.  Not having a _q_exports attribute is an error, though
    having _q_exports be an empty list is OK.  If a component of the path
    isn't in _q_exports, that also produces an error.

    Modifies the namespace_stack as it traverses the url, so that
    any exceptions encountered along the way can be handled by the
    nearest handler.
    """

    path = '/' + '/'.join(path_components)

    # If someone accesses a Quixote driver script without a trailing
    # slash, we'll wind up here with an empty path.  This won't
    # work; relative references in the page generated by the root
    # namespace's _q_index() will be off.  Fix it by redirecting the
    # user to the right URL; when the client follows the redirect,
    # we'll wind up here again with path == '/'.
    if not path:
        return redirect(request.environ['SCRIPT_NAME'] + '/', permanent=1)

    # Traverse starting at the root
    object = root_namespace
    namespace_stack.append(object)

    # Loop over the components of the path
    for component in path_components:
        if component == "":
            # "/q/foo/" == "/q/foo/_q_index"
            component = "_q_index"
        object = _get_component(object, component, request, namespace_stack)

    if not (isstring(object) or hasattr(object, '__call__')):
        # We went through all the components of the path and ended up at
        # something which isn't callable, like a module or an instance
        # without a __call__ method.
        if path[-1] != '/':
            if not request.form:
                # This is for the convenience of users who type in paths.
                # Repair the path and redirect.  This should not happen for
                # URLs within the site.
                return redirect(request.get_path() + "/", permanent=1)

            else:
                # Automatic redirects disabled or there is form data.  If
                # there is form data then the programmer is using the
                # wrong path.  A redirect won't work if the form data came
                # from a POST anyhow.
                raise errors.TraversalError(
                    "object is neither callable nor string "
                    "(missing trailing slash?)",
                    private_msg=repr(object),
                    path=path)
        else:
            raise errors.TraversalError(
                "object is neither callable nor string",
                private_msg=repr(object),
                path=path)

    return object
Ejemplo n.º 40
0
 def __call__(self):
     return quixote.redirect(self.location, self.permanent)