def upgrade():
    context = get_context()
    session = Session(bind=op.get_bind())

    # two following lines avoids double 'DELETE' erroneous call when deleting group due to incorrect checks
    # https://stackoverflow.com/questions/28824401
    context.connection.engine.dialect.supports_sane_rowcount = False
    context.connection.engine.dialect.supports_sane_multi_rowcount = False

    if isinstance(context.connection.engine.dialect, PGDialect):
        # make sure group exists, then get it
        init_anonymous(db_session=session)
        anonym_group = GroupService.by_group_name(
            constants.get_constant("MAGPIE_ANONYMOUS_GROUP"),
            db_session=session)

        all_users = BaseService.all(models.User, db_session=session)
        all_user_group_refs = BaseService.all(models.UserGroup,
                                              db_session=session)
        all_user_group_tups = [(ugr.user_id, ugr.group_id)
                               for ugr in all_user_group_refs]
        for user in all_users:
            if (user.id, anonym_group.id) not in all_user_group_tups:
                # noinspection PyArgumentList
                user_group = models.UserGroup(user_id=user.id,
                                              group_id=anonym_group.id)
                session.add(user_group)
        session.commit()
Ejemplo n.º 2
0
 def _add_to_group(usr, grp):
     # type: (models.User, models.Group) -> None
     # noinspection PyArgumentList
     group_entry = models.UserGroup(group_id=grp.id, user_id=usr.id)
     ax.evaluate_call(
         lambda: db_session.add(group_entry),
         fallback=lambda: db_session.rollback(),
         httpError=HTTPForbidden,
         msgOnFail=s.UserGroup_GET_ForbiddenResponseSchema.description)
Ejemplo n.º 3
0
def register_user_with_group(user_name, group_name, email, password,
                             db_session):
    # type: (Str, Str, Str, Str, Session) -> None
    """
    Registers the user if missing and associate him to a group specified by name, also created if missing.

    :param user_name: name of the user to create (if missing) and to make part of the group (if specified)
    :param group_name: name of the group to create (if missing and specified) and to make the user join (if not already)
    :param email: email of the user to be created (if missing)
    :param password: password of the user to be created (if missing)
    :param db_session: database connexion to apply changes

    .. warning::
        Should be employed only for **special** users/groups in this module as other expected API behaviour
        and operations will not be applied (ex: create additional permissions or user-group references).
    """

    if not GroupService.by_group_name(group_name, db_session=db_session):
        # noinspection PyArgumentList
        new_group = models.Group(group_name=group_name)
        db_session.add(new_group)
    registered_group = GroupService.by_group_name(group_name=group_name,
                                                  db_session=db_session)

    registered_user = UserService.by_user_name(user_name,
                                               db_session=db_session)
    if not registered_user:
        # noinspection PyArgumentList
        new_user = models.User(user_name=user_name, email=email)
        UserService.set_password(new_user, password)
        UserService.regenerate_security_code(new_user)
        db_session.add(new_user)
        if group_name is not None:
            registered_user = UserService.by_user_name(user_name,
                                                       db_session=db_session)
    else:
        print_log("User '{}' already exist".format(user_name),
                  level=logging.DEBUG)

    # noinspection PyBroadException
    try:
        # ensure the reference between user/group exists (user joined the group)
        user_group_refs = BaseService.all(models.UserGroup,
                                          db_session=db_session)
        user_group_refs_tup = [(ref.group_id, ref.user_id)
                               for ref in user_group_refs]
        if (registered_group.id,
                registered_user.id) not in user_group_refs_tup:
            # noinspection PyArgumentList
            group_entry = models.UserGroup(group_id=registered_group.id,
                                           user_id=registered_user.id)
            db_session.add(group_entry)
    except Exception:  # in case reference already exists, avoid duplicate error
        db_session.rollback()
Ejemplo n.º 4
0
def assign_user_group(user, group, db_session):
    # type: (models.User, models.Group, Session) -> None
    """
    Creates a user-group relationship (user membership to a group).

    :returns: nothing - user-group is created.
    :raises HTTPError: corresponding error matching problem encountered.
    """
    ax.verify_param(user.id, param_compare=[usr.id for usr in group.users], not_in=True, with_param=False,
                    http_error=HTTPConflict, content={"user_name": user.user_name, "group_name": group.group_name},
                    msg_on_fail=s.UserGroups_POST_ConflictResponseSchema.description)
    ax.evaluate_call(lambda: db_session.add(models.UserGroup(group_id=group.id, user_id=user.id)),  # noqa
                     fallback=lambda: db_session.rollback(), http_error=HTTPForbidden,
                     msg_on_fail=s.UserGroups_POST_RelationshipForbiddenResponseSchema.description,
                     content={"user_name": user.user_name, "group_name": group.group_name})
Ejemplo n.º 5
0
def assign_user_group_view(request):
    """
    Assign a user to a group.
    """
    user = ar.get_user_matchdict_checked_or_logged(request)

    group_name = ar.get_value_multiformat_post_checked(request, "group_name")
    group = ax.evaluate_call(
        lambda: GroupService.by_group_name(group_name, db_session=request.db),
        fallback=lambda: request.db.rollback(),
        httpError=HTTPForbidden,
        msgOnFail=s.UserGroups_POST_ForbiddenResponseSchema.description)
    ax.verify_param(
        group,
        notNone=True,
        httpError=HTTPNotFound,
        msgOnFail=s.UserGroups_POST_GroupNotFoundResponseSchema.description)
    ax.verify_param(
        user.id,
        paramCompare=[usr.id for usr in group.users],
        notIn=True,
        httpError=HTTPConflict,
        content={
            u"user_name": user.user_name,
            u"group_name": group.group_name
        },
        msgOnFail=s.UserGroups_POST_ConflictResponseSchema.description)
    # noinspection PyArgumentList
    ax.evaluate_call(
        lambda: request.db.add(
            models.UserGroup(group_id=group.id, user_id=user.id)),
        fallback=lambda: request.db.rollback(),
        httpError=HTTPForbidden,
        msgOnFail=s.UserGroups_POST_RelationshipForbiddenResponseSchema.
        description,
        content={
            u"user_name": user.user_name,
            u"group_name": group.group_name
        })
    return ax.valid_http(
        httpSuccess=HTTPCreated,
        detail=s.UserGroups_POST_CreatedResponseSchema.description,
        content={
            u"user_name": user.user_name,
            u"group_name": group.group_name
        })
Ejemplo n.º 6
0
def join_discoverable_group_view(request):
    """
    Assigns membership of the logged user to a publicly discoverable group.
    """
    group = ar.get_group_matchdict_checked(request)
    user = ar.get_logged_user(request)
    group = ru.get_discoverable_group_by_name(group.group_name, db_session=request.db)

    ax.verify_param(user.id, param_compare=[usr.id for usr in group.users], not_in=True, with_param=False,
                    http_error=HTTPConflict, content={"user_name": user.user_name, "group_name": group.group_name},
                    msg_on_fail=s.RegisterGroup_POST_ConflictResponseSchema.description)
    ax.evaluate_call(lambda: request.db.add(models.UserGroup(group_id=group.id, user_id=user.id)),  # noqa
                     fallback=lambda: request.db.rollback(), http_error=HTTPForbidden,
                     msg_on_fail=s.RegisterGroup_POST_ForbiddenResponseSchema.description,
                     content={"user_name": user.user_name, "group_name": group.group_name})
    return ax.valid_http(http_success=HTTPCreated, detail=s.RegisterGroup_POST_CreatedResponseSchema.description,
                         content={"user_name": user.user_name, "group_name": group.group_name})
Ejemplo n.º 7
0
def downgrade_migrate(old_group, old_user, new_group, old_name, db_session):
    """
    Migrates a standard group back to the original user and corresponding personal user-group.

    Reassigns the user references to link to the old personal group.
    """

    if old_group is None:
        # create missing group
        # noinspection PyArgumentList
        old_group = models.Group(group_name=old_name)
        db_session.add(old_group)
    if old_group is not None and new_group is not None:
        # transfer user-group references
        all_usr_grp = db_session.query(models.UserGroup)
        for usr_grp in all_usr_grp:
            if usr_grp.group_id == new_group.id:
                # if user_id/group_id combination already exists, delete duplicate that would be generated by transfer
                match_old_grp = [
                    ug for ug in all_usr_grp if ug.group_id == old_group.id
                ]
                if len(match_old_grp) > 0:
                    db_session.delete(usr_grp)
                # otherwise transfer back reference to old group
                else:
                    usr_grp.group_id = old_group.id

    if new_group is not None:
        db_session.delete(new_group)

    if old_user is None:
        # noinspection PyArgumentList
        old_user = models.User(user_name=old_name,
                               email='{}@mail.com'.format(old_name))
        db_session.add(old_user)
        old_user = models.User.by_user_name(old_name, db_session)
        # noinspection PyArgumentList
        usr_grp = models.UserGroup(group_id=old_group.id, user_id=old_user.id)
        db_session.add(usr_grp)
Ejemplo n.º 8
0
 def _add_to_group(usr, grp):
     # type: (models.User, models.Group) -> None
     group_entry = models.UserGroup(group_id=grp.id, user_id=usr.id)  # noqa
     ax.evaluate_call(lambda: db_session.add(group_entry), fallback=lambda: db_session.rollback(),
                      http_error=HTTPForbidden, msg_on_fail=s.UserGroup_GET_ForbiddenResponseSchema.description)
Ejemplo n.º 9
0
def upgrade():
    context = get_context()
    session = Session(bind=op.get_bind())

    # two following lines avoids double 'DELETE' erroneous call when deleting group due to incorrect checks
    # https://stackoverflow.com/questions/28824401
    context.connection.engine.dialect.supports_sane_rowcount = False
    context.connection.engine.dialect.supports_sane_multi_rowcount = False

    if isinstance(context.connection.engine.dialect, PGDialect):
        all_groups = session.query(models.Group)
        all_user_group_refs = BaseService.all(models.UserGroup,
                                              db_session=session)
        map_groups = {
            OLD_GROUP_ADMIN: NEW_GROUP_ADMIN,
            OLD_GROUP_USERS: NEW_GROUP_USERS
        }

        for group in all_groups:
            if group.group_name in map_groups.keys():
                new_group_name = map_groups[group.group_name]
                new_group = GroupService.by_group_name(new_group_name,
                                                       db_session=session)

                # create new group if missing
                if not new_group:
                    # noinspection PyArgumentList
                    new_group = models.Group(group_name=new_group_name)
                    session.add(new_group)
                    new_group = GroupService.by_group_name(new_group_name,
                                                           db_session=session)

                old_group_perms = GroupService.resources_with_possible_perms(
                    group, db_session=session)
                new_group_perms = GroupService.resources_with_possible_perms(
                    new_group, db_session=session)
                diff_group_perms = set(old_group_perms) - set(new_group_perms)

                for perm in diff_group_perms:
                    perm.group = new_group
                    session.add(perm)

                for perm in old_group_perms:
                    session.delete(perm)

                old_group_users = [user.user_name for user in group.users]
                new_group_users = [user.user_name for user in new_group.users]
                diff_group_users = set(old_group_users) - set(new_group_users)

                for user_name in diff_group_users:
                    user = UserService.by_user_name(user_name=user_name,
                                                    db_session=session)
                    # noinspection PyArgumentList
                    user_group = models.UserGroup(group_id=new_group.id,
                                                  user_id=user.id)
                    session.add(user_group)

                session.delete(group)
                for user_group in all_user_group_refs:
                    if user_group.group_id == group.id:
                        session.delete(user_group)

        session.commit()