Exemple #1
0
    def request(self, user_obj, **kw):
        u = None
        # always revalidate auth
        if user_obj and user_obj.auth_method == self.name:
            user_obj = None
        # something else authenticated before us
        if user_obj:
            return user_obj, True

        auth = request.authorization
        if auth and auth.username and auth.password is not None:
            logging.debug("http basic auth, received username: {0!r} password: {1!r}".format(
                auth.username, auth.password))
            u = user.User(name=auth.username.decode(self.coding),
                          password=auth.password.decode(self.coding),
                          auth_method=self.name, auth_attribs=[], trusted=self.trusted)
            logging.debug("user: {0!r}".format(u))

        if not u or not u.valid:
            from werkzeug import Response, abort
            response = Response(_('Please log in first.'), 401,
                                {'WWW-Authenticate': 'Basic realm="{0}"'.format(self.realm)})
            abort(response)

        logging.debug("u: {0!r}".format(u))
        if u and self.autocreate:
            logging.debug("autocreating user")
            u.create_or_update()
        if u and u.valid:
            logging.debug("returning valid user {0!r}".format(u))
            return u, True  # True to get other methods called, too
        else:
            logging.debug("returning {0!r}".format(user_obj))
            return user_obj, True
Exemple #2
0
def send_file_partial(filePath):
    range_header = request.range
    if not range_header: return send_file(filePath)

    if range_header.units != 'bytes' or len(range_header.ranges) != 1:
        abort(400)

    size = os.path.getsize(filePath)
    content_range = range_header.make_content_range(size)

    app.logger.debug("Send file %s: %s" % (content_range, filePath))

    length = content_range.stop - content_range.start

    def data_generator(length=length):
        buffer_size = 8192
        with open(filePath, 'rb') as fp:
            fp.seek(content_range.start)
            while length > 0:
                data = fp.read(min(length, buffer_size))
                length -= len(data)
                yield data

    rv = Response(data_generator(),
                  206,
                  mimetype=mimetypes.guess_type(filePath)[0],
                  direct_passthrough=True)

    rv.headers.add('Content-Range', content_range.to_header())

    return rv
Exemple #3
0
def get_by_id_or_404(model, id, parent=None):
    """Returns a model instance fetched by id or raises a 404 Not Found error.
    Example::

        from tipfy import RequestHandler
        from tipfy.appengine.db import get_by_id_or_404
        from mymodels import Contact

        class EditContactHandler(RequestHandler):
            def get(self, **kwargs):
                contact = get_by_id_or_404(Contact, kwargs['contact_id'])

                # ... continue processing contact ...

    This function derives from `Kay <http://code.google.com/p/kay-framework/>`_.

    :param model:
        A ``db.Model`` class to load an entity.
    :param id:
        An id from a ``db.Key`` (an integer).
    :param parent:
        The parent entity for the requested entities, as a Model
        instance or Key instance, or None (the default) if the requested
        entities do not have a parent.
    :returns:
        A ``db.Model`` instance.
    """
    obj = model.get_by_id(id, parent=parent)
    if obj:
        return obj

    abort(404)
def send_file_partial(filePath):
    range_header = request.range
    if not range_header: return send_file(filePath)

    if range_header.units != 'bytes' or len(range_header.ranges) != 1:
        abort(400)

    size = os.path.getsize(filePath)
    content_range = range_header.make_content_range(size)

    app.logger.debug("Send file %s: %s" % (content_range, filePath))

    length = content_range.stop - content_range.start

    def data_generator(length=length):
        buffer_size = 8192
        with open(filePath, 'rb') as fp:
            fp.seek(content_range.start)
            while length > 0:
                data = fp.read(min(length, buffer_size))
                length -= len(data)
                yield data

    rv = Response(data_generator(),
        206,
        mimetype=mimetypes.guess_type(filePath)[0],
        direct_passthrough=True)

    rv.headers.add('Content-Range', content_range.to_header())

    return rv
Exemple #5
0
    def process_action_method(self):
        # now call our "action" methods, only one of these methods will be
        # called depending on the type of request and the attributes
        # available on the view
        http_method = rg.request.method.lower()
        method_name = None

        # handle XHR (Ajax) requests
        if rg.request.is_xhr:
            method_name = self.http_method_map['_xhr_']
            # if the method isn't present, treat it as a non-xhr request
            if method_name and not hasattr(self, method_name):
                method_name = None

        # handle based on HTTP request method type
        if not method_name and http_method in self.http_method_map:
            method_name = self.http_method_map[http_method]

        # if there wasn't a method name found or the method name doesn't exist
        # as a method, then try the default handler
        if method_name is None or not hasattr(self, method_name):
            method_name = self.http_method_map.get('_default_')
            if method_name is None or not hasattr(self, method_name):
                # default fallback failed, we can't handle this request method
                abort(405)

        # call the method that responds to this request method type
        retval = self._call_with_expected_args(getattr(self, method_name))

        # we allow the views to work on self.retval directly, but if the
        # action method returns a non-None value, it takes precedence
        if retval is not None:
            self.retval = retval
def test_proxy_exception():
    """Proxy exceptions"""
    orig_resp = Response('Hello World')
    try:
        abort(orig_resp)
    except exceptions.HTTPException, e:
        resp = e.get_response({})
Exemple #7
0
def get_by_key_name_or_404(model, key_name, parent=None):
    """Returns a model instance fetched by key name or raises a 404 Not Found
    error. Example::

        from tipfy import RequestHandler
        from tipfy.appengine.db import get_by_key_name_or_404
        from mymodels import Contact

        class EditContactHandler(RequestHandler):
            def get(self, **kwargs):
                contact = get_by_key_name_or_404(Contact,
                    kwargs['contact_key_name'])

                # ... continue processing contact ...

    This function derives from `Kay <http://code.google.com/p/kay-framework/>`_.

    :param model:
        A ``db.Model`` class to load an entity.
    :param key_name:
        A key name from a ``db.Key`` (a string).
    :param parent:
        The parent entity for the requested entities, as a Model
        instance or Key instance, or None (the default) if the requested
        entities do not have a parent.
    :returns:
        A ``db.Model`` instance.
    """
    obj = model.get_by_key_name(key_name, parent=parent)
    if obj:
        return obj

    abort(404)
 def http_redirect(self, url, code=302):
     """ Raise a simple redirect exception. """
     # werkzeug >= 0.6 does iri-to-uri transform if it gets unicode, but our
     # url is already url-quoted, so we better give it str to have same behaviour
     # with werkzeug 0.5.x and 0.6.x:
     url = str(url) # if url is unicode, it should contain ascii chars only
     abort(redirect(url, code=code))
Exemple #9
0
    def new_password(cls):
        """Create a new password

        .. tip::

            Unlike change password this does not demand the old password.
            And hence this method will check in the session for a parameter
            called allow_new_password which has to be True. This acts as a
            security against attempts to POST to this method and changing
            password.

            The allow_new_password flag is popped on successful saving

        This is intended to be used when a user requests for a password reset.
        """
        form = NewPasswordForm(request.form)

        if request.method == 'POST' and form.validate():
            if not session.get('allow_new_password', False):
                current_app.logger.debug('New password not allowed in session')
                abort(403)

            cls.write(
                [request.nereid_user],
                {'password': form.password.data}
            )
            session.pop('allow_new_password')
            flash(_(
                'Your password has been successfully changed! '
                'Please login again'))
            session.pop('user')
            return redirect(url_for('nereid.website.login'))

        return render_template('new-password.jinja', password_form=form)
    def new_password(self):
        """Create a new password

        .. tip::

            Unlike change password this does not demand the old password.
            And hence this method will check in the session for a parameter
            called allow_new_password which has to be True. This acts as a
            security against attempts to POST to this method and changing
            password.

            The allow_new_password flag is popped on successful saving

        This is intended to be used when a user requests for a password reset.
        """
        form = NewPasswordForm(request.form)

        if request.method == "POST" and form.validate():
            if not session.get("allow_new_password", False):
                current_app.logger.debug("New password not allowed in session")
                abort(403)

            self.write(request.nereid_user.id, {"password": form.password.data})
            session.pop("allow_new_password")
            flash(_("Your password has been successfully changed! " "Please login again"))
            session.pop("user")
            return redirect(url_for("nereid.website.login"))

        return render_template("new-password.jinja", password_form=form)
Exemple #11
0
    def request(self, user_obj, **kw):
        u = None
        # always revalidate auth
        if user_obj and user_obj.auth_method == self.name:
            user_obj = None
        # something else authenticated before us
        if user_obj:
            return user_obj, True

        auth = request.authorization
        if auth and auth.username and auth.password is not None:
            logging.debug("http basic auth, received username: {0!r} password: {1!r}".format(
                auth.username, auth.password))
            u = user.User(name=auth.username.decode(self.coding),
                          password=auth.password.decode(self.coding),
                          auth_method=self.name, auth_attribs=[], trusted=self.trusted)
            logging.debug("user: {0!r}".format(u))

        if not u or not u.valid:
            from werkzeug import Response, abort
            response = Response(_('Please log in first.'), 401,
                                {'WWW-Authenticate': 'Basic realm="{0}"'.format(self.realm)})
            abort(response)

        logging.debug("u: {0!r}".format(u))
        if u and self.autocreate:
            logging.debug("autocreating user")
            u.create_or_update()
        if u and u.valid:
            logging.debug("returning valid user {0!r}".format(u))
            return u, True  # True to get other methods called, too
        else:
            logging.debug("returning {0!r}".format(user_obj))
            return user_obj, True
Exemple #12
0
    def new_password(cls):
        """Create a new password

        .. tip::

            Unlike change password this does not demand the old password.
            And hence this method will check in the session for a parameter
            called allow_new_password which has to be True. This acts as a
            security against attempts to POST to this method and changing
            password.

            The allow_new_password flag is popped on successful saving

        This is intended to be used when a user requests for a password reset.
        """
        form = NewPasswordForm(request.form)

        if request.method == 'POST' and form.validate():
            if not session.get('allow_new_password', False):
                current_app.logger.debug('New password not allowed in session')
                abort(403)

            cls.write([request.nereid_user], {'password': form.password.data})
            session.pop('allow_new_password')
            flash(
                _('Your password has been successfully changed! '
                  'Please login again'))
            session.pop('user')
            return redirect(url_for('nereid.website.login'))

        return render_template('new-password.jinja', password_form=form)
Exemple #13
0
 def http_redirect(self, url, code=302):
     """ Raise a simple redirect exception. """
     # werkzeug >= 0.6 does iri-to-uri transform if it gets unicode, but our
     # url is already url-quoted, so we better give it str to have same behaviour
     # with werkzeug 0.5.x and 0.6.x:
     url = str(url) # if url is unicode, it should contain ascii chars only
     abort(redirect(url, code=code))
Exemple #14
0
def abort(send):
    """
        An enhanced version of Werkzeug's abort.  `send` is handled differently
        based on what it is:

        int: assumed to be a HTTP status code; not all codes supported by
            default, see the Werkzeug documentation for an explanation.
        string/unicode: will put the string as the body of a response and send
            it.
        callable: assume its a Response object or other WSGI application; wrap
            in proxy HTTPException and raise it;
        anything else: pformat, escape, wrap in <pre> tags, and treat like
            string/unicode above.
    """
    # this is a circular import if done at the module level
    from blazeweb.wrappers import Response

    response_body = reindent("""
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>abort() Response</title>
    <h1 style="margin-bottom: 25px">abort() Response</h1>

    %s""".strip(), 0)

    if isinstance(send, int) or hasattr(send, '__call__'):
        response = send
    elif isinstance(send, six.string_types):
        response = Response(response_body % escape(send))
    else:
        response = Response(response_body % ('<pre>%s</pre>' % escape(pformat(send))))
    werkzeug.abort(response)
Exemple #15
0
    def _dispatch_request(self, req, language, active_id):
        """
        Implement the nereid specific _dispatch
        """
        with Transaction().set_context(language=language):

            # otherwise dispatch to the handler for that endpoint
            if req.url_rule.endpoint in self.view_functions:
                meth = self.view_functions[req.url_rule.endpoint]
            else:
                model, method = req.url_rule.endpoint.rsplit('.', 1)
                meth = getattr(Pool().get(model), method)

            if not hasattr(meth, 'im_self') or meth.im_self:
                # static or class method
                result = meth(**req.view_args)
            else:
                # instance method, extract active_id from the url
                # arguments and pass the model instance as first argument
                model = Pool().get(req.url_rule.endpoint.rsplit('.', 1)[0])
                i = model(active_id)
                try:
                    i.rec_name
                except UserError:
                    # The record may not exist anymore which results in
                    # a read error
                    current_app.logger.debug(
                        "Record %s doesn't exist anymore." % i)
                    abort(404)
                result = meth(i, **req.view_args)

            if isinstance(result, LazyRenderer):
                result = (unicode(result), result.status, result.headers)

            return result
Exemple #16
0
    def new_password(self, sign, max_age=24 * 60 * 60):
        """Create a new password

        This is intended to be used when a user requests for a password reset.
        The link sent out to reset the password will be a timestamped sign
        which is validated for max_age before allowing the user to set the
        new password.
        """
        form = NewPasswordForm(request.form)

        if request.method == 'POST' and form.validate():
            try:
                unsigned = self._serializer.loads(
                    self._signer.unsign(sign, max_age=max_age),
                    salt='reset-password'
                )
            except SignatureExpired:
                flash(_("The password reset link has expired"))
            except BadSignature:
                flash(_('Invalid reset password code'))
            else:
                if not self.id == unsigned:
                    current_app.logger.debug('Invalid reset password code')
                    abort(403)

                self.write([self], {'password': form.password.data})
                flash(_(
                    'Your password has been successfully changed! '
                    'Please login again'))
            return redirect(url_for('nereid.website.login'))

        return render_template(
            'new-password.jinja', password_form=form, sign=sign, user=self
        )
Exemple #17
0
 def wrapped(*args, **kwargs):
     if not 'user' in session:
         if forbiddenCallback:
             return forbiddenCallback()
         else:
             abort(403)
     rv = f(*args, **kwargs)
     return rv
Exemple #18
0
def login_admin():
    pwd = request.form.get('password', None)
    if pwd is None or not isinstance(pwd, str):
        abort(403)
    import hashlib
    if hashlib.md5(pwd.encode()).hexdigest() == '52793b67f1e21817a15039f62f1041b9':
        make_admin()
        return redirect("/")
    return redirect(request.referrer)
Exemple #19
0
def _admin_required(handler):
    """Implementation for admin_required and AdminRequiredMiddleware."""
    auth = handler.auth

    if not auth.session:
        return handler.redirect(auth.login_url())

    if not auth.user or not auth.user.is_admin:
        abort(403)
Exemple #20
0
def _admin_required(handler):
    """Implementation for admin_required and AdminRequiredMiddleware."""
    auth = handler.auth

    if not auth.session:
        return handler.redirect(auth.login_url())

    if not auth.user or not auth.user.is_admin:
        abort(403)
Exemple #21
0
    def edit_address(cls, address=None):
        """
        Edit an Address

        POST will update an existing address.
        GET will return a existing address edit form.

        .. version_changed:: 3.0.3.0

            For creating new address use the create_address handled instead of
            this one. The functionality would be deprecated in 3.2.X

        :param address: ID of the address
        """
        if address is None:
            warnings.warn(
                "Address creation will be deprecated from edit_address handler."
                " Use party.address.create_address instead",
                DeprecationWarning
            )
            return cls.create_address()

        form = cls.get_address_form()

        if address not in (a.id for a in request.nereid_user.party.addresses):
            # Check if the address is in the list of addresses of the
            # current user's party
            abort(403)

        address = cls(address)

        if request.method == 'POST' and form.validate():
            party = request.nereid_user.party
            cls.write([address], {
                'name': form.name.data,
                'street': form.street.data,
                'streetbis': form.streetbis.data,
                'zip': form.zip.data,
                'city': form.city.data,
                'country': form.country.data,
                'subdivision': form.subdivision.data,
            })
            if form.email.data:
                party.add_contact_mechanism_if_not_exists(
                    'email', form.email.data
                )
            if form.phone.data:
                party.add_contact_mechanism_if_not_exists(
                    'phone', form.phone.data
                )
            return redirect(url_for('party.address.view_address'))

        elif request.method == 'GET' and address:
            # Its an edit of existing address, prefill data
            form = cls.get_address_form(address)

        return render_template('address-edit.jinja', form=form, address=address)
Exemple #22
0
def login_replace():
    target_uid = request.args.get('uid', None)
    confirm = request.args.get('confirm', None)
    if target_uid:
        if confirm:
            set_user_id(target_uid)
            return redirect('/')
        else:
            uid = get_user_id()
            return 'Your current user ID is \'%s\'.<br/>Replace it to \'%s\'?<br/><a href="%s">Do it!</a>' % (uid, target_uid, url_for('login_replace', uid=uid, confirm=True))
    abort(403)
Exemple #23
0
    def subdivision_list(cls):
        """
        Return the list of states for given country
        """
        Subdivision = Pool().get('country.subdivision')

        country = int(request.args.get('country', 0))
        if country not in [c.id for c in request.nereid_website.countries]:
            abort(404)
        subdivisions = Subdivision.search([('country', '=', country)])
        return jsonify(result=[s.serialize() for s in subdivisions])
Exemple #24
0
    def subdivision_list():
        """
        Return the list of states for given country
        """
        country = int(request.args.get("country", 0))
        if country not in [c.id for c in request.nereid_website.countries]:
            abort(404)

        Subdivision = Pool().get("country.subdivision")
        subdivisions = Subdivision.search([("country", "=", country)])
        return jsonify(result=[{"id": s.id, "name": s.name, "code": s.code} for s in subdivisions])
Exemple #25
0
 def wrapped(*args, **kwargs):
     if not 'user' in session:
         if not rate_limit_registration_global():
             abort(403)
         session.permanent = True
         session['user'] = '******'
         session['user_id'] = str(uuid4())
         session['create_info'] = _get_info()
         log.info('Create new guest accont:\n%s' % json.dumps(session['create_info'], indent=2))
         session['timestamp'] = time.time()
     rv = f(*args, **kwargs)
     return rv
Exemple #26
0
def handle_login(request,
                 userobj=None,
                 username=None,
                 password=None,
                 attended=True,
                 openid_identifier=None,
                 stage=None):
    """
    Process a 'login' request by going through the configured authentication
    methods in turn. The passable keyword arguments are explained in more
    detail at the top of this file.
    """
    params = {
        'username': username,
        'password': password,
        'attended': attended,
        'openid_identifier': openid_identifier,
        'multistage': (stage and True) or None
    }
    for authmethod in request.cfg.auth:
        #logging.info('CURRENT STAGE: %s, %s' % (params, authmethod.name))
        if stage and authmethod.name != stage:
            continue
        if openid_identifier and authmethod.name != 'openidqw':
            continue
        ret = authmethod.login(request, userobj, **params)

        userobj = ret.user_obj
        cont = ret.continue_flag
        if stage:
            stage = None
            del params['multistage']

        if ret.multistage:
            request._login_multistage = ret.multistage
            request._login_multistage_name = authmethod.name
            return userobj

        if ret.redirect_to:
            nextstage = get_multistage_continuation_url(
                request, authmethod.name)
            url = ret.redirect_to
            url = url.replace('%return_form', url_quote_plus(nextstage))
            url = url.replace('%return', url_quote(nextstage))
            abort(redirect(url))
        msg = ret.message
        if msg and not msg in request._login_messages:
            request._login_messages.append(msg)

        if not cont:
            break

    return userobj
Exemple #27
0
def download(fid):
    cur = get_db().execute("""SELECT "filename" FROM "file" WHERE "id" = :fid;""", {"fid": fid})
    res = cur.fetchone()
    cur.close()
    
    if res is None:
        abort(404, "There is no file with id {:d}.".format(fid))
    else:
        filename = join_path(current_app.config["UPLOAD_FOLDER"], res["filename"])
        if isfile(filename):
            return send_file(filename, as_attachment=True)
        else:
            abort(404, "The file '{:s}' could not be found.".format(filename))
Exemple #28
0
    def remove(self):
        """
        DELETE: Removes the current contact mechanism
        """
        ContactMechanism = Pool().get("party.contact_mechanism")

        if self.party == request.nereid_user.party:
            ContactMechanism.delete([self])
        else:
            abort(403)
        if request.is_xhr:
            return jsonify({"success": True})
        return redirect(request.referrer)
Exemple #29
0
    def subdivision_list(cls):
        """
        Return the list of states for given country
        """
        Subdivision = Pool().get('country.subdivision')

        country = int(request.args.get('country', 0))
        if country not in [c.id for c in request.nereid_website.countries]:
            abort(404)
        subdivisions = Subdivision.search([('country', '=', country)])
        return jsonify(
            result=[s.serialize() for s in subdivisions]
        )
Exemple #30
0
    def remove(self):
        """
        DELETE: Removes the current contact mechanism
        """
        ContactMechanism = Pool().get('party.contact_mechanism')

        if self.party == current_user.party:
            ContactMechanism.delete([self])
        else:
            abort(403)
        if request.is_xhr:
            return jsonify({'success': True})
        return redirect(request.referrer)
Exemple #31
0
    def remove_address(self):
        """
        Make address inactive if user removes the address from address book.
        """
        if self.party == current_user.party:
            self.active = False
            self.save()
            flash(_('Address has been deleted successfully!'))
            if request.is_xhr:
                return jsonify(success=True)
            return redirect(request.referrer)

        abort(403)
Exemple #32
0
    def nereid_user(self):
        """Fetch the browse record of current user or None."""
        NereidUser = current_app.pool.get('nereid.user')
        if 'user' not in session:
            return NereidUser(self.nereid_website.guest_user.id)

        try:
            nereid_user, = NereidUser.search([('id', '=', session['user'])])
        except ValueError:
            session.pop('user')
            abort(redirect(url_for('nereid.website.login')))
        else:
            return nereid_user
Exemple #33
0
    def edit_address(cls, address=None):
        """
        Edit an Address

        POST will update an existing address.
        GET will return a existing address edit form.

        .. version_changed:: 3.0.3.0

            For creating new address use the create_address handled instead of
            this one. The functionality would be deprecated in 3.2.X

        :param address: ID of the address
        """
        if address is None:
            warnings.warn(
                "Address creation will be deprecated from edit_address handler."
                " Use party.address.create_address instead",
                DeprecationWarning
            )
            return cls.create_address()

        address = cls(address)
        if address.party != current_user.party:
            # Check if the address belong to party
            abort(403)

        form = cls.get_address_form(address)

        if request.method == 'POST' and form.validate_on_submit():
            party = current_user.party
            cls.write([address], {
                'name': form.name.data,
                'street': form.street.data,
                'streetbis': form.streetbis.data,
                'zip': form.zip.data,
                'city': form.city.data,
                'country': form.country.data,
                'subdivision': form.subdivision.data,
            })
            if form.phone.data:
                phone = party.add_contact_mechanism_if_not_exists(
                    'phone', form.phone.data
                )
                cls.write([address], {
                    'phone_number': phone.id
                })
            return redirect(url_for('party.address.view_address'))

        return render_template('address-edit.jinja', form=form, address=address)
def handle_login(userobj, **kw):
    """
    Process a 'login' request by going through the configured authentication
    methods in turn. The passable keyword arguments are explained in more
    detail at the top of this file.
    """

    stage = kw.get('stage')
    params = {
        'username': kw.get('login_username'),
        'password': kw.get('login_password'),
        'openid': kw.get('login_openid'),
        'multistage': (stage and True) or None,
        'attended': True
    }
    # add the other parameters from the form
    for param in kw.keys():
        params[param] = kw.get(param)

    for authmethod in app.cfg.auth:
        if stage and authmethod.name != stage:
            continue
        ret = authmethod.login(userobj, **params)

        userobj = ret.user_obj
        cont = ret.continue_flag
        if stage:
            stage = None
            del params['multistage']

        if ret.multistage:
            flaskg._login_multistage = ret.multistage
            flaskg._login_multistage_name = authmethod.name
            return userobj

        if ret.redirect_to:
            nextstage = get_multistage_continuation_url(authmethod.name)
            url = ret.redirect_to
            url = url.replace('%return_form', url_quote_plus(nextstage))
            url = url.replace('%return', url_quote(nextstage))
            abort(redirect(url))
        msg = ret.message
        if msg and not msg in flaskg._login_messages:
            flaskg._login_messages.append(msg)

        if not cont:
            break

    return userobj
Exemple #35
0
    def edit_address(cls, address=None):
        """
        Edit an Address

        POST will update an existing address.
        GET will return a existing address edit form.

        .. version_changed:: 3.0.3.0

            For creating new address use the create_address handled instead of
            this one. The functionality would be deprecated in 3.2.X

        :param address: ID of the address
        """
        if address is None:
            warnings.warn(
                "Address creation will be deprecated from edit_address handler."
                " Use party.address.create_address instead",
                DeprecationWarning)
            return cls.create_address()

        address = cls(address)
        if address.party != current_user.party:
            # Check if the address belong to party
            abort(403)

        form = cls.get_address_form(address)

        if request.method == 'POST' and form.validate_on_submit():
            party = current_user.party
            cls.write(
                [address], {
                    'name': form.name.data,
                    'street': form.street.data,
                    'streetbis': form.streetbis.data,
                    'zip': form.zip.data,
                    'city': form.city.data,
                    'country': form.country.data,
                    'subdivision': form.subdivision.data,
                })
            if form.phone.data:
                phone = party.add_contact_mechanism_if_not_exists(
                    'phone', form.phone.data)
                cls.write([address], {'phone_number': phone.id})
            return redirect(url_for('party.address.view_address'))

        return render_template('address-edit.jinja',
                               form=form,
                               address=address)
Exemple #36
0
    def subdivision_list():
        """
        Return the list of states for given country
        """
        country = int(request.args.get('country', 0))
        if country not in [c.id for c in request.nereid_website.countries]:
            abort(404)

        Subdivision = Pool().get('country.subdivision')
        subdivisions = Subdivision.search([('country', '=', country)])
        return jsonify(result=[{
            'id': s.id,
            'name': s.name,
            'code': s.code,
        } for s in subdivisions])
Exemple #37
0
    def get(self, filename):
        try:
            resource = Resource(RetrieveResource(request))
            try:
                current_app.storages.retrieveResource(resource)
                response = x_accel_redirect(resource.location, resource.size)
                return response
            except StorageUnavailableError as e:
                abort(503)

        except HTTPException as e:
            # print(e)
            raise
        except Exception as e:
            abort(500)
Exemple #38
0
def handle_login(userobj, **kw):
    """
    Process a 'login' request by going through the configured authentication
    methods in turn. The passable keyword arguments are explained in more
    detail at the top of this file.
    """

    stage = kw.get('stage')
    params = {'username': kw.get('login_username'),
              'password': kw.get('login_password'),
              'openid': kw.get('login_openid'),
              'multistage': (stage and True) or None,
              'attended': True
             }
    # add the other parameters from the form
    for param in kw.keys():
        params[param] = kw.get(param)

    for authmethod in app.cfg.auth:
        if stage and authmethod.name != stage:
            continue
        ret = authmethod.login(userobj, **params)

        userobj = ret.user_obj
        cont = ret.continue_flag
        if stage:
            stage = None
            del params['multistage']

        if ret.multistage:
            flaskg._login_multistage = ret.multistage
            flaskg._login_multistage_name = authmethod.name
            return userobj

        if ret.redirect_to:
            nextstage = get_multistage_continuation_url(authmethod.name)
            url = ret.redirect_to
            url = url.replace('%return_form', url_quote_plus(nextstage))
            url = url.replace('%return', url_quote(nextstage))
            abort(redirect(url))
        msg = ret.message
        if msg and not msg in flaskg._login_messages:
            flaskg._login_messages.append(msg)

        if not cont:
            break

    return userobj
Exemple #39
0
    def _dispatch_request(self, req):
        """
        Implement the nereid specific _dispatch
        """

        language = 'en_US'
        if req.nereid_website:
            # If this is a request specific to a website
            # then take the locale from the website
            language = req.nereid_locale.language.code

        with Transaction().set_context(language=language):

            # pop locale if specified in the view_args
            req.view_args.pop('locale', None)

            # otherwise dispatch to the handler for that endpoint
            if req.url_rule.endpoint in self.view_functions:
                meth = self.view_functions[req.url_rule.endpoint]
            else:
                model, method = req.url_rule.endpoint.rsplit('.', 1)
                meth = getattr(Pool().get(model), method)

            if not hasattr(meth, 'im_self') or meth.im_self:
                # static or class method
                result = meth(**req.view_args)
            else:
                # instance method, extract active_id from the url
                # arguments and pass the model instance as first argument
                model = Pool().get(req.url_rule.endpoint.rsplit('.', 1)[0])
                i = model(req.view_args.pop('active_id'))
                try:
                    i.rec_name
                except UserError:
                    # The record may not exist anymore which results in
                    # a read error
                    current_app.logger.debug(
                        "Record %s doesn't exist anymore." % i
                    )
                    abort(404)
                result = meth(i, **req.view_args)

            if isinstance(result, LazyRenderer):
                result = (
                    unicode(result), result.status, result.headers
                )

            return result
Exemple #40
0
    def post(self):
        try:
            upload = request.files['image_file']

            resource = Resource(SaveResource(upload))

            try:
                current_app.storages.saveResource(resource)
                return 'OK', 201, {'location': resource.fileName}
            except StorageUnavailableError as e:
                abort(503)
            except ResourceExists:
                return 'OK', 200, {'location': resource.fileName}

        except Exception as e:
            abort(400)
Exemple #41
0
    def request(self, next, request, session, _route):
        if request.method == "POST" and not hasattr(_route.endpoint, '__csrf_exempt__'):
            csrf_token = session.pop('_csrf_token', None)
            if not csrf_token or csrf_token != request.form.get('_csrf_token'):
                raise abort(403, 'invalid CSRF token')

        return next()
Exemple #42
0
def rule(request, id):
    """Return a specific rule."""
    rule = Rule.query(id=id).first()
    if rule is None:
        return abort(404)
    else:
        return render_template(request, 'rule.html', rule=rule)
Exemple #43
0
    def send_static_file(cls, folder, name):
        """
        Invokes the send_file method in nereid.helpers to send a file as the
        response to the request. The file is sent in a way which is as
        efficient as possible. For example nereid will use the X-Send_file
        header to make nginx send the file if possible.

        :param folder: name of the folder
        :param name: name of the file
        """
        # TODO: Separate this search and find into separate cached method

        files = cls.search([('folder.name', '=', folder), ('name', '=', name)])
        if not files:
            abort(404)
        return send_file(files[0].file_path)
Exemple #44
0
    def send_static_file(cls, folder, name):
        """
        Invokes the send_file method in nereid.helpers to send a file as the
        response to the request. The file is sent in a way which is as
        efficient as possible. For example nereid will use the X-Send_file
        header to make nginx send the file if possible.

        :param folder: name of the folder
        :param name: name of the file
        """
        # TODO: Separate this search and find into separate cached method

        files = cls.search([("folder.name", "=", folder), ("name", "=", name)])
        if not files:
            abort(404)
        return send_file(files[0].file_path)
Exemple #45
0
    def request(self, next, request, session, _route):
        if request.method == "POST" and not hasattr(_route.endpoint,
                                                    '__csrf_exempt__'):
            csrf_token = session.pop('_csrf_token', None)
            if not csrf_token or csrf_token != request.form.get('_csrf_token'):
                raise abort(403, 'invalid CSRF token')

        return next()
def qrcode():
    if 'email' not in session:
        abort(404)
    user = Users.query.filter_by(Email=session['email']).first()
    if user is None:
        abort(404)
    del session['email']

    url = pyqrcode.create(user.get_totp_uri())
    stream = BytesIO()
    url.svg(stream, scale=5)
    return stream.getvalue(), 200, {
        'Content-Type': 'image/svg+xml',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
    }
Exemple #47
0
    def subdivision_list():
        """
        Return the list of states for given country
        """
        country = int(request.args.get('country', 0))
        if country not in [c.id for c in request.nereid_website.countries]:
            abort(404)

        Subdivision = Pool().get('country.subdivision')
        subdivisions = Subdivision.search([('country', '=', country)])
        return jsonify(
            result = [{
                'id': s.id,
                'name': s.name,
                'code': s.code,
                } for s in subdivisions
            ]
        )
Exemple #48
0
    def new_password(self, sign, max_age=24 * 60 * 60):
        """Create a new password

        This is intended to be used when a user requests for a password reset.
        The link sent out to reset the password will be a timestamped sign
        which is validated for max_age before allowing the user to set the
        new password.
        """
        form = NewPasswordForm()
        if form.validate_on_submit():
            try:
                unsigned = self._serializer.loads(
                    self._signer.unsign(sign, max_age=max_age),
                    salt='reset-password'
                )
            except SignatureExpired:
                return self.build_response(
                    'The password reset link has expired',
                    redirect(url_for('nereid.website.login')), 400
                )
            except BadSignature:
                return self.build_response(
                    'Invalid reset password code',
                    redirect(url_for('nereid.website.login')), 400
                )
            else:
                if not self.id == unsigned:
                    current_app.logger.debug('Invalid reset password code')
                    abort(403)

                self.write([self], {'password': form.password.data})
                return self.build_response(
                    'Your password has been successfully changed! '
                    'Please login again',
                    redirect(url_for('nereid.website.login')), 200
                )
        elif form.errors:
            if request.is_xhr or request.is_json:
                return jsonify(error=form.errors), 400
            flash(_('Passwords must match'))

        return render_template(
            'new-password.jinja', password_form=form, sign=sign, user=self
        )
Exemple #49
0
    def new_password(self, sign, max_age=24 * 60 * 60):
        """Create a new password

        This is intended to be used when a user requests for a password reset.
        The link sent out to reset the password will be a timestamped sign
        which is validated for max_age before allowing the user to set the
        new password.
        """
        form = NewPasswordForm()
        if form.validate_on_submit():
            try:
                unsigned = self._serializer.loads(
                    self._signer.unsign(sign, max_age=max_age),
                    salt='reset-password'
                )
            except SignatureExpired:
                return self.build_response(
                    'The password reset link has expired',
                    redirect(url_for('nereid.website.login')), 400
                )
            except BadSignature:
                return self.build_response(
                    'Invalid reset password code',
                    redirect(url_for('nereid.website.login')), 400
                )
            else:
                if not self.id == unsigned:
                    current_app.logger.debug('Invalid reset password code')
                    abort(403)

                self.write([self], {'password': form.password.data})
                return self.build_response(
                    'Your password has been successfully changed! '
                    'Please login again',
                    redirect(url_for('nereid.website.login')), 200
                )
        elif form.errors:
            if request.is_xhr or request.is_json:
                return jsonify(error=form.errors), 400
            flash(_('Passwords must match'))

        return render_template(
            'new-password.jinja', password_form=form, sign=sign, user=self
        )
def handle_login(request, userobj=None, username=None, password=None,
                 attended=True, openid_identifier=None, stage=None):
    """
    Process a 'login' request by going through the configured authentication
    methods in turn. The passable keyword arguments are explained in more
    detail at the top of this file.
    """
    params = {
        'username': username,
        'password': password,
        'attended': attended,
        'openid_identifier': openid_identifier,
        'multistage': (stage and True) or None
    }
    for authmethod in request.cfg.auth:
        if stage and authmethod.name != stage:
            continue
        ret = authmethod.login(request, userobj, **params)

        userobj = ret.user_obj
        cont = ret.continue_flag
        if stage:
            stage = None
            del params['multistage']

        if ret.multistage:
            request._login_multistage = ret.multistage
            request._login_multistage_name = authmethod.name
            return userobj

        if ret.redirect_to:
            nextstage = get_multistage_continuation_url(request, authmethod.name)
            url = ret.redirect_to
            url = url.replace('%return_form', url_quote_plus(nextstage))
            url = url.replace('%return', url_quote(nextstage))
            abort(redirect(url))
        msg = ret.message
        if msg and not msg in request._login_messages:
            request._login_messages.append(msg)

        if not cont:
            break

    return userobj
Exemple #51
0
def help_keyword(request, id):
    """Return help topics for a specific keyword."""
    keyword = HelpKeyword.query(id=id).first()
    if keyword is None:
        return abort(404)
    return render_template(request,
                           'help.html',
                           pages=keyword.help_topics,
                           keywords=None,
                           page=None)
Exemple #52
0
def help_page(request, id):
    """Return a specific help page."""
    page = HelpTopic.query(id=id).first()
    if page is None:
        return abort(404)
    return render_template(request,
                           'help.html',
                           page=page,
                           keywords=page.keywords,
                           pages=None)
Exemple #53
0
    def send_static_file(self, folder, name):
        """
        Invokes the send_file method in nereid.helpers to send a file as the
        response to the reuqest. The file is sent in a way which is as 
        efficient as possible. For example nereid will use the X-Send_file
        header to make nginx send the file if possible.

        :param folder: folder_name of the folder
        :param name: name of the file
        """
        #TODO: Separate this search and find into separate cached method

        ids = self.search([
            ('folder.folder_name', '=', folder),
            ('name', '=', name)
            ])
        if not ids:
            abort(404)
        file_ = self.browse(ids[0])
        return send_file(file_.file_path)
Exemple #54
0
    def set_currency(self):
        """Set the currency for the current session.

        Accepted Methods: GET, POST
        Accepts XHR: Yes
        """
        currency = int(request.values.get('currency', 0))
        if currency not in [c['id'] for c in self.get_currencies()]:
            abort(403)  # Forbidden currency

        session['currency'] = currency
        message = _("The currency has been successfully changed")

        if request.is_xhr:
            return jsonify(result = {'success': True, 'message': message})

        flash(message)
        # redirect to the next url if given else take to home page
        return redirect(
            request.values.get('next', url_for('nereid.website.home'))
            )
def get_or_404(*args, **kwargs):
    """Returns a model instance fetched by key or raises a 404 Not Found error.
    Example:

        from tipfy import RequestHandler
        from tipfy.appengine.db import get_or_404
        from mymodels import Contact

        class EditContactHandler(RequestHandler):
            def get(self, **kwargs):
                contact = get_or_404(kwargs['contact_key'])

                # ... continue processing contact ...

    This function derives from `Kay <http://code.google.com/p/kay-framework/>`_.

    :param args:
        Positional arguments to construct a key using ``db.Key.from_path()``
        or a ``db.Key`` instance or encoded key.
    :param kwargs:
        Keyword arguments to construct a key using ``db.Key.from_path()``.
    :returns:
        A ``db.Model`` instance.
    """
    try:
        if len(args) == 1:
            # A Key or encoded Key is the single argument.
            obj = db.get(args[0])
        else:
            # Build a key using all arguments.
            obj = db.get(db.Key.from_path(*args, **kwargs))

        if obj:
            return obj
    except (db.BadArgumentError, db.BadKeyError):
        # Falling through to raise the NotFound.
        pass

    abort(404)
Exemple #56
0
def get_or_404(*args, **kwargs):
    """Returns a model instance fetched by key or raises a 404 Not Found error.
    Example:

        from tipfy import RequestHandler
        from tipfy.appengine.db import get_or_404
        from mymodels import Contact

        class EditContactHandler(RequestHandler):
            def get(self, **kwargs):
                contact = get_or_404(kwargs['contact_key'])

                # ... continue processing contact ...

    This function derives from `Kay <http://code.google.com/p/kay-framework/>`_.

    :param args:
        Positional arguments to construct a key using ``db.Key.from_path()``
        or a ``db.Key`` instance or encoded key.
    :param kwargs:
        Keyword arguments to construct a key using ``db.Key.from_path()``.
    :returns:
        A ``db.Model`` instance.
    """
    try:
        if len(args) == 1:
            # A Key or encoded Key is the single argument.
            obj = db.get(args[0])
        else:
            # Build a key using all arguments.
            obj = db.get(db.Key.from_path(*args, **kwargs))

        if obj:
            return obj
    except (db.BadArgumentError, db.BadKeyError):
        # Falling through to raise the NotFound.
        pass

    abort(404)
Exemple #57
0
def get_post(id):
    cur = get_db().cursor()

    post = cur.execute(
        """
SELECT
    "id",
    "title",
    "body",
    "ref_date"
FROM "post" p
WHERE "id" = :pid
;
        """, {
            "pid": id
        }).fetchone()

    cur.close()

    if post is None:
        abort(404, "There is no post with id {:d}".format(id))

    return post
Exemple #58
0
def redirect_last_visited(request):
    pagetrail = request.user.getTrail()
    if pagetrail:
        # Redirect to last page visited
        last_visited = pagetrail[-1]
        wikiname, pagename = wikiutil.split_interwiki(last_visited)
        if wikiname != 'Self':
            wikitag, wikiurl, wikitail, error = wikiutil.resolve_interwiki(request, wikiname, pagename)
            url = wikiurl + wikiutil.quoteWikinameURL(wikitail)
        else:
            url = Page(request, pagename).url(request)
    else:
        # Or to localized FrontPage
        url = wikiutil.getFrontPage(request).url(request)
    url = request.getQualifiedURL(url)
    return abort(redirect(url))