Esempio n. 1
0
    def __init__(self, copr, applicant, permission_dict):
        """
        :param models.Copr copr:
        :param models.User applicant: object of a user that applies for new permissions (e.g. flask.g.user)
        :param models.CoprPermission permission: permission object
        :param dict permission_dict: {"old_builder": int, "old_admin": int, "new_builder": int, "new_admin": int}
        """
        self.subject = "[Copr] {0}: {1} is requesting permissions change".format(
            copr.full_name, applicant.name)

        self.text = "{0} asked for these changes:\n\n".format(applicant.name)

        for perm in ['Builder', 'Admin']:
            old = permission_dict.get("old_" + perm.lower())
            new = permission_dict.get("new_" + perm.lower())

            if old != new:
                if old is None:
                    old = 0  # previously unset
                self.text += "{0}: {1} -> {2}\n".format(
                    perm,
                    helpers.PermissionEnum(old),
                    helpers.PermissionEnum(new),
                )

        self.text += "\nProject: {0}".format(copr.full_name)
Esempio n. 2
0
    def request_permission(cls, copr, user, permission, req_bool):
        approved = helpers.PermissionEnum('approved')
        state = None
        if req_bool is True:
            state = 'request'
        elif req_bool is False:
            state = 'nothing'
        else:
            raise BadRequest("invalid '{0}' permission request '{1}', "
                             "expected True or False".format(
                                 permission, req_bool))

        cls.validate_permission(user, copr, permission, state)
        perm_o = models.CoprPermission(user_id=user.id, copr_id=copr.id)
        perm_o = db.session.merge(perm_o)
        old_state = perm_o.get_permission(permission)
        if old_state == approved and state == 'request':
            raise BadRequest("You already are '{0}' in '{1}'".format(
                permission, copr.full_name))

        new_state = helpers.PermissionEnum(state)
        perm_o.set_permission(permission, new_state)

        if old_state != new_state:
            return (old_state, new_state)
        return None
Esempio n. 3
0
    def create_form_cls(permission=None):
        class F(FlaskForm):
            pass

        builder_default = False
        admin_default = False

        if permission:
            if permission.copr_builder != helpers.PermissionEnum("nothing"):
                builder_default = True
            if permission.copr_admin != helpers.PermissionEnum("nothing"):
                admin_default = True

        setattr(
            F, "copr_builder",
            wtforms.BooleanField(default=builder_default,
                                 false_values=FALSE_VALUES,
                                 filters=[ValueToPermissionNumberFilter()]))

        setattr(
            F, "copr_admin",
            wtforms.BooleanField(default=admin_default,
                                 false_values=FALSE_VALUES,
                                 filters=[ValueToPermissionNumberFilter()]))

        return F
Esempio n. 4
0
def copr_permissions_applier_change(username, coprname):
    copr = coprs_logic.CoprsLogic.get(flask.g.user, username, coprname).first()
    permission = coprs_logic.CoprPermissionsLogic.get(
        flask.g.user, copr, flask.g.user).first()
    applier_permissions_form = \
        forms.PermissionsApplierFormFactory.create_form_cls(permission)()

    if not copr:
        return page_not_found(
            "Project with name {0} does not exist.".format(coprname))

    if copr.owner == flask.g.user:
        flask.flash("Owner cannot request permissions for his own project.")
    elif applier_permissions_form.validate_on_submit():
        # we rely on these to be 0 or 1 from form. TODO: abstract from that
        if permission is not None:
            old_builder = permission.copr_builder
            old_admin = permission.copr_admin
        else:
            old_builder = 0
            old_admin = 0
        new_builder = applier_permissions_form.copr_builder.data
        new_admin = applier_permissions_form.copr_admin.data
        coprs_logic.CoprPermissionsLogic.update_permissions_by_applier(
            flask.g.user, copr, permission, new_builder, new_admin)
        db.session.commit()
        flask.flash(
            "Successfuly updated permissions for project '{0}'."
            .format(copr.name))
        admin_mails = [copr.owner.mail]
        for perm in copr.copr_permissions:
            # this 2 means that his status (admin) is approved
            if perm.copr_admin == 2:
                admin_mails.append(perm.user.mail)

        # sending emails
        if flask.current_app.config.get("SEND_EMAILS", False):
            for mail in admin_mails:
                msg = MIMEText(
                    "{6} is asking for these permissions:\n\n"
                    "Builder: {0} -> {1}\nAdmin: {2} -> {3}\n\n"
                    "Project: {4}\nOwner: {5}".format(
                        helpers.PermissionEnum(old_builder),
                        helpers.PermissionEnum(new_builder),
                        helpers.PermissionEnum(old_admin),
                        helpers.PermissionEnum(new_admin),
                        copr.name, copr.owner.name, flask.g.user.name))

                msg["Subject"] = "[Copr] {0}: {1} is asking permissons".format(copr.name, flask.g.user.name)
                msg["From"] = "root@{0}".format(platform.node())
                msg["To"] = mail
                s = smtplib.SMTP("localhost")
                s.sendmail("root@{0}".format(platform.node()), mail, msg.as_string())
                s.quit()

    return flask.redirect(flask.url_for("coprs_ns.copr_detail",
                                        username=copr.owner.name,
                                        coprname=copr.name))
Esempio n. 5
0
def copr_update_permissions(username, coprname):
    query = coprs_logic.CoprsLogic.get(flask.g.user, username, coprname)
    copr = query.first()
    permissions = copr.copr_permissions
    permissions_form = forms.PermissionsFormFactory.create_form_cls(
        permissions)()

    if permissions_form.validate_on_submit():
        # we don't change owner (yet)
        try:
            # if admin is changing his permissions, his must be changed last
            # so that we don't get InsufficientRightsException
            permissions.sort(
                cmp=lambda x, y: -1 if y.user_id == flask.g.user.id else 1)
            for perm in permissions:
                old_builder = perm.copr_builder
                old_admin = perm.copr_admin
                new_builder = permissions_form[
                    "copr_builder_{0}".format(perm.user_id)].data
                new_admin = permissions_form[
                    "copr_admin_{0}".format(perm.user_id)].data
                coprs_logic.CoprPermissionsLogic.update_permissions(
                    flask.g.user, copr, perm, new_builder, new_admin)
                if flask.current_app.config.get("SEND_EMAILS", False) and \
                        (old_builder is not new_builder or old_admin is not new_admin):

                    msg = MIMEText(
                        "Your permissions have changed:\n\n"
                        "Builder: {0} -> {1}\nAdmin: {2} -> {3}\n\n"
                        "Project: {4}\nOwner: {5}".format(
                            helpers.PermissionEnum(old_builder),
                            helpers.PermissionEnum(new_builder),
                            helpers.PermissionEnum(old_admin),
                            helpers.PermissionEnum(new_admin),
                            copr.name, copr.owner.name))

                    msg["Subject"] = "[Copr] {0}: Your permissions have changed".format(copr.name)
                    msg["From"] = "root@{0}".format(platform.node())
                    msg["To"] = perm.user.mail
                    s = smtplib.SMTP("localhost")
                    s.sendmail("root@{0}".format(platform.node()), perm.user.mail, msg.as_string())
                    s.quit()
        # for now, we don't check for actions here, as permissions operation
        # don't collide with any actions
        except exceptions.InsufficientRightsException as e:
            db.session.rollback()
            flask.flash(str(e))
        else:
            db.session.commit()
            flask.flash("Project permissions were updated successfully.")

    return flask.redirect(flask.url_for("coprs_ns.copr_detail",
                                        username=copr.owner.name,
                                        coprname=copr.name))
Esempio n. 6
0
    def f_copr_more_permissions(self, f_copr_permissions):
        self.u4 = models.User(
            username=u"user4",
            proven=False,
            mail="*****@*****.**",
            api_token='u4xxx',
            api_login='******',
            api_token_expiration=datetime.date.today() + datetime.timedelta(days=1000))

        # only a builder
        self.cp4 = models.CoprPermission(
            copr=self.c3,
            user=self.u4,
            copr_builder=helpers.PermissionEnum("approved"),
            copr_admin=helpers.PermissionEnum("nothing"))

        self.db.session.add_all([self.cp1, self.cp2, self.cp3])
Esempio n. 7
0
    def __init__(self, copr, permission_dict):
        """
        :param models.Copr copr:
        :param dict permission_dict: {"old_builder": int, "old_admin": int, "new_builder": int, "new_admin": int}
        """
        self.subject = "[Copr] {0}: Your permissions have changed".format(copr.full_name)
        self.text = "Your permissions have changed:\n\n"

        for perm in ['Builder', 'Admin']:
            old = permission_dict.get("old_"+perm.lower())
            new = permission_dict.get("new_"+perm.lower())
            if old != new:
                if old is None:
                    old = 0 # previously unset
                self.text += "{0}: {1} -> {2}\n".format(
                    perm, helpers.PermissionEnum(old),
                    helpers.PermissionEnum(new))

        self.text += "\nProject: {0}".format(copr.full_name)
Esempio n. 8
0
    def update_permissions_by_applier(cls, user, copr, copr_permission,
                                      new_builder, new_admin):
        if copr_permission:
            # preserve approved permissions if set
            if (not new_builder or copr_permission.copr_builder !=
                    helpers.PermissionEnum("approved")):

                copr_permission.copr_builder = new_builder

            if (not new_admin or copr_permission.copr_admin !=
                    helpers.PermissionEnum("approved")):

                copr_permission.copr_admin = new_admin
        else:
            perm = models.CoprPermission(user=user,
                                         copr=copr,
                                         copr_builder=new_builder,
                                         copr_admin=new_admin)

            cls.new(perm)
Esempio n. 9
0
    def can_edit(self, copr):
        """
        Determine if this user can edit the given copr.
        """

        can_edit = False
        if copr.owner == self:
            can_edit = True
        if (self.permissions_for_copr(copr)
                and self.permissions_for_copr(copr).copr_admin
                == helpers.PermissionEnum("approved")):

            can_edit = True

        return can_edit
Esempio n. 10
0
    def can_build_in(self, copr):
        """
        Determine if this user can build in the given copr.
        """

        can_build = False
        if copr.owner == self:
            can_build = True
        if (self.permissions_for_copr(copr)
                and self.permissions_for_copr(copr).copr_builder
                == helpers.PermissionEnum("approved")):

            can_build = True

        return can_build
Esempio n. 11
0
    def set_permissions(cls, request_user, copr, user, permission, state):
        users_logic.UsersLogic.raise_if_cant_update_copr(
            request_user, copr,
            "only owners and admins may update their projects permissions.")

        cls.validate_permission(user, copr, permission, state)

        perm_o = models.CoprPermission(user_id=user.id, copr_id=copr.id)
        perm_o = db.session.merge(perm_o)
        old_state = perm_o.get_permission(permission)

        new_state = helpers.PermissionEnum(state)
        perm_o.set_permission(permission, new_state)
        db.session.merge(perm_o)

        return (old_state, new_state) if old_state != new_state else None
Esempio n. 12
0
    def get_multiple(cls, user, **kwargs):
        user_relation = kwargs.get("user_relation", None)
        username = kwargs.get("username", None)
        with_mock_chroots = kwargs.get("with_mock_chroots", None)
        with_builds = kwargs.get("with_builds", None)
        incl_deleted = kwargs.get("incl_deleted", None)
        ids = kwargs.get("ids", None)

        query = (db.session.query(models.Copr)
                 .join(models.Copr.owner)
                 .options(db.contains_eager(models.Copr.owner))
                 .order_by(models.Copr.id.desc()))

        if not incl_deleted:
            query = query.filter(models.Copr.deleted == False)

        if isinstance(ids, list):  # can be an empty list
            query = query.filter(models.Copr.id.in_(ids))

        if user_relation == "owned":
            query = query.filter(
                models.User.username == username)
        elif user_relation == "allowed":
            aliased_user = db.aliased(models.User)

            query = (query.join(models.CoprPermission,
                                models.Copr.copr_permissions)
                     .filter(models.CoprPermission.copr_builder ==
                             helpers.PermissionEnum('approved'))
                     .join(aliased_user, models.CoprPermission.user)
                     .filter(aliased_user.username == username))

        if with_mock_chroots:
            query = (query.outerjoin(*models.Copr.mock_chroots.attr)
                     .options(db.contains_eager(*models.Copr.mock_chroots.attr))
                     .order_by(models.MockChroot.os_release.asc())
                     .order_by(models.MockChroot.os_version.asc())
                     .order_by(models.MockChroot.arch.asc()))

        if with_builds:
            query = (query.outerjoin(models.Copr.builds)
                     .options(db.contains_eager(models.Copr.builds))
                     .order_by(models.Build.submitted_on.desc()))

        return query
Esempio n. 13
0
    def can_edit(self, copr):
        """
        Determine if this user can edit the given copr.
        """

        if copr.user == self or self.admin:
            return True
        if (self.permissions_for_copr(copr)
                and self.permissions_for_copr(copr).copr_admin
                == helpers.PermissionEnum("approved")):

            return True

        if copr.group is not None and \
                copr.group.fas_name in self.user_teams:
            return True

        return False
Esempio n. 14
0
    def can_build_in(self, copr):
        """
        Determine if this user can build in the given copr.
        """
        can_build = False
        if copr.user_id == self.id:
            can_build = True
        if (self.permissions_for_copr(copr)
                and self.permissions_for_copr(copr).copr_builder
                == helpers.PermissionEnum("approved")):

            can_build = True

        # a bit dirty code, here we access flask.session object
        if copr.group is not None and \
                copr.group.fas_name in self.user_teams:
            return True

        return can_build
Esempio n. 15
0
    def f_copr_permissions(self):
        self.cp1 = models.CoprPermission(
            copr=self.c2,
            user=self.u1,
            copr_builder=helpers.PermissionEnum("approved"),
            copr_admin=helpers.PermissionEnum("nothing"))

        self.cp2 = models.CoprPermission(
            copr=self.c3,
            user=self.u3,
            copr_builder=helpers.PermissionEnum("nothing"),
            copr_admin=helpers.PermissionEnum("nothing"))

        self.cp3 = models.CoprPermission(
            copr=self.c3,
            user=self.u1,
            copr_builder=helpers.PermissionEnum("request"),
            copr_admin=helpers.PermissionEnum("approved"))
Esempio n. 16
0
 def __call__(self, value):
     if value:
         return helpers.PermissionEnum("request")
     return helpers.PermissionEnum("nothing")
Esempio n. 17
0
 def get_admins_for_copr(cls, copr):
     permissions = cls.get_for_copr(copr)
     return [copr.user] + [
         p.user for p in permissions
         if p.copr_admin == helpers.PermissionEnum("approved")
     ]
Esempio n. 18
0
def perm_type_from_num(num):
    return helpers.PermissionEnum(num)