Esempio n. 1
0
def user_set_quota(request, email):
    if request.method != 'POST':
        raise Http404

    content_type = 'application/json; charset=utf-8'
    result = {}

    f = SetUserQuotaForm(request.POST)
    if f.is_valid():
        space_quota_mb = f.cleaned_data['space_quota']
        space_quota = space_quota_mb * get_file_size_unit('MB')

        org = ccnet_api.get_orgs_by_user(email)
        try:
            if not org:
                seafile_api.set_user_quota(email, space_quota)
            else:
                org_id = org[0].org_id
                org_quota_mb = seafserv_threaded_rpc.get_org_quota(org_id) / get_file_size_unit('MB')
                if space_quota_mb > org_quota_mb:
                    result['error'] = _('Failed to set quota: maximum quota is %d MB' % \
                                            org_quota_mb)
                    return HttpResponse(json.dumps(result), status=400, content_type=content_type)
                else:
                    seafile_api.set_org_user_quota(org_id, email, space_quota)
        except:
            result['error'] = _('Failed to set quota: internal server error')
            return HttpResponse(json.dumps(result), status=500, content_type=content_type)

        result['success'] = True
        return HttpResponse(json.dumps(result), content_type=content_type)
    else:
        result['error'] = str(list(f.errors.values())[0])
        return HttpResponse(json.dumps(result), status=400, content_type=content_type)
Esempio n. 2
0
def update_user_info(request, user, password, is_active, is_staff, role,
                     nickname, login_id, contact_email, reference_id,
                     quota_total_mb, institution_name):

    # update basic user info
    if is_active is not None:
        user.is_active = is_active

    if password:
        user.set_password(password)

    if is_staff is not None:
        user.is_staff = is_staff

    # update user
    user.save()

    email = user.username

    # update additional user info
    if is_pro_version() and role:
        User.objects.update_role(email, role)

    if nickname is not None:
        Profile.objects.add_or_update(email, nickname)
        key = normalize_cache_key(nickname, NICKNAME_CACHE_PREFIX)
        cache.set(key, nickname, NICKNAME_CACHE_TIMEOUT)

    if login_id is not None:
        Profile.objects.add_or_update(email, login_id=login_id)

    if contact_email is not None:
        Profile.objects.add_or_update(email, contact_email=contact_email)
        key = normalize_cache_key(email, CONTACT_CACHE_PREFIX)
        cache.set(key, contact_email, CONTACT_CACHE_TIMEOUT)

    if reference_id is not None:
        if reference_id.strip():
            ccnet_api.set_reference_id(email, reference_id.strip())
        else:
            # remove reference id
            ccnet_api.set_reference_id(email, None)

    if institution_name is not None:
        Profile.objects.add_or_update(email, institution=institution_name)
        if institution_name == '':
            InstitutionAdmin.objects.filter(user=email).delete()

    if quota_total_mb:
        quota_total = int(quota_total_mb) * get_file_size_unit('MB')
        orgs = ccnet_api.get_orgs_by_user(email)
        try:
            if orgs:
                org_id = orgs[0].org_id
                seafile_api.set_org_user_quota(org_id, email, quota_total)
            else:
                seafile_api.set_user_quota(email, quota_total)
        except Exception as e:
            logger.error(e)
            seafile_api.set_user_quota(email, -1)
Esempio n. 3
0
def user_set_quota(request, email):
    if request.method != 'POST':
        raise Http404

    content_type = 'application/json; charset=utf-8'
    result = {}

    f = SetUserQuotaForm(request.POST)
    if f.is_valid():
        email = f.cleaned_data['email']
        quota_mb = f.cleaned_data['quota']
        quota = quota_mb * (1 << 20)

        org = ccnet_threaded_rpc.get_orgs_by_user(email)
        try:
            if not org:
                seafile_api.set_user_quota(email, quota)
            else:
                org_id = org[0].org_id
                seafserv_threaded_rpc.set_org_user_quota(org_id, email, quota)
        except:
            result['error'] = _(u'Failed to set quota: internal server error')
            return HttpResponse(json.dumps(result),
                                status=500,
                                content_type=content_type)

        result['success'] = True
        return HttpResponse(json.dumps(result), content_type=content_type)
    else:
        result['error'] = str(f.errors.values()[0])
        return HttpResponse(json.dumps(result),
                            status=400,
                            content_type=content_type)
Esempio n. 4
0
def user_set_quota(request, email):
    if request.method != 'POST':
        raise Http404

    content_type = 'application/json; charset=utf-8'
    result = {}

    f = SetUserQuotaForm(request.POST)
    if f.is_valid():
        email = f.cleaned_data['email']
        quota_mb = f.cleaned_data['quota']
        quota = quota_mb * (1 << 20)

        org = ccnet_threaded_rpc.get_orgs_by_user(email)
        try:
            if not org:
                seafile_api.set_user_quota(email, quota)
            else:
                org_id = org[0].org_id
                org_quota_mb = seafserv_threaded_rpc.get_org_quota(org_id) / (1 << 20)
                if quota_mb > org_quota_mb:
                    result['error'] = _(u'Failed to set quota: maximum quota is %d MB' % \
                                            org_quota_mb)
                    return HttpResponse(json.dumps(result), status=400, content_type=content_type)
                else:
                    seafserv_threaded_rpc.set_org_user_quota(org_id, email, quota)
        except:
            result['error'] = _(u'Failed to set quota: internal server error')
            return HttpResponse(json.dumps(result), status=500, content_type=content_type)

        result['success'] = True
        return HttpResponse(json.dumps(result), content_type=content_type)
    else:
        result['error'] = str(f.errors.values()[0])
        return HttpResponse(json.dumps(result), status=400, content_type=content_type)
Esempio n. 5
0
    def _update_account_quota(self, request, email):
        storage = request.data.get("storage", None)
        sharing = request.data.get("sharing", None)

        if storage is None and sharing is None:
            return

        if storage is not None:
            seafile_api.set_user_quota(email, int(storage))
Esempio n. 6
0
    def _update_account_quota(self, request, email):
        storage = request.data.get("storage", None)
        sharing = request.data.get("sharing", None)

        if storage is None and sharing is None:
            return

        if storage is not None:
            seafile_api.set_user_quota(email, int(storage))
Esempio n. 7
0
def _set_quota(user, quota):
    """Set the quota of the user to the given value, and restore the old value when exit"""
    oldquota = seafilerpc.get_user_quota(user)
    if seafilerpc.set_user_quota(user, quota) < 0:
        raise RuntimeError('failed to change user quota')
    assert seafilerpc.get_user_quota(user) == quota
    try:
        yield
    finally:
        seafilerpc.set_user_quota(user, oldquota)
Esempio n. 8
0
def _set_quota(user, quota):
    """Set the quota of the user to the given value, and restore the old value when exit"""
    oldquota = seafilerpc.get_user_quota(user)
    if seafilerpc.set_user_quota(user, quota) < 0:
        raise RuntimeError('failed to change user quota')
    assert seafilerpc.get_user_quota(user) == quota
    try:
        yield
    finally:
        seafilerpc.set_user_quota(user, oldquota)
Esempio n. 9
0
    def _update_account_additional_info(self, request, email):

        # update account profile
        name = request.data.get("name", None)
        if name is not None:
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)
            profile.nickname = name
            profile.save()

        # update account loginid
        loginid = request.data.get("login_id", '').strip()
        if loginid != '':
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)
            profile.login_id = loginid
            profile.save()

        # update account detailed profile
        department = request.data.get("department", None)
        if department is not None:
            d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email)
            if d_profile is None:
                d_profile = DetailedProfile(user=email)

            d_profile.department = department
            d_profile.save()

        # update user quota
        space_quota_mb = request.data.get("storage", None)
        if space_quota_mb is not None:
            space_quota = int(space_quota_mb) * get_file_size_unit('MB')
            if is_org_context(request):
                org_id = request.user.org.org_id
                seaserv.seafserv_threaded_rpc.set_org_user_quota(org_id,
                        email, space_quota)
            else:
                seafile_api.set_user_quota(email, space_quota)

        # update is_trial
        is_trial = request.data.get("is_trial", None)
        if is_trial is not None:
            try:
                from seahub_extra.trialaccount.models import TrialAccount
            except ImportError:
                pass
            else:
                if is_trial is True:
                    expire_date = timezone.now() + relativedelta(days=7)
                    TrialAccount.object.create_or_update(email, expire_date)
                else:
                    TrialAccount.objects.filter(user_or_org=email).delete()
Esempio n. 10
0
def update_user_info(request):

    email = request.data.get("email")
    user = User.objects.get(email=email)

    # update basic user info
    password = request.data.get("password")
    if password:
        user.set_password(password)

    is_staff = request.data.get("is_staff")
    if is_staff:
        is_staff = to_python_boolean(is_staff)
        user.is_staff = is_staff

    is_active = request.data.get("is_active")
    if is_active:
        is_active = to_python_boolean(is_active)
        user.is_active = is_active

    # update user
    user.save()

    # update additional user info
    if is_pro_version():
        role = request.data.get("role")
        if role:
            User.objects.update_role(email, role)

    name = request.data.get("name")
    if name:
        profile = Profile.objects.get_profile_by_user(email)
        if profile is None:
            profile = Profile(user=email)
        profile.nickname = name
        profile.save()

    department = request.data.get("department")
    if department:
        d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email)
        if d_profile is None:
            d_profile = DetailedProfile(user=email)

        d_profile.department = department
        d_profile.save()

    quota_total_mb = request.data.get("quota_total")
    if quota_total_mb:
        quota_total = int(quota_total_mb) * get_file_size_unit('MB')
        if is_org_context(request):
            org_id = request.user.org.org_id
            seafile_api.set_org_user_quota(org_id, email, quota_total)
        else:
            seafile_api.set_user_quota(email, quota_total)
Esempio n. 11
0
def user_set_quota(request, email):
    content_type = 'application/json; charset=utf-8'
    quota_mb = int(request.POST.get('space_quota', 0))
    quota = quota_mb * get_file_size_unit('MB')

    available_quota = get_institution_available_quota(request.user.institution)
    if available_quota < quota:
        result = {}
        result['error'] = _(u'Failed to set quota: maximum quota is %d MB' % \
                            (available_quota / 10 ** 6))
        return HttpResponse(json.dumps(result), status=400, content_type=content_type)

    seafile_api.set_user_quota(email, quota)

    return HttpResponse(json.dumps({'success': True}), content_type=content_type)
Esempio n. 12
0
    def test_quota_check(self):
        """Assert the user storage quota should not be exceeded"""
        assert seafilerpc.set_user_quota(USER, 0) >= 0
        repo = TEST_REPO
        rootdir = repo.get_dir('/')
        testfn = 'elpa.tar.gz'
        testfpath = os.path.join(os.path.dirname(__file__), 'data', testfn)
        testfilesize = os.stat(testfpath).st_size
        rootdir.upload_local_file(testfpath)

        _wait_repo_size_recompute(repo, testfilesize)
        with _set_quota(USER, testfilesize):
            with self.assertRaises(WebDAVOperationFailed) as cm:
                davclient.repo_uploadfile(repo, testfpath,
                                          '/%s' % randstring())
            self.assertEqual(
                cm.exception.actual_code, 403,
                'the operation should fail because quota is full')

            # Attempts to create empty files should also fail
            with self.assertRaises(WebDAVOperationFailed) as cm:
                empty_fileobj = io.BytesIO()
                davclient.repo_uploadfile(repo, empty_fileobj,
                                          '/%s' % randstring())
            self.assertEqual(
                cm.exception.actual_code, 403,
                'the operation should fail because quota is full')

        # After the quota restored, the upload should succeed
        repo_fpath = '/%s' % randstring()
        davclient.repo_uploadfile(repo, testfpath, repo_fpath)
        with open(testfpath, 'r') as fp:
            assert fp.read() == repo.get_file(repo_fpath).get_content()
Esempio n. 13
0
    def test_quota_check(self):
        """Assert the user storage quota should not be exceeded"""
        assert seafilerpc.set_user_quota(USER, 0) >= 0
        repo = TEST_REPO
        rootdir = repo.get_dir('/')
        testfn = 'elpa.tar.gz'
        testfpath = os.path.join(os.path.dirname(__file__), 'data', testfn)
        testfilesize = os.stat(testfpath).st_size
        rootdir.upload_local_file(testfpath)

        _wait_repo_size_recompute(repo, testfilesize)
        with _set_quota(USER, testfilesize):
            with self.assertRaises(WebDAVOperationFailed) as cm:
                davclient.repo_uploadfile(repo, testfpath, '/%s' % randstring())
            self.assertEqual(cm.exception.actual_code, 403,
                             'the operation should fail because quota is full')

            # Attempts to create empty files should also fail
            with self.assertRaises(WebDAVOperationFailed) as cm:
                empty_fileobj = io.BytesIO()
                davclient.repo_uploadfile(repo, empty_fileobj, '/%s' % randstring())
            self.assertEqual(cm.exception.actual_code, 403,
                             'the operation should fail because quota is full')

        # After the quota restored, the upload should succeed
        repo_fpath = '/%s' % randstring()
        davclient.repo_uploadfile(repo, testfpath, repo_fpath)
        with open(testfpath, 'r') as fp:
            assert fp.read() == repo.get_file(repo_fpath).get_content()
Esempio n. 14
0
def user_info(request, email):
    if request.method == 'POST':
        result = {}
        content_type = 'application/json; charset=utf-8'

        f = SetUserQuotaForm(request.POST)
        if f.is_valid():
            email = f.cleaned_data['email']
            quota_mb = f.cleaned_data['quota']
            quota = quota_mb * (1 << 20)

            try:
                seafile_api.set_user_quota(email, quota)
            except:
                result['error'] = _(u'Failed to set quota: internal error')
                return HttpResponse(json.dumps(result),
                                    content_type=content_type)

            result['success'] = True
            return HttpResponse(json.dumps(result), content_type=content_type)
        else:
            result['error'] = str(f.errors.values()[0])
            return HttpResponse(json.dumps(result), content_type=content_type)

    owned_repos = []

    owned_repos = seafile_api.get_owned_repo_list(email)

    quota = seafile_api.get_user_quota(email)
    quota_usage = 0
    share_usage = 0
    my_usage = 0
    my_usage = seafile_api.get_user_self_usage(email)
    if CALC_SHARE_USAGE:
        try:
            share_usage = seafile_api.get_user_share_usage(email)
        except SearpcError, e:
            logger.error(e)
            share_usage = 0
        quota_usage = my_usage + share_usage
Esempio n. 15
0
def user_info(request, email):
    if request.method == 'POST':
        result = {}
        content_type = 'application/json; charset=utf-8'

        f = SetUserQuotaForm(request.POST)
        if f.is_valid():
            email = f.cleaned_data['email']
            quota_mb = f.cleaned_data['quota']
            quota = quota_mb * (1 << 20)

            try:
                seafile_api.set_user_quota(email, quota)
            except:
                result['error'] = _(u'Failed to set quota: internal error')
                return HttpResponse(json.dumps(result), content_type=content_type)

            result['success'] = True
            return HttpResponse(json.dumps(result), content_type=content_type)
        else:
            result['error'] = str(f.errors.values()[0])
            return HttpResponse(json.dumps(result), content_type=content_type)

    owned_repos = []

    owned_repos = seafile_api.get_owned_repo_list(email)

    quota = seafile_api.get_user_quota(email)
    quota_usage = 0
    share_usage = 0
    my_usage = 0
    my_usage = seafile_api.get_user_self_usage(email)
    if CALC_SHARE_USAGE:
        try:
            share_usage = seafile_api.get_user_share_usage(email)
        except SearpcError, e:
            logger.error(e)
            share_usage = 0
        quota_usage = my_usage + share_usage
Esempio n. 16
0
def create_user_info(request, email, role, nickname, contact_email, quota_total_mb):
    # update additional user info

    if is_pro_version() and role:
        User.objects.update_role(email, role)

    if nickname is not None:
        Profile.objects.add_or_update(email, nickname)
        key = normalize_cache_key(nickname, NICKNAME_CACHE_PREFIX)
        cache.set(key, nickname, NICKNAME_CACHE_TIMEOUT)

    if contact_email is not None:
        Profile.objects.add_or_update(email, contact_email=contact_email)
        key = normalize_cache_key(email, CONTACT_CACHE_PREFIX)
        cache.set(key, contact_email, CONTACT_CACHE_TIMEOUT)

    if quota_total_mb:
        quota_total = int(quota_total_mb) * get_file_size_unit('MB')
        if is_org_context(request):
            org_id = request.user.org.org_id
            seafile_api.set_org_user_quota(org_id, email, quota_total)
        else:
            seafile_api.set_user_quota(email, quota_total)
Esempio n. 17
0
def user_set_quota(request, email):
    if not request.is_ajax() or request.method != 'POST':
        raise Http404

    content_type = 'application/json; charset=utf-8'
    result = {}

    f = SetUserQuotaForm(request.POST)
    if f.is_valid():
        email = f.cleaned_data['email']
        quota_mb = f.cleaned_data['quota']
        quota = quota_mb * (1 << 20)

        try:
            seafile_api.set_user_quota(email, quota)
        except:
            result['error'] = _(u'Failed to set quota: internal error')
            return HttpResponse(json.dumps(result), status=500, content_type=content_type)

        result['success'] = True
        return HttpResponse(json.dumps(result), content_type=content_type)
    else:
        result['error'] = str(f.errors.values()[0])
        return HttpResponse(json.dumps(result), status=400, content_type=content_type)
Esempio n. 18
0
def update_user_info(request, user):

    # update basic user info
    password = request.data.get("password")
    if password:
        user.set_password(password)

    is_staff = request.data.get("is_staff")
    if is_staff:
        is_staff = to_python_boolean(is_staff)
        user.is_staff = is_staff

    is_active = request.data.get("is_active")
    if is_active:
        is_active = to_python_boolean(is_active)
        user.is_active = is_active

    # update user
    user.save()

    email = user.username

    # update additional user info
    if is_pro_version():
        role = request.data.get("role")
        if role:
            User.objects.update_role(email, role)

    name = request.data.get("name")
    if name:
        profile = Profile.objects.get_profile_by_user(email)
        if profile is None:
            profile = Profile(user=email)
        profile.nickname = name
        profile.save()

    # update account login_id
    login_id = request.data.get("login_id", None)
    if login_id is not None:
        login_id = login_id.strip()
        profile = Profile.objects.get_profile_by_user(email)
        if profile is None:
            profile = Profile(user=email)
        profile.login_id = None if login_id == "" else login_id
        profile.save()

    reference_id = request.data.get("reference_id", None)
    if reference_id is not None:
        reference_id = reference_id.strip()
        ccnet_api.set_reference_id(email, reference_id)

    department = request.data.get("department")
    if department:
        d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email)
        if d_profile is None:
            d_profile = DetailedProfile(user=email)

        d_profile.department = department
        d_profile.save()

    quota_total_mb = request.data.get("quota_total")
    if quota_total_mb:
        quota_total = int(quota_total_mb) * get_file_size_unit('MB')
        if is_org_context(request):
            org_id = request.user.org.org_id
            seafile_api.set_org_user_quota(org_id, email, quota_total)
        else:
            seafile_api.set_user_quota(email, quota_total)
Esempio n. 19
0
    def _update_account_additional_info(self, request, email):

        # update account name
        name = request.data.get("name", None)
        if name is not None:
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)
            profile.nickname = name
            profile.save()

        # update account list_in_address_book
        list_in_address_book = request.data.get("list_in_address_book", None)
        if list_in_address_book is not None:
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)

            profile.list_in_address_book = list_in_address_book.lower() == 'true'
            profile.save()

        # update account loginid
        loginid = request.data.get("login_id", '').strip()
        if loginid != '':
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)
            profile.login_id = loginid
            profile.save()

        # update account detailed profile
        department = request.data.get("department", None)
        if department is not None:
            d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email)
            if d_profile is None:
                d_profile = DetailedProfile(user=email)

            d_profile.department = department
            d_profile.save()

        # update user quota
        space_quota_mb = request.data.get("storage", None)
        if space_quota_mb is not None:
            space_quota = int(space_quota_mb) * get_file_size_unit('MB')
            if is_org_context(request):
                org_id = request.user.org.org_id
                seaserv.seafserv_threaded_rpc.set_org_user_quota(org_id,
                        email, space_quota)
            else:
                seafile_api.set_user_quota(email, space_quota)

        # update user institution
        institution = request.data.get("institution", None)
        if institution is not None:
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)
            profile.institution = institution
            profile.save()

        # update is_trial
        is_trial = request.data.get("is_trial", None)
        if is_trial is not None:
            try:
                from seahub_extra.trialaccount.models import TrialAccount
            except ImportError:
                pass
            else:
                if is_trial is True:
                    expire_date = timezone.now() + relativedelta(days=7)
                    TrialAccount.object.create_or_update(email, expire_date)
                else:
                    TrialAccount.objects.filter(user_or_org=email).delete()
Esempio n. 20
0
    def _update_account_additional_info(self, request, email):

        # update account name
        name = request.data.get("name", None)
        if name is not None:
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)
            profile.nickname = name
            profile.save()

        # update account list_in_address_book
        list_in_address_book = request.data.get("list_in_address_book", None)
        if list_in_address_book is not None:
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)

            profile.list_in_address_book = list_in_address_book.lower(
            ) == 'true'
            profile.save()

        # update account loginid
        loginid = request.data.get("login_id", '').strip()
        if loginid != '':
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)
            profile.login_id = loginid
            profile.save()

        # update account detailed profile
        department = request.data.get("department", None)
        if department is not None:
            d_profile = DetailedProfile.objects.get_detailed_profile_by_user(
                email)
            if d_profile is None:
                d_profile = DetailedProfile(user=email)

            d_profile.department = department
            d_profile.save()

        # update user quota
        space_quota_mb = request.data.get("storage", None)
        if space_quota_mb is not None:
            space_quota = int(space_quota_mb) * get_file_size_unit('MB')
            if is_org_context(request):
                org_id = request.user.org.org_id
                seaserv.seafserv_threaded_rpc.set_org_user_quota(
                    org_id, email, space_quota)
            else:
                seafile_api.set_user_quota(email, space_quota)

        # update user institution
        institution = request.data.get("institution", None)
        if institution is not None:
            profile = Profile.objects.get_profile_by_user(email)
            if profile is None:
                profile = Profile(user=email)
            profile.institution = institution
            profile.save()
Esempio n. 21
0
def update_user_info(request, user):

    # update basic user info
    password = request.data.get("password")
    if password:
        user.set_password(password)

    is_staff = request.data.get("is_staff")
    if is_staff:
        is_staff = to_python_boolean(is_staff)
        user.is_staff = is_staff

    is_active = request.data.get("is_active")
    if is_active:
        is_active = to_python_boolean(is_active)
        user.is_active = is_active

    # update user
    user.save()

    email = user.username

    # update additional user info
    if is_pro_version():
        role = request.data.get("role")
        if role:
            User.objects.update_role(email, role)

    nickname = request.data.get("name", None)
    if nickname is not None:
        Profile.objects.add_or_update(email, nickname)

    # update account login_id
    login_id = request.data.get("login_id", None)
    if login_id is not None:
        Profile.objects.add_or_update(email, login_id=login_id)

    # update account contact email
    contact_email = request.data.get('contact_email', None)
    if contact_email is not None:
        Profile.objects.add_or_update(email, contact_email=contact_email)
        key = normalize_cache_key(email, CONTACT_CACHE_PREFIX)
        cache.set(key, contact_email, CONTACT_CACHE_TIMEOUT)

    reference_id = request.data.get("reference_id", None)
    if reference_id is not None:
        if reference_id.strip():
            ccnet_api.set_reference_id(email, reference_id.strip())
        else:
            # remove reference id
            ccnet_api.set_reference_id(email, None)

    department = request.data.get("department")
    if department:
        d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email)
        if d_profile is None:
            d_profile = DetailedProfile(user=email)

        d_profile.department = department
        d_profile.save()

    quota_total_mb = request.data.get("quota_total")
    if quota_total_mb:
        quota_total = int(quota_total_mb) * get_file_size_unit('MB')
        if is_org_context(request):
            org_id = request.user.org.org_id
            seafile_api.set_org_user_quota(org_id, email, quota_total)
        else:
            seafile_api.set_user_quota(email, quota_total)
Esempio n. 22
0
    def post(self, request):
        """ Set user quota, set user institution, delete users, in batch.

        Permission checking:
        1. admin user.
        """

        # argument check
        emails = request.POST.getlist('email', None)
        if not emails:
            error_msg = 'email invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        operation = request.POST.get('operation', None)
        if operation not in ('set-quota', 'delete-user', 'set-institution'):
            error_msg = "operation can only be 'set-quota', 'delete-user', or 'set-institution'."
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        result = {}
        result['failed'] = []
        result['success'] = []

        existed_users = []
        for email in emails:
            try:
                user = User.objects.get(email=email)
                existed_users.append(user)
            except User.DoesNotExist:
                result['failed'].append({
                    'email': email,
                    'error_msg': 'User %s not found.' % email
                    })
                continue

        if operation == 'set-quota':
            quota_total_mb = request.POST.get('quota_total', None)
            if not quota_total_mb:
                error_msg = 'quota_total invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            try:
                quota_total_mb = int(quota_total_mb)
            except ValueError:
                error_msg = _('must be an integer that is greater than or equal to 0.')
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if quota_total_mb < 0:
                error_msg = _('Space quota is too low (minimum value is 0)')
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            quota_total_byte = quota_total_mb * get_file_size_unit('MB')

            for user in existed_users:
                email = user.email
                try:
                    seafile_api.set_user_quota(email, quota_total_byte)
                except Exception as e:
                    logger.error(e)
                    result['failed'].append({
                        'email': email,
                        'error_msg': 'Internal Server Error'
                        })
                    continue

                result['success'].append({
                    'email': email,
                    'quota_total': seafile_api.get_user_quota(email),
                })

        if operation == 'delete-user':
            for user in existed_users:
                email = user.email
                try:
                    user.delete()
                except Exception as e:
                    logger.error(e)
                    result['failed'].append({
                        'email': email,
                        'error_msg': 'Internal Server Error'
                        })
                    continue

                result['success'].append({
                    'email': email,
                })

                # send admin operation log signal
                admin_op_detail = {
                    "email": email,
                }
                admin_operation.send(sender=None, admin_name=request.user.username,
                        operation=USER_DELETE, detail=admin_op_detail)

        if operation == 'set-institution':
            institution = request.POST.get('institution', None)
            if institution is None:
                error_msg = 'Institution can not be blank.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if institution != '':
                try:
                    obj_insti = Institution.objects.get(name=institution)
                except Institution.DoesNotExist:
                    error_msg = 'Institution %s does not exist' % institution
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            for user in existed_users:
                email = user.email
                profile = Profile.objects.get_profile_by_user(email)
                if profile is None:
                    profile = Profile(user=email)
                profile.institution = institution
                profile.save()
                result['success'].append({
                    'email': email,
                    'institution': institution
                })

        return Response(result)
Esempio n. 23
0
    def post(self, request):
        """ Set user quota, set user institution, delete users, in batch.

        Permission checking:
        1. admin user.
        """

        # argument check
        emails = request.POST.getlist('email', None)
        if not emails:
            error_msg = 'email invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        operation = request.POST.get('operation', None)
        if operation not in ('set-quota', 'delete-user', 'set-institution'):
            error_msg = "operation can only be 'set-quota', 'delete-user', or 'set-institution'."
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        result = {}
        result['failed'] = []
        result['success'] = []

        existed_users = []
        for email in emails:
            try:
                user = User.objects.get(email=email)
                existed_users.append(user)
            except User.DoesNotExist:
                result['failed'].append({
                    'email': email,
                    'error_msg': 'User %s not found.' % email
                    })
                continue

        if operation == 'set-quota':
            quota_total_mb = request.POST.get('quota_total', None)
            if not quota_total_mb:
                error_msg = 'quota_total invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            try:
                quota_total_mb = int(quota_total_mb)
            except ValueError:
                error_msg = _('must be an integer that is greater than or equal to 0.')
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if quota_total_mb < 0:
                error_msg = _('Space quota is too low (minimum value is 0)')
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            quota_total_byte = quota_total_mb * get_file_size_unit('MB')

            for user in existed_users:
                email = user.email
                try:
                    seafile_api.set_user_quota(email, quota_total_byte)
                except Exception as e:
                    logger.error(e)
                    result['failed'].append({
                        'email': email,
                        'error_msg': 'Internal Server Error'
                        })
                    continue

                result['success'].append({
                    'email': email,
                    'quota_total': seafile_api.get_user_quota(email),
                })

        if operation == 'delete-user':
            for user in existed_users:
                email = user.email
                try:
                    user.delete()
                except Exception as e:
                    logger.error(e)
                    result['failed'].append({
                        'email': email,
                        'error_msg': 'Internal Server Error'
                        })
                    continue

                result['success'].append({
                    'email': email,
                })

                # send admin operation log signal
                admin_op_detail = {
                    "email": email,
                }
                admin_operation.send(sender=None, admin_name=request.user.username,
                        operation=USER_DELETE, detail=admin_op_detail)

        if operation == 'set-institution':
            institution = request.POST.get('institution', None)
            if institution is None:
                error_msg = 'Institution can not be blank.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if institution != '':
                try:
                    obj_insti = Institution.objects.get(name=institution)
                except Institution.DoesNotExist:
                    error_msg = 'Institution %s does not exist' % institution
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            for user in existed_users:
                email = user.email
                profile = Profile.objects.get_profile_by_user(email)
                if profile is None:
                    profile = Profile(user=email)
                profile.institution = institution
                profile.save()
                result['success'].append({
                    'email': email,
                    'institution': institution
                })

        return Response(result)
Esempio n. 24
0
    def post(self, request):
        """ Import users from xlsx file

        Permission checking:
        1. admin user.
        """
        xlsx_file = request.FILES.get('file', None)
        if not xlsx_file:
            error_msg = 'file can not be found.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        file_type, ext = get_file_type_and_ext(xlsx_file.name)
        if ext != 'xlsx':
            error_msg = file_type_error_msg(ext, 'xlsx')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        content = xlsx_file.read()

        try:
            fs = BytesIO(content)
            wb = load_workbook(filename=fs, read_only=True)
        except Exception as e:
            logger.error(e)

        # example file is like:
        # Email    Password Name(Optional) Role(Optional) Space Quota(MB, Optional)
        # [email protected]  a        a              default        1024
        # [email protected]  b        b              default        2048

        rows = wb.worksheets[0].rows
        records = []
        # skip first row(head field).
        next(rows)
        for row in rows:
            records.append([col.value for col in row])

        if user_number_over_limit(new_users=len(records)):
            error_msg = 'The number of users exceeds the limit.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        result = {}
        result['failed'] = []
        result['success'] = []
        for record in records:
            if record[0]:
                email = record[0].strip()
                if not is_valid_username(email):
                    result['failed'].append({
                        'email': email,
                        'error_msg': 'email %s invalid.' % email
                    })
                    continue
            else:
                result['failed'].append({
                    'email': '',
                    'error_msg': 'email invalid.'
                })
                continue

            if record[1]:
                password = str(record[1]).strip()
                if not password:
                    result['failed'].append({
                        'email': email,
                        'error_msg': 'password invalid.'
                    })
                    continue
            else:
                result['failed'].append({
                    'email': email,
                    'error_msg': 'password invalid.'
                })
                continue
            
            vid = get_virtual_id_by_email(email)
            try:
                User.objects.get(email=vid)
                result['failed'].append({
                    'email': email,
                    'error_msg': 'user %s exists.' % email
                })
                continue
            except User.DoesNotExist:
                pass

            user = User.objects.create_user(email, password, is_staff=False, is_active=True)
            virtual_id = get_virtual_id_by_email(email)

            if config.FORCE_PASSWORD_CHANGE:
                UserOptions.objects.set_force_passwd_change(virtual_id)

            # update the user's optional info
            # update nikename
            nickname = email.split('@')[0]
            try:
                if record[2]:
                    input_nickname = str(record[2]).strip()
                    if len(input_nickname) <= 64 and '/' not in input_nickname:
                        nickname = input_nickname
                Profile.objects.add_or_update(virtual_id, nickname, '')
            except Exception as e:
                logger.error(e)
            # update role
            if record[3]:
                try:
                    role = record[3].strip()
                    if is_pro_version() and role in get_available_roles():
                        User.objects.update_role(virtual_id, role)
                except Exception as e:
                    logger.error(e)
            # update quota
            if record[4]:
                try:
                    space_quota_mb = int(record[4])
                    if space_quota_mb >= 0:
                        space_quota = int(space_quota_mb) * get_file_size_unit('MB')
                        seafile_api.set_user_quota(virtual_id, space_quota)
                except Exception as e:
                    logger.error(e)

            try:
                send_html_email_with_dj_template(
                    email, dj_template='sysadmin/user_batch_add_email.html',
                    subject=_('You are invited to join %s') % get_site_name(),
                    context={
                        'user': email2nickname(request.user.username),
                        'email': email,
                        'password': password,
                    })
            except Exception as e:
                logger.error(e)

            user_info = get_user_info(virtual_id)
            
            result['success'].append(user_info)

            # send admin operation log signal
            admin_op_detail = {
                "email": email,
            }
            admin_operation.send(sender=None, admin_name=request.user.username,
                                 operation=USER_ADD, detail=admin_op_detail)

        return Response(result)
def test_file_operation():
    t_repo_version = 1
    t_repo_id1 = api.create_repo('test_file_operation1', '', USER, passwd=None)

    create_the_file()

    # test post_file
    assert api.post_file(t_repo_id1, file_path, '/', file_name, USER) == 0
    t_file_id = api.get_file_id_by_path(t_repo_id1, '/' + file_name)
    t_file_size = len(file_content)
    assert t_file_size == api.get_file_size(t_repo_id1, t_repo_version,
                                            t_file_id)

    # test post_dir
    assert api.post_dir(t_repo_id1, '/', dir_name, USER) == 0

    # test copy_file (synchronize)
    t_copy_file_result1 = api.copy_file(t_repo_id1, '/', file_name, t_repo_id1,
                                        '/', new_file_name, USER, 0, 1)
    assert t_copy_file_result1
    assert t_copy_file_result1.task_id is None
    assert not t_copy_file_result1.background
    t_file_id = api.get_file_id_by_path(t_repo_id1, '/' + new_file_name)
    assert t_file_size == api.get_file_size(t_repo_id1, t_repo_version,
                                            t_file_id)

    # test copy_file (asynchronous)
    t_repo_id2 = api.create_repo('test_file_operation2', '', USER, passwd=None)
    usage = api.get_user_self_usage(USER)
    api.set_user_quota(USER, usage + 1)
    t_copy_file_result2 = api.copy_file(t_repo_id1, '/', file_name, t_repo_id2,
                                        '/', file_name, USER, 1, 0)
    assert t_copy_file_result2
    assert t_copy_file_result2.background
    while True:
        time.sleep(0.1)
        t_copy_task = api.get_copy_task(t_copy_file_result2.task_id)
        assert t_copy_task.failed
        assert t_copy_task.failed_reason == 'Quota is full'
        if t_copy_task.failed:
            break

    api.set_user_quota(USER, -1)
    t_copy_file_result2 = api.copy_file(t_repo_id1, '/', file_name, t_repo_id2,
                                        '/', file_name, USER, 1, 0)
    assert t_copy_file_result2
    assert t_copy_file_result2.task_id
    assert t_copy_file_result2.background
    while True:
        time.sleep(0.1)
        t_copy_task = api.get_copy_task(t_copy_file_result2.task_id)
        if t_copy_task.successful:
            break
    t_file_id = api.get_file_id_by_path(t_repo_id2, '/' + file_name)
    assert t_file_size == api.get_file_size(t_repo_id2, t_repo_version,
                                            t_file_id)

    # test move_file (synchronize)
    t_move_file_info1 = api.get_dirent_by_path(t_repo_id1, '/' + new_file_name)
    t_move_file_result1 = api.move_file(t_repo_id1, '/', new_file_name,
                                        t_repo_id1, '/' + dir_name,
                                        new_file_name, 1, USER, 0, 1)
    assert t_move_file_result1
    t_move_file_info2 = api.get_dirent_by_path(
        t_repo_id1, '/' + dir_name + '/' + new_file_name)
    assert t_move_file_info1.mtime == t_move_file_info2.mtime
    t_file_id = api.get_file_id_by_path(t_repo_id1, '/' + new_file_name)
    assert t_file_id is None

    # test move_file (synchronize)
    t_move_file_result1 = api.move_file(t_repo_id1, '/' + dir_name,
                                        new_file_name, t_repo_id1, '/',
                                        new_file_name_2, 1, USER, 0, 1)
    assert t_move_file_result1
    t_file_id = api.get_file_id_by_path(t_repo_id1,
                                        '/' + dir_name + '/' + new_file_name)
    assert t_file_id is None

    # test move_file (asynchronous)
    usage = api.get_user_self_usage(USER)
    api.set_user_quota(USER, usage + 1)
    t_move_file_result2 = api.move_file(t_repo_id1, '/', file_name, t_repo_id2,
                                        '/', new_file_name, 1, USER, 1, 0)
    assert t_move_file_result2
    assert t_move_file_result2.task_id
    assert t_move_file_result2.background
    while True:
        time.sleep(0.1)
        t_move_task = api.get_copy_task(t_move_file_result2.task_id)
        assert t_move_task.failed
        assert t_move_task.failed_reason == 'Quota is full'
        if t_move_task.failed:
            break

    api.set_user_quota(USER, -1)
    t_move_file_result2 = api.move_file(t_repo_id1, '/', file_name, t_repo_id2,
                                        '/', new_file_name, 1, USER, 1, 0)
    assert t_move_file_result2
    assert t_move_file_result2.task_id
    assert t_move_file_result2.background
    while True:
        time.sleep(0.1)
        t_move_task = api.get_copy_task(t_move_file_result2.task_id)
        if t_move_task.successful:
            break
    t_file_id = api.get_file_id_by_path(t_repo_id2, '/' + new_file_name)
    assert t_file_size == api.get_file_size(t_repo_id2, t_repo_version,
                                            t_file_id)

    # test post_empty_file
    assert api.post_empty_file(t_repo_id1, '/' + dir_name, empty_file_name,
                               USER) == 0
    t_file_id = api.get_file_id_by_path(t_repo_id1,
                                        '/' + dir_name + '/' + empty_file_name)
    assert api.get_file_size(t_repo_id1, t_repo_version, t_file_id) == 0

    # test rename_file
    assert api.rename_file(t_repo_id1, '/' + dir_name, empty_file_name,
                           new_empty_file_name, USER) == 0

    #test put_file
    t_new_file_id = api.put_file(t_repo_id1, file_path, '/' + dir_name,
                                 new_empty_file_name, USER, None)
    assert t_new_file_id

    # test get_file_revisions
    t_commit_list = api.get_file_revisions(t_repo_id2, None, '/' + file_name,
                                           2)
    assert t_commit_list
    assert len(t_commit_list) == 2
    assert t_commit_list[0].creator_name == USER

    # test del_file
    assert api.del_file(t_repo_id2, '/', file_name, USER) == 0

    # test get_deleted
    t_deleted_file_list = api.get_deleted(t_repo_id2, 1)
    assert t_deleted_file_list
    assert len(t_deleted_file_list) == 2
    assert t_deleted_file_list[0].obj_name == file_name
    assert t_deleted_file_list[0].basedir == '/'

    # test del a non-exist file. should return 0.
    assert api.del_file(t_repo_id2, '/', file_name, USER) == 0

    assert api.del_file(t_repo_id1, '/' + dir_name, new_empty_file_name,
                        USER) == 0
    assert api.del_file(t_repo_id1, '/' + dir_name, new_file_name, USER) == 0
    assert api.del_file(t_repo_id2, '/', new_file_name, USER) == 0
    assert api.del_file(t_repo_id1, '/', new_file_name_2, USER) == 0

    time.sleep(1)
    api.remove_repo(t_repo_id1)