def delete(self, request, pk):
        view_utils.authorize(request, pk,
                             needed_permission=ACTION_TO_AUTHORIZE.EDIT_RESOURCE_ACCESS)
        keys = request.query_params.keys()
        user_access = UserAccess(user=request.user)
        resource = hydroshare.get_resource_by_shortkey(shortkey=pk)

        if "user_id" in keys and "group_id" in keys:
            message = "Request cannot contain both a 'user_id' and a 'group_id' parameter."
            return Response(
                data={'error': message},
                status=status.HTTP_400_BAD_REQUEST
            )

        if "user_id" in keys:
            user_to_remove = utils.user_from_id(request.query_params['user_id'])
            user_access.unshare_resource_with_user(resource, user_to_remove)
            return Response(
                data={'success': "Resource access privileges removed."},
                status=status.HTTP_202_ACCEPTED
            )

        if "group_id" in keys:
            group_to_remove = utils.group_from_id(request.query_params['group_id'])
            user_access.unshare_resource_with_group(resource, group_to_remove)
            return Response(
                data={'success': "Resource access privileges removed."},
                status=status.HTTP_202_ACCEPTED
            )

        message = "Request must contain a 'resource' ID as well as a 'user_id' or 'group_id'"
        return Response(
            data={'error': message},
            status=status.HTTP_400_BAD_REQUEST
        )
Example #2
0
def create_account(email,
                   username=None,
                   first_name=None,
                   last_name=None,
                   superuser=None,
                   groups=None,
                   password=None,
                   active=True):
    """
    Create a new user within the HydroShare system.

    Returns: The user that was created

    """

    from django.contrib.auth.models import User, Group
    from hs_access_control.models import UserAccess
    from hs_labels.models import UserLabels

    username = username if username else email

    groups = groups if groups else []
    groups = Group.objects.in_bulk(
        *groups) if groups and isinstance(groups[0], int) else groups

    if superuser:
        u = User.objects.create_superuser(username,
                                          email,
                                          first_name=first_name,
                                          last_name=last_name,
                                          password=password)
    else:
        u = User.objects.create_user(
            username,
            email,
            first_name=first_name,
            last_name=last_name,
            password=password,
        )

    u.is_staff = False
    if not active:
        u.is_active = False
    u.save()

    u.groups = groups

    # make the user a member of the Hydroshare role group
    u.groups.add(Group.objects.get(name='Hydroshare Author'))

    user_access = UserAccess(user=u)
    user_access.save()
    user_labels = UserLabels(user=u)
    user_labels.save()
    # create default UserQuota object for the new user
    uq = UserQuota.objects.create(user=u)
    uq.save()
    return u
    def put(self, request, pk):
        view_utils.authorize(request, pk,
                             needed_permission=ACTION_TO_AUTHORIZE.EDIT_RESOURCE_ACCESS)
        user_access = UserAccess(user=request.user)
        resource = hydroshare.get_resource_by_shortkey(shortkey=pk)
        keys = request.data.keys()

        if "user_id" in keys and "group_id" in keys:
            return Response(
                data={
                    'error': "Request cannot contain both a 'user_id' and a 'group_id' parameter."
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        if "user_id" in keys and "privilege" in keys:
            if int(request.data['privilege']) in (1, 2, 3, 4):
                try:
                    user_to_add = utils.user_from_id(request.data['user_id'])
                    user_access.share_resource_with_user(resource,
                                                         user_to_add,
                                                         request.data['privilege'])
                    return Response(
                        data={'success': "Resource access privileges added."},
                        status=status.HTTP_202_ACCEPTED
                    )
                except Exception:
                    return Response(
                        data={'error': "This resource may not be shared with that user."},
                        status=status.HTTP_400_BAD_REQUEST
                    )

        if "group_id" in keys and "privilege" in keys:
            if int(request.data['privilege']) in (1, 2, 3, 4):
                group_to_add = utils.group_from_id(request.data['group_id'])
                try:
                    user_access.share_resource_with_group(resource,
                                                          group_to_add,
                                                          request.data['privilege'])
                    return Response(
                        data={'success': "Resource access privileges added."},
                        status=status.HTTP_202_ACCEPTED
                    )
                except Exception:
                    return Response(
                        data={'error': "This group may not be added to any resources."},
                        status=status.HTTP_400_BAD_REQUEST
                    )

        message = "Request must contain a 'resource' ID as well as a 'user_id' or " \
                  "'group_id', and 'privilege' must be one of 1, 2, or 3."
        return Response(
            data={'error': message},
            status=status.HTTP_400_BAD_REQUEST
        )
    def delete(self, request, pk):
        view_utils.authorize(
            request,
            pk,
            needed_permission=ACTION_TO_AUTHORIZE.EDIT_RESOURCE_ACCESS)
        keys = request.query_params.keys()
        user_access = UserAccess(user=request.user)
        resource = hydroshare.get_resource_by_shortkey(shortkey=pk)

        if "user_id" in keys and "group_id" in keys:
            message = "Request cannot contain both a 'user_id' and a 'group_id' parameter."
            return Response(data={'error': message},
                            status=status.HTTP_400_BAD_REQUEST)

        if "user_id" in keys:
            user_to_remove = utils.user_from_id(
                request.query_params['user_id'])
            user_access.unshare_resource_with_user(resource, user_to_remove)
            return Response(
                data={'success': "Resource access privileges removed."},
                status=status.HTTP_202_ACCEPTED)

        if "group_id" in keys:
            group_to_remove = utils.group_from_id(
                request.query_params['group_id'])
            user_access.unshare_resource_with_group(resource, group_to_remove)
            return Response(
                data={'success': "Resource access privileges removed."},
                status=status.HTTP_202_ACCEPTED)

        message = "Request must contain a 'resource' ID as well as a 'user_id' or 'group_id'"
        return Response(data={'error': message},
                        status=status.HTTP_400_BAD_REQUEST)
    def put(self, request, pk):
        view_utils.authorize(
            request,
            pk,
            needed_permission=ACTION_TO_AUTHORIZE.EDIT_RESOURCE_ACCESS)
        user_access = UserAccess(user=request.user)
        resource = hydroshare.get_resource_by_shortkey(shortkey=pk)
        keys = request.data.keys()

        if "user_id" in keys and "group_id" in keys:
            return Response(data={
                'error':
                "Request cannot contain both a 'user_id' and a 'group_id' parameter."
            },
                            status=status.HTTP_400_BAD_REQUEST)

        if "user_id" in keys and "privilege" in keys:
            if int(request.data['privilege']) in (1, 2, 3, 4):
                try:
                    user_to_add = utils.user_from_id(request.data['user_id'])
                    user_access.share_resource_with_user(
                        resource, user_to_add, request.data['privilege'])
                    return Response(
                        data={'success': "Resource access privileges added."},
                        status=status.HTTP_202_ACCEPTED)
                except Exception:
                    return Response(data={
                        'error':
                        "This resource may not be shared with that user."
                    },
                                    status=status.HTTP_400_BAD_REQUEST)

        if "group_id" in keys and "privilege" in keys:
            if int(request.data['privilege']) in (1, 2, 3, 4):
                group_to_add = utils.group_from_id(request.data['group_id'])
                try:
                    user_access.share_resource_with_group(
                        resource, group_to_add, request.data['privilege'])
                    return Response(
                        data={'success': "Resource access privileges added."},
                        status=status.HTTP_202_ACCEPTED)
                except Exception:
                    return Response(data={
                        'error':
                        "This group may not be added to any resources."
                    },
                                    status=status.HTTP_400_BAD_REQUEST)

        message = "Request must contain a 'resource' ID as well as a 'user_id' or " \
                  "'group_id', and 'privilege' must be one of 1, 2, or 3."
        return Response(data={'error': message},
                        status=status.HTTP_400_BAD_REQUEST)
Example #6
0
def create_account(email,
                   username=None,
                   first_name=None,
                   last_name=None,
                   superuser=None,
                   groups=None,
                   password=None,
                   active=True,
                   organization=None):
    """
    Create a new user within the CommonsShare system.

    Returns: The user that was created

    """

    from django.contrib.auth.models import User, Group
    from hs_access_control.models import UserAccess
    from hs_labels.models import UserLabels

    username = username if username else email

    groups = groups if groups else []
    groups = Group.objects.in_bulk(
        *groups) if groups and isinstance(groups[0], int) else groups

    if superuser:
        u = User.objects.create_superuser(username,
                                          email,
                                          first_name=first_name,
                                          last_name=last_name,
                                          password=password)
    else:
        u = User.objects.create_user(
            username,
            email,
            first_name=first_name,
            last_name=last_name,
            password=password,
        )

    u.is_staff = False
    if not active:
        u.is_active = False
    u.save()

    u.groups = groups

    # make the user a member of the CommonsShare role group
    u.groups.add(Group.objects.get(name='CommonsShare Author'))

    user_access = UserAccess(user=u)
    user_access.save()
    user_labels = UserLabels(user=u)
    user_labels.save()
    user_profile = get_profile(u)

    if organization:
        user_profile.organization = organization
        user_profile.save()

        dict_items = organization.split(",")

        for dict_item in dict_items:
            # Update Dictionaries
            try:
                University.objects.get(name=dict_item)
            except ObjectDoesNotExist:
                new_term = UncategorizedTerm(name=dict_item)
                new_term.save()

    # create default UserQuota object for the new user
    uq = UserQuota.objects.create(user=u)
    uq.save()
    return u
Example #7
0
def create_account(email,
                   username=None,
                   first_name=None,
                   last_name=None,
                   superuser=None,
                   groups=None,
                   password=None,
                   active=True,
                   organization=None,
                   middle_name=None):
    """
    Create a new user within the HydroShare system.

    Returns: The user that was created

    """

    from django.contrib.auth.models import User, Group
    from hs_access_control.models import UserAccess
    from hs_labels.models import UserLabels

    try:
        user = User.objects.get(Q(username__iexact=username))
        raise ValidationError("User with provided username already exists.")
    except User.DoesNotExist:
        pass
    try:
        # we chose to follow current email practices with case insensitive emails
        user = User.objects.get(Q(email__iexact=email))
        raise ValidationError("User with provided email already exists.")
    except User.DoesNotExist:
        pass
    groups = groups if groups else []
    groups = Group.objects.in_bulk(
        *groups) if groups and isinstance(groups[0], int) else groups

    if superuser:
        u = User.objects.create_superuser(username,
                                          email,
                                          first_name=first_name,
                                          last_name=last_name,
                                          password=password)
    else:
        u = User.objects.create_user(
            username,
            email,
            first_name=first_name,
            last_name=last_name,
            password=password,
        )

    u.is_staff = False
    if not active:
        u.is_active = False
    u.save()

    u.groups = groups

    # make the user a member of the Hydroshare role group
    u.groups.add(Group.objects.get(name='Hydroshare Author'))

    user_access = UserAccess(user=u)
    user_access.save()
    user_labels = UserLabels(user=u)
    user_labels.save()
    user_profile = get_profile(u)

    if organization:
        user_profile.organization = organization
        user_profile.save()

        dict_items = organization.split(";")

        for dict_item in dict_items:
            # Update Dictionaries
            try:
                University.objects.get(name=dict_item)
            except ObjectDoesNotExist:
                new_term = UncategorizedTerm(name=dict_item)
                new_term.save()

    if middle_name:
        user_profile.middle_name = middle_name
        user_profile.save()

    # create default UserQuota object for the new user
    uq = UserQuota.objects.create(user=u)
    uq.save()
    return u
Example #8
0
def base_sample_resource(username='******',
                         title=str(uuid.uuid4()),
                         contributor=str(uuid.uuid4()),
                         creator=str(uuid.uuid4())):
    """A resource with sample entries that can be customized by tests"""
    rtype = 'CompositeResource'
    metadata = [{
        'coverage': {
            'type': 'period',
            'value': {
                'start': '01/01/2000',
                'end': '12/12/2010'
            }
        }
    }]
    statement = 'This resource is shared under the Creative Commons Attribution CC BY.'
    url = 'http://creativecommons.org/licenses/by/4.0/'
    metadata.append({'rights': {'statement': statement, 'url': url}})
    metadata.append({'language': {'code': 'fre'}})

    # contributor
    con_name = contributor
    con_org = 'USU'
    con_email = '*****@*****.**'
    con_address = "11 River Drive, Logan UT-84321, USA"
    con_phone = '435-567-0989'
    con_homepage = 'http://usu.edu/homepage/001'
    con_identifiers = {
        'ORCID': 'https://orcid.org/mike_s',
        'ResearchGateID': 'https://www.researchgate.net/mike_s'
    }
    metadata.append({
        'contributor': {
            'name': con_name,
            'organization': con_org,
            'email': con_email,
            'address': con_address,
            'phone': con_phone,
            'homepage': con_homepage,
            'identifiers': con_identifiers
        }
    })

    # creator
    cr_name = creator
    cr_org = 'USU'
    cr_email = '*****@*****.**'
    cr_address = "101 Clarson Ave, Provo UT-84321, USA"
    cr_phone = '801-567=9090'
    cr_homepage = 'http://byu.edu/homepage/002'
    cr_identifiers = {
        'ORCID': 'https://orcid.org/john_smith',
        'ResearchGateID': 'https://www.researchgate.net/john_smith'
    }
    metadata.append({
        'creator': {
            'name': cr_name,
            'organization': cr_org,
            'email': cr_email,
            'address': cr_address,
            'phone': cr_phone,
            'homepage': cr_homepage,
            'identifiers': cr_identifiers
        }
    })

    # relation
    metadata.append({
        'relation': {
            'type': 'isPartOf',
            'value': 'http://hydroshare.org/resource/001'
        }
    })
    # source
    metadata.append(
        {'source': {
            'derived_from': 'http://hydroshare.org/resource/0001'
        }})

    # identifier
    # metadata.append({'identifier': {'name': 'someIdentifier', 'url': 'http://some.org/001'}})

    # fundingagency
    agency_name = 'NSF'
    award_title = "Cyber Infrastructure"
    award_number = "NSF-101-20-6789"
    agency_url = "http://www.nsf.gov"
    metadata.append({
        'fundingagency': {
            'agency_name': agency_name,
            'award_title': award_title,
            'award_number': award_number,
            'agency_url': agency_url
        }
    })

    user = User.objects.get(username=username)

    _ = UserAccess(user=user)  # noqa
    _ = UserLabels(user=user)  # noqa

    metadata = json.loads(json.dumps(metadata))

    _res = hydroshare.create_resource(
        resource_type=rtype,
        owner=user,
        title=title,
        metadata=metadata,
        # files=(open('file.ext', 'rb'),)  # use a file that will exist in all environments and containers
    )
    return _res
Example #9
0
def create_account(
        email, username=None, first_name=None, last_name=None, superuser=None, groups=None,
        password=None, active=True, organization=None, middle_name=None):
    """
    Create a new user within the HydroShare system.

    Returns: The user that was created

    """

    from django.contrib.auth.models import User, Group
    from hs_access_control.models import UserAccess
    from hs_labels.models import UserLabels

    try:
        user = User.objects.get(Q(username__iexact=username))
        raise ValidationError("User with provided username already exists.")
    except User.DoesNotExist:
        pass
    try:
        # we chose to follow current email practices with case insensitive emails
        user = User.objects.get(Q(email__iexact=email))
        raise ValidationError("User with provided email already exists.")
    except User.DoesNotExist:
        pass
    groups = groups if groups else []
    groups = Group.objects.in_bulk(*groups) if groups and isinstance(groups[0], int) else groups

    if superuser:
        u = User.objects.create_superuser(
            username,
            email,
            first_name=first_name,
            last_name=last_name,
            password=password
        )
    else:
        u = User.objects.create_user(
            username, email,
            first_name=first_name,
            last_name=last_name,
            password=password,
        )

    u.is_staff = False
    if not active:
        u.is_active = False
    u.save()

    u.groups = groups

    # make the user a member of the Hydroshare role group
    u.groups.add(Group.objects.get(name='Hydroshare Author'))

    user_access = UserAccess(user=u)
    user_access.save()
    user_labels = UserLabels(user=u)
    user_labels.save()
    user_profile = get_profile(u)

    if organization:
        user_profile.organization = organization
        user_profile.save()

        dict_items = organization.split(";")

        for dict_item in dict_items:
            # Update Dictionaries
            try:
                University.objects.get(name=dict_item)
            except ObjectDoesNotExist:
                new_term = UncategorizedTerm(name=dict_item)
                new_term.save()

    if middle_name:
        user_profile.middle_name = middle_name
        user_profile.save()

    # create default UserQuota object for the new user
    uq = UserQuota.objects.create(user=u)
    uq.save()
    return u
Example #10
0
# usage: python loadUsersFromJSON.py users.JSON
# Cannot get django migration for hs_access_control migrate_users() to run after loading
# existing users, so write this customized script to load existing users as well as
# creating related UserAccess data
# Author: Hong Yi
import os
import sys

os.environ.setdefault("PYTHONPATH", "/home/docker/hydroshare")
os.environ["DJANGO_SETTINGS_MODULE"] = "hydroshare.settings"

import django
from django.core import serializers
from django.contrib.auth.models import User

django.setup()

with open(sys.argv[1]) as json_file:
    for user in serializers.deserialize("json", json_file):
        user.save()
    json_file.close()
from hs_access_control.models import UserAccess

UserAccess.objects.all().delete()
for u in User.objects.all():
    ua = UserAccess(user=u, admin=False)
    ua.save()
Example #11
0
def resource_with_metadata():
    """Resource with metadata for testing"""
    rtype = 'GenericResource'
    res_uuid = str(uuid.uuid4())
    title = 'Resource {}'.format(res_uuid)
    metadata = []
    metadata.append({
        'coverage': {
            'type': 'period',
            'value': {
                'start': '01/01/2000',
                'end': '12/12/2010'
            }
        }
    })
    statement = 'This resource is shared under the Creative Commons Attribution CC BY.'
    url = 'http://creativecommons.org/licenses/by/4.0/'
    metadata.append({'rights': {'statement': statement, 'url': url}})
    metadata.append({'language': {'code': 'fre'}})

    # contributor
    con_name = 'Mike Sundar'
    con_org = "USU"
    con_email = '*****@*****.**'
    con_address = "11 River Drive, Logan UT-84321, USA"
    con_phone = '435-567-0989'
    con_homepage = 'http://usu.edu/homepage/001'
    con_identifiers = {
        'ORCID': 'https://orcid.org/mike_s',
        'ResearchGateID': 'https://www.researchgate.net/mike_s'
    }
    metadata.append({
        'contributor': {
            'name': con_name,
            'organization': con_org,
            'email': con_email,
            'address': con_address,
            'phone': con_phone,
            'homepage': con_homepage,
            'identifiers': con_identifiers
        }
    })

    # creator
    cr_name = 'John Smith'
    cr_org = "USU"
    cr_email = '*****@*****.**'
    cr_address = "101 Clarson Ave, Provo UT-84321, USA"
    cr_phone = '801-567=9090'
    cr_homepage = 'http://byu.edu/homepage/002'
    cr_identifiers = {
        'ORCID': 'https://orcid.org/john_smith',
        'ResearchGateID': 'https://www.researchgate.net/john_smith'
    }
    metadata.append({
        'creator': {
            'name': cr_name,
            'organization': cr_org,
            'email': cr_email,
            'address': cr_address,
            'phone': cr_phone,
            'homepage': cr_homepage,
            'identifiers': cr_identifiers
        }
    })

    # relation
    metadata.append({
        'relation': {
            'type': 'isPartOf',
            'value': 'http://hydroshare.org/resource/001'
        }
    })
    # source
    metadata.append(
        {'source': {
            'derived_from': 'http://hydroshare.org/resource/0001'
        }})

    # identifier
    metadata.append({
        'identifier': {
            'name': 'someIdentifier',
            'url': 'http://some.org/001'
        }
    })

    # fundingagency
    agency_name = 'NSF'
    award_title = "Cyber Infrastructure"
    award_number = "NSF-101-20-6789"
    agency_url = "http://www.nsf.gov"
    metadata.append({
        'fundingagency': {
            'agency_name': agency_name,
            'award_title': award_title,
            'award_number': award_number,
            'agency_url': agency_url
        }
    })

    user = User.objects.get(username='******')

    user_access = UserAccess(user=user)
    user_access.save()
    user_labels = UserLabels(user=user)
    user_labels.save()

    metadata = json.loads(json.dumps(metadata))

    _res = hydroshare.create_resource(resource_type=rtype,
                                      owner=user,
                                      title=title,
                                      metadata=metadata,
                                      files=(open('assets/cea.tif'), ))
    yield res_uuid
    _res.delete()
Example #12
0
def resource_with_metadata():
    """Resource with metadata for testing"""
    rtype = 'GenericResource'
    res_uuid = str(uuid.uuid4())
    title = 'Resource {}'.format(res_uuid)
    metadata = []
    metadata.append({'coverage': {'type': 'period', 'value': {'start': '01/01/2000',
                                                              'end': '12/12/2010'}}})
    statement = 'This resource is shared under the Creative Commons Attribution CC BY.'
    url = 'http://creativecommons.org/licenses/by/4.0/'
    metadata.append({'rights': {'statement': statement, 'url': url}})
    metadata.append({'language': {'code': 'fre'}})

    # contributor
    con_name = 'Mike Sundar'
    con_org = "USU"
    con_email = '*****@*****.**'
    con_address = "11 River Drive, Logan UT-84321, USA"
    con_phone = '435-567-0989'
    con_homepage = 'http://usu.edu/homepage/001'
    con_identifiers = {'ORCID': 'https://orcid.org/mike_s',
                       'ResearchGateID': 'https://www.researchgate.net/mike_s'}
    metadata.append({'contributor': {'name': con_name,
                                     'organization': con_org, 'email': con_email,
                                     'address': con_address, 'phone': con_phone,
                                     'homepage': con_homepage,
                                     'identifiers': con_identifiers}})

    # creator
    cr_name = 'John Smith'
    cr_org = "USU"
    cr_email = '*****@*****.**'
    cr_address = "101 Clarson Ave, Provo UT-84321, USA"
    cr_phone = '801-567=9090'
    cr_homepage = 'http://byu.edu/homepage/002'
    cr_identifiers = {'ORCID': 'https://orcid.org/john_smith',
                      'ResearchGateID': 'https://www.researchgate.net/john_smith'}
    metadata.append({'creator': {'name': cr_name, 'organization': cr_org,
                                 'email': cr_email, 'address': cr_address,
                                 'phone': cr_phone, 'homepage': cr_homepage,
                                 'identifiers': cr_identifiers}})

    # relation
    metadata.append({'relation': {'type': 'isPartOf',
                                  'value': 'http://hydroshare.org/resource/001'}})
    # source
    metadata.append({'source': {'derived_from': 'http://hydroshare.org/resource/0001'}})

    # identifier
    metadata.append({'identifier': {'name': 'someIdentifier', 'url': 'http://some.org/001'}})

    # fundingagency
    agency_name = 'NSF'
    award_title = "Cyber Infrastructure"
    award_number = "NSF-101-20-6789"
    agency_url = "http://www.nsf.gov"
    metadata.append({'fundingagency': {'agency_name': agency_name, 'award_title': award_title,
                                       'award_number': award_number, 'agency_url': agency_url}})

    user = User.objects.get(username='******')

    user_access = UserAccess(user=user)
    user_access.save()
    user_labels = UserLabels(user=user)
    user_labels.save()

    metadata = json.loads(json.dumps(metadata))

    _res = hydroshare.create_resource(
        resource_type=rtype,
        owner=user,
        title=title,
        metadata=metadata,
        files=(open('assets/cea.tif'),)
    )
    yield res_uuid
    _res.delete()
Example #13
0
def migrate_users(apps, schema_editor):
    # create a 'UserAccess' record for each existing user - needed for the new access control to work
    UserAccess.objects.all().delete()
    for u in User.objects.all():
        ua = UserAccess(user=u)
        ua.save()