Skip to content

Commit

Permalink
Merge pull request haiwen#1507 from haiwen/admin-user-batch-api
Browse files Browse the repository at this point in the history
admin user batch api
  • Loading branch information
xiez authored Mar 14, 2017
2 parents d1f3dd1 + 287bad0 commit 5d08286
Show file tree
Hide file tree
Showing 2 changed files with 132 additions and 0 deletions.
129 changes: 129 additions & 0 deletions seahub/api2/endpoints/admin/batch_set_user_quota.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Copyright (c) 2012-2016 Seafile Ltd.

import logging
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from django.utils.translation import ugettext as _

from seaserv import seafile_api

from seahub.api2.authentication import TokenAuthentication
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.utils import api_error

from seahub.base.accounts import User
from seahub.utils.file_size import get_file_size_unit

logger = logging.getLogger(__name__)

# user fields returned by admin users api
# {
# "email": "email",
# "name": "email2nickname(email)",
# "contact_email": Profile.objects.get_contact_email_by_user(email),
# "is_admin": True, # False
# "active": True, # False
# "role": "default", # guest
# "quota_total": 100000,
# "quota_used": 50000,
# "created_at": "2017-02-23T15:51:21+08:00",
# "last_login": "2017-02-27T15:51:21+08:00",
# }


class AdminUsersBatch(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
throttle_classes = (UserRateThrottle,)
permission_classes = (IsAdminUser,)

def post(self, request):
""" Set user quota / 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'):
error_msg = "operation can only be 'set-quota' or 'delete-user'."
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,
})

return Response(result)
3 changes: 3 additions & 0 deletions seahub/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
from seahub.api2.endpoints.admin.group_libraries import AdminGroupLibraries, AdminGroupLibrary
from seahub.api2.endpoints.admin.group_members import AdminGroupMembers, AdminGroupMember
from seahub.api2.endpoints.admin.shares import AdminShares
from seahub.api2.endpoints.admin.batch_set_user_quota import AdminUsersBatch

# Uncomment the next two lines to enable the admin:
#from django.contrib import admin
Expand Down Expand Up @@ -213,6 +214,8 @@
url(r'^api/v2.1/admin/trash-libraries/(?P<repo_id>[-0-9a-f]{36})/$', AdminTrashLibrary.as_view(), name='api-v2.1-admin-trash-library'),
url(r'^api/v2.1/admin/shares/$', AdminShares.as_view(), name='api-v2.1-admin-shares'),

url(r'^api/v2.1/admin/users/batch/$', AdminUsersBatch.as_view(), name='api-v2.1-admin-users-batch'),

(r'^avatar/', include('seahub.avatar.urls')),
(r'^notification/', include('seahub.notifications.urls')),
(r'^contacts/', include('seahub.contacts.urls')),
Expand Down

0 comments on commit 5d08286

Please sign in to comment.