Эх сурвалжийг харах

HUE-4278 [useradmin] Provide basic useradmin API

/useradmin/api/get_users

{
	"status": 0,
	"users": [{
		"username": "hue",
		"superuser": false,
		"is_active": false,
		"id": 1100713,
		"groups": ["default"]
	}, {
		"username": "admin",
		"superuser": true,
		"is_active": true,
		"id": 1,
		"groups": ["default"]
	}, {
		"username": "hive",
		"superuser": false,
		"is_active": true,
		"id": 1100714,
		"groups": ["default", "hive"]
	}]
}
Jenny Kim 9 жил өмнө
parent
commit
24e59d662f

+ 92 - 0
apps/useradmin/src/useradmin/api.py

@@ -0,0 +1,92 @@
+#!/usr/bin/env python
+# Licensed to Cloudera, Inc. under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  Cloudera, Inc. licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+
+from django.contrib.auth.models import User, Group
+
+from desktop.lib.django_util import JsonResponse
+from desktop.lib.i18n import smart_unicode
+
+
+LOG = logging.getLogger(__name__)
+
+
+def error_handler(view_fn):
+  def decorator(*args, **kwargs):
+    response = {}
+    try:
+      return view_fn(*args, **kwargs)
+    except Exception, e:
+      LOG.exception('Error running %s' % view_fn)
+      response['status'] = -1
+      response['message'] = smart_unicode(e)
+    return JsonResponse(response)
+  return decorator
+
+
+@error_handler
+def get_users(request):
+  """
+  Returns all users with username, ID, groups, active and superuser status by default.
+  Optional params:
+    username=<username> - Filter by username
+    groups=<groupnames> - List of group names to filter on (additive "OR" search)
+    is_active=true         - Only return active users (defaults to all users)
+  """
+  response = {
+    'users': []
+  }
+
+  username = request.GET.get('username', '').lower()
+  groups = request.GET.getlist('groups')
+  is_active = request.GET.get('is_active', '').lower()
+
+  users = User.objects
+
+  if is_active and is_active == 'true':
+    users = users.filter(is_active=True)
+
+  if username:
+    users = users.filter(username=username)
+
+  if groups:
+    group_ids = []
+    for groupname in groups:
+      groupname = groupname.lower()
+      try:
+        group = Group.objects.get(name=groupname)
+        group_ids.append(group.id)
+      except Group.DoesNotExist, e:
+        LOG.exception("Failed to filter by group, group with name %s not found." % groupname)
+    users = users.filter(groups__in=group_ids)
+
+  users = users.order_by('username')
+
+  for user in users:
+    user = {
+      'id': user.id,
+      'username': user.username,
+      'groups': [group.name for group in user.groups.all()],
+      'is_active': user.is_active,
+      'superuser': user.is_superuser
+    }
+    response['users'].append(user)
+
+  response['status'] = 0
+
+  return JsonResponse(response)

+ 59 - 0
apps/useradmin/src/useradmin/tests_api.py

@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Licensed to Cloudera, Inc. under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  Cloudera, Inc. licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+
+from nose.tools import assert_equal, assert_false, assert_true
+from django.contrib.auth.models import User, Group
+
+from desktop.lib.django_test_util import make_logged_in_client
+
+
+class TestUseradminApi(object):
+
+  def setUp(self):
+    self.client = make_logged_in_client(username="hue_test_admin", groupname="hue_test_admin", recreate=True, is_superuser=True)
+    self.user = User.objects.get(username="hue_test_admin")
+
+    self.non_superuser_client = make_logged_in_client(username="hue_test_user", groupname="hue_test_user", recreate=True, is_superuser=False)
+    self.non_superuser = User.objects.get(username="hue_test_user")
+
+    self.test_group = Group.objects.create(name="hue_test_group")
+    self.non_superuser.groups.add(self.test_group)
+    self.non_superuser.save()
+
+  def test_get_users(self):
+    # Test get all users
+    response = self.client.get('/useradmin/api/get_users/')
+    data = json.loads(response.content)
+    assert_equal(0, data['status'])
+    assert_true('users' in data)
+    assert_true(self.user.username in [user['username'] for user in data['users']])
+    assert_true(self.non_superuser.username in [user['username'] for user in data['users']])
+
+    # Test get by username
+    response = self.client.get('/useradmin/api/get_users/', {'username': self.non_superuser.username})
+    data = json.loads(response.content)
+    assert_equal(1, len(data['users']), data['users'])
+    assert_true(self.non_superuser.username in [user['username'] for user in data['users']])
+
+    # Test filter by group
+    response = self.client.get('/useradmin/api/get_users/', {'groups': [self.test_group.name]})
+    data = json.loads(response.content)
+    assert_equal(1, len(data['users']), data['users'])
+    assert_true(self.non_superuser.username in [user['username'] for user in data['users']])

+ 4 - 0
apps/useradmin/src/useradmin/urls.py

@@ -40,3 +40,7 @@ urlpatterns = patterns('useradmin.views',
   url(r'^users/delete', 'delete_user'),
   url(r'^users/delete', 'delete_user'),
   url(r'^groups/delete$', 'delete_group'),
   url(r'^groups/delete$', 'delete_group'),
 )
 )
+
+urlpatterns += patterns('useradmin.api',
+  url(r'^api/get_users/?', 'get_users', name='api_get_users'),
+)