Esempio n. 1
0
def integrity_error_handler(error):
    """
    Flask error handler for unhandled IntegrityErrors.

    Args:
        error (IntegrityError): The exception to be handled.

    Returns:
        tuple: A tuple of (message, HTTP error code).
    """
    # Because social auth provides the route and raises the exception, this is
    # the simplest way to turn the error into a nicely formatted error message
    # for the user.
    if 'email' in error.params:
        Session.rollback()
        if 'social_auth' in error.params:
            msg = (
                "Error: Authentication with authentication provider failed. "
                "Please try again later...")
            return msg, 500
        else:
            other_user = models.User.query.filter_by(
                email=error.params['email']).one()
            social_auth_user = other_user.social_auth.filter_by(
                user_id=other_user.id).one()
            msg = (
                "Error: There's already an account associated with your email, "
                "authenticate with {}.".format(social_auth_user.provider))
            return msg, 400

    return 'The server encountered an unexpected error', 500
Esempio n. 2
0
def add_distro():

    form = anitya.forms.DistroForm()

    if form.validate_on_submit():
        name = form.name.data

        distro = models.Distro(name)

        utilities.publish_message(
            distro=distro.__json__(),
            topic="distro.add",
            message=dict(agent=flask.g.user.username, distro=distro.name),
        )

        try:
            Session.add(distro)
            Session.commit()
            flask.flash("Distribution added")
        except SQLAlchemyError:
            Session.rollback()
            flask.flash("Could not add this distro, already exists?", "error")
        return flask.redirect(flask.url_for("anitya_ui.distros"))

    return flask.render_template("distro_add_edit.html",
                                 context="Add",
                                 current="distros",
                                 form=form)
Esempio n. 3
0
File: app.py Progetto: odra/anitya
def integrity_error_handler(error):
    """
    Flask error handler for unhandled IntegrityErrors.

    Args:
        error (IntegrityError): The exception to be handled.

    Returns:
        tuple: A tuple of (message, HTTP error code).
    """
    # Because social auth provides the route and raises the exception, this is
    # the simplest way to turn the error into a nicely formatted error message
    # for the user.
    if 'email' in error.params:
        Session.rollback()
        other_user = models.User.query.filter_by(email=error.params['email']).one()
        try:
            social_auth_user = other_user.social_auth.filter_by(user_id=other_user.id).one()
            msg = ("Error: There's already an account associated with your email, "
                   "authenticate with {}.".format(social_auth_user.provider))
            return msg, 400
        # This error happens only if there is account without provider info
        except NoResultFound:
            Session.delete(other_user)
            Session.commit()
            msg = (
                "Error: There was already an existing account with missing provider. "
                "So we removed it. "
                "Please try to log in again.")
            return msg, 500

    return 'The server encountered an unexpected error', 500
Esempio n. 4
0
def add_distro():

    form = anitya.forms.DistroForm()

    if form.validate_on_submit():
        name = form.name.data

        distro = models.Distro(name)

        utilities.log(Session,
                      distro=distro,
                      topic='distro.add',
                      message=dict(
                          agent=flask.g.user.username,
                          distro=distro.name,
                      ))

        try:
            Session.add(distro)
            Session.commit()
            flask.flash('Distribution added')
        except SQLAlchemyError:
            Session.rollback()
            flask.flash('Could not add this distro, already exists?', 'error')
        return flask.redirect(flask.url_for('anitya_ui.distros'))

    return flask.render_template('distro_add_edit.html',
                                 context='Add',
                                 current='distros',
                                 form=form)
Esempio n. 5
0
def set_user_active_state(user_id, state):

    if not is_admin():
        flask.abort(401)

    if state.upper() == "TRUE":
        state = True
    elif state.upper() == "FALSE":
        state = False
    else:
        flask.abort(422)

    try:
        user = Session.query(
            models.User).filter(models.User.id == user_id).one()
    except Exception as err:
        _log.exception(err)
        user = None

    if not user:
        flask.abort(404)

    form = anitya.forms.ConfirmationForm()

    if form.validate_on_submit():
        try:
            user.active = state
            Session.add(user)
            Session.commit()
            if state:
                flask.flash("User {0} is no longer banned".format(
                    user.username))
            else:
                flask.flash("User {0} is banned".format(user.username))
        except Exception as err:
            _log.exception(err)
            flask.flash(str(err), "errors")
            Session.rollback()

    return flask.redirect(flask.url_for("anitya_ui.browse_users"))
Esempio n. 6
0
def set_user_active_state(user_id, state):

    if not is_admin():
        flask.abort(401)

    if state.upper() == "TRUE":
        state = True
    elif state.upper() == "FALSE":
        state = False
    else:
        flask.abort(422)

    try:
        user = Session.query(models.User).filter(models.User.id == user_id).one()
    except Exception as err:
        _log.exception(err)
        user = None

    if not user:
        flask.abort(404)

    form = anitya.forms.ConfirmationForm()

    if form.validate_on_submit():
        try:
            user.active = state
            Session.add(user)
            Session.commit()
            if state:
                flask.flash("User {0} is no longer banned".format(user.username))
            else:
                flask.flash("User {0} is banned".format(user.username))
        except Exception as err:
            _log.exception(err)
            flask.flash(str(err), "errors")
            Session.rollback()

    return flask.redirect(flask.url_for("anitya_ui.browse_users"))
Esempio n. 7
0
def integrity_error_handler(error):
    """
    Flask error handler for unhandled IntegrityErrors.

    Args:
        error (IntegrityError): The exception to be handled.

    Returns:
        tuple: A tuple of (message, HTTP error code).
    """
    # Because social auth provides the route and raises the exception, this is
    # the simplest way to turn the error into a nicely formatted error message
    # for the user.
    if "email" in error.params:
        Session.rollback()
        other_user = models.User.query.filter_by(email=error.params["email"]).one()
        try:
            social_auth_user = other_user.social_auth.filter_by(
                user_id=other_user.id
            ).one()
            msg = (
                "Error: There's already an account associated with your email, "
                "authenticate with {}.".format(social_auth_user.provider)
            )
            return msg, 400
        # This error happens only if there is account without provider info
        except NoResultFound:
            Session.delete(other_user)
            Session.commit()
            msg = (
                "Error: There was already an existing account with missing provider. "
                "So we removed it. "
                "Please try to log in again."
            )
            return msg, 500

    return "The server encountered an unexpected error", 500
Esempio n. 8
0
    def post(self):
        """
        Create a new package associated with an existing project and distribution.

        **Example request**:

        .. sourcecode:: http

            POST /api/v2/packages/ HTTP/1.1
            Accept: application/json
            Accept-Encoding: gzip, deflate
            Authorization: Token gAOFi2wQPzUJFIfDkscAKjbJfXELCz0r44m57Ur2
            Connection: keep-alive
            Content-Length: 120
            Content-Type: application/json
            Host: localhost:5000
            User-Agent: HTTPie/0.9.4

            {
                "distribution": "Fedora",
                "package_name": "python-requests",
                "project_ecosystem": "pypi",
                "project_name": "requests"
            }

        .. sourcecode:: http

            HTTP/1.0 201 CREATED
            Content-Length: 69
            Content-Type: application/json
            Date: Mon, 15 Jan 2018 21:49:01 GMT
            Server: Werkzeug/0.14.1 Python/2.7.14

            {
                "distribution": "Fedora",
                "name": "python-requests"
            }


        :reqheader Authorization: API token to use for authentication
        :reqjson string distribution: The name of the distribution that contains this
            package.
        :reqjson string package_name: The name of the package in the distribution repository.
        :reqjson string project_name: The project name in Anitya.
        :reqjson string project_ecosystem: The ecosystem the project is a part of.
            If it's not part of an ecosystem, use the homepage used in the Anitya project.

        :statuscode 201: When the package was successfully created.
        :statuscode 400: When required arguments are missing or malformed.
        :statuscode 401: When your access token is missing or invalid
        :statuscode 409: When the package already exists.
        """
        distribution_help = _(
            "The name of the distribution that contains this package.")
        package_name_help = _(
            "The name of the package in the distribution repository.")
        project_name_help = _("The project name in Anitya.")
        project_ecosystem_help = _(
            "The ecosystem the project is a part of. If it's not part of an ecosystem,"
            " use the homepage used in the Anitya project.")

        parser = _BASE_ARG_PARSER.copy()
        parser.add_argument("distribution",
                            type=str,
                            help=distribution_help,
                            required=True)
        parser.add_argument("package_name",
                            type=str,
                            help=package_name_help,
                            required=True)
        parser.add_argument("project_name",
                            type=str,
                            help=project_name_help,
                            required=True)
        parser.add_argument("project_ecosystem",
                            type=str,
                            help=project_ecosystem_help,
                            required=True)
        args = parser.parse_args(strict=True)
        try:
            project = models.Project.query.filter(
                func.lower(models.Project.name) == func.lower(
                    args.project_name),
                func.lower(models.Project.ecosystem_name) == func.lower(
                    args.project_ecosystem),
            ).one()
        except NoResultFound:
            return (
                {
                    "error":
                    'Project "{}" in ecosystem "{}" not found'.format(
                        args.project_name, args.project_ecosystem)
                },
                400,
            )

        try:
            distro = models.Distro.query.filter(
                func.lower(models.Distro.name) == func.lower(
                    args.distribution)).one()
        except NoResultFound:
            return (
                {
                    "error":
                    'Distribution "{}" not found'.format(args.distribution)
                },
                400,
            )

        try:
            package = models.Packages(distro_name=distro.name,
                                      project=project,
                                      package_name=args.package_name)

            Session.add(package)
            Session.commit()

            message = dict(
                agent=flask_login.current_user.email,
                project=project.name,
                distro=distro.name,
                new=package.package_name,
            )
            utilities.publish_message(
                project=project.__json__(),
                distro=distro.__json__(),
                topic="project.map.new",
                message=message,
            )
            return {
                "distribution": distro.name,
                "name": package.package_name
            }, 201
        except IntegrityError:
            Session.rollback()
            return {"error": "package already exists in distribution"}, 409
Esempio n. 9
0
    def post(self):
        """
        Create a new package associated with an existing project and distribution.

        **Example request**:

        .. sourcecode:: http

            POST /api/v2/packages/ HTTP/1.1
            Accept: application/json
            Accept-Encoding: gzip, deflate
            Authorization: Token gAOFi2wQPzUJFIfDkscAKjbJfXELCz0r44m57Ur2
            Connection: keep-alive
            Content-Length: 120
            Content-Type: application/json
            Host: localhost:5000
            User-Agent: HTTPie/0.9.4

            {
                "distribution": "Fedora",
                "package_name": "python-requests",
                "project_ecosystem": "pypi",
                "project_name": "requests"
            }

        .. sourcecode:: http

            HTTP/1.0 201 CREATED
            Content-Length: 69
            Content-Type: application/json
            Date: Mon, 15 Jan 2018 21:49:01 GMT
            Server: Werkzeug/0.14.1 Python/2.7.14

            {
                "distribution": "Fedora",
                "name": "python-requests"
            }


        :reqheader Authorization: API token to use for authentication
        :reqjson string distribution: The name of the distribution that contains this
            package.
        :reqjson string package_name: The name of the package in the distribution repository.
        :reqjson string project_name: The project name in Anitya.
        :reqjson string project_ecosystem: The ecosystem the project is a part of.
            If it's not part of an ecosystem, use the homepage used in the Anitya project.

        :statuscode 201: When the package was successfully created.
        :statuscode 400: When required arguments are missing or malformed.
        :statuscode 401: When your access token is missing or invalid
        :statuscode 409: When the package already exists.
        """
        distribution_help = _(
            "The name of the distribution that contains this package."
        )
        package_name_help = _("The name of the package in the distribution repository.")
        project_name_help = _("The project name in Anitya.")
        project_ecosystem_help = _(
            "The ecosystem the project is a part of. If it's not part of an ecosystem,"
            " use the homepage used in the Anitya project."
        )

        parser = _BASE_ARG_PARSER.copy()
        parser.add_argument(
            "distribution", type=str, help=distribution_help, required=True
        )
        parser.add_argument(
            "package_name", type=str, help=package_name_help, required=True
        )
        parser.add_argument(
            "project_name", type=str, help=project_name_help, required=True
        )
        parser.add_argument(
            "project_ecosystem", type=str, help=project_ecosystem_help, required=True
        )
        args = parser.parse_args(strict=True)
        try:
            project = models.Project.query.filter_by(
                name=args.project_name, ecosystem_name=args.project_ecosystem
            ).one()
        except NoResultFound:
            return (
                {
                    "error": 'Project "{}" in ecosystem "{}" not found'.format(
                        args.project_name, args.project_ecosystem
                    )
                },
                400,
            )

        try:
            distro = models.Distro.query.filter_by(name=args.distribution).one()
        except NoResultFound:
            return (
                {"error": 'Distribution "{}" not found'.format(args.distribution)},
                400,
            )

        try:
            package = models.Packages(
                distro_name=distro.name, project=project, package_name=args.package_name
            )

            Session.add(package)
            Session.commit()

            message = dict(
                agent=flask_login.current_user.email,
                project=project.name,
                distro=distro.name,
                new=package.package_name,
            )
            utilities.log(
                Session,
                project=project.__json__(),
                distro=distro.__json__(),
                topic="project.map.new",
                message=message,
            )
            return {u"distribution": distro.name, u"name": package.package_name}, 201
        except IntegrityError:
            Session.rollback()
            return {"error": "package already exists in distribution"}, 409