def create_user(username, password, is_superuser=True): if ENABLE_ORGANIZATIONS.get(): organization = get_organization(email=username) lookup = {'email': username, 'organization': organization} else: lookup = {'username': username} LOG.info("Materializing user %s in the database" % lookup) user = User(**lookup) if password is None: user.set_unusable_password() else: user.set_password(password) user.is_superuser = is_superuser user.save() if ENABLE_ORGANIZATIONS.get(): user.is_admin = is_superuser or not organization.organizationuser_set.exists( ) or not organization.is_multi_user ensure_has_a_group(user) return user
def create_user(username, password, is_superuser=True): if ENABLE_ORGANIZATIONS.get(): organization = get_organization(email=username) attrs = {'email': username, 'organization': organization} else: attrs = {'username': username} user = User(**attrs) if password is None: user.set_unusable_password() else: user.set_password(password) user.is_superuser = is_superuser if ENABLE_ORGANIZATIONS.get(): user.is_admin = is_superuser or not organization.organizationuser_set.exists() or not organization.is_multi_user user.save() ensure_has_a_group(user) user.save() LOG.info("User %s was created." % username) return user
def is_admin(user): """ Admin of the Organization. Typically can edit users, connectors... To rename to is_org_admin at some point. If ENABLE_ORGANIZATIONS is false: - Hue superusers are automatically also admin If ENABLE_ORGANIZATIONS is true: - Hue superusers might not be admin of the organization """ is_admin = False if hasattr(user, 'is_superuser') and not ENABLE_ORGANIZATIONS.get(): is_admin = user.is_superuser if not is_admin and user.is_authenticated(): try: user = rewrite_user(user) is_admin = user.is_admin if ENABLE_ORGANIZATIONS.get( ) else user.has_hue_permission(action="superuser", app="useradmin") except Exception: LOG.exception( "Could not validate if %s is a superuser, assuming False." % user) return is_admin
def make_logged_in_client(username="******", password="******", is_superuser=True, recreate=False, groupname=None): """ Create a client with a user already logged in. Sometimes we recreate the user, because some tests like to mess with is_active and such. """ if ENABLE_ORGANIZATIONS.get() and username == 'test': username = username + '@gethue.com' try: lookup = {orm_user_lookup(): username} user = User.objects.get(**lookup) if recreate: user.delete() raise User.DoesNotExist except User.DoesNotExist: user_attrs = { 'password': password } if ENABLE_ORGANIZATIONS.get(): user_attrs['email'] = username user_attrs['organization'] = default_organization() else: user_attrs['username'] = username user_attrs['email'] = username + '@localhost' user = User.objects.create_user(**user_attrs) user.is_superuser = is_superuser user.save() else: if user.is_superuser != is_superuser: user.is_superuser = is_superuser user.save() if groupname is not None: group_attrs = {'name': groupname} if ENABLE_ORGANIZATIONS.get(): group_attrs['organization'] = default_organization() group, created = Group.objects.get_or_create(**group_attrs) if not user.groups.filter(name=group.name).exists(): user.groups.add(group) user.save() c = Client() ret = c.login(username=username, password=password) assert ret, "Login failed (user '%s')." % username return c
def make_logged_in_client(username="******", password="******", is_superuser=True, recreate=False, groupname=None, is_admin=False, request=None): """ Create a client with a user already logged in. Sometimes we recreate the user, because some tests like to mess with is_active and such. Note: could be combined with backend.create_user and other standart utils. """ request = Mock() try: user = User.objects.get(username=username) if recreate: user.delete() raise User.DoesNotExist except User.DoesNotExist: user = User.objects.create_user(username=username, password=password) user.is_superuser = is_superuser if ENABLE_ORGANIZATIONS.get(): user.is_admin = is_admin else: user.is_superuser = user.is_superuser or is_admin user.save() else: if user.is_superuser != is_superuser: user.is_superuser = is_superuser user.save() if groupname is not None: attributes = {'name': groupname} if ENABLE_ORGANIZATIONS.get(): attributes['organization'] = user.organization group, created = Group.objects.get_or_create(**attributes) if not user.groups.filter(**attributes).exists(): user.groups.add(group) user.save() c = Client() ret = c.login(username=username, password=password, request=request) assert ret, "Login failed (user '%s')." % username return c
def is_first_login_ever(self): """ Return true if no one has ever logged in.""" if ENABLE_ORGANIZATIONS.get(): # Tmp return False else: return User.objects.exclude( id=install_sample_user().id).count() == 0
def __init__(self, *args, **kwargs): super(GroupEditForm, self).__init__(*args, **kwargs) if self.instance.id: self.fields['name'].widget.attrs['readonly'] = True initial_members = User.objects.filter( groups=self.instance).order_by( 'email' if ENABLE_ORGANIZATIONS.get() else 'username') initial_perms = HuePermission.objects.filter( grouppermission__group=self.instance).order_by( 'app', 'description') else: initial_members = [] initial_perms = [] self.fields["members"] = _make_model_field( _("members"), initial_members, User.objects.order_by('username')) self.fields["permissions"] = _make_model_field( _("permissions"), initial_perms, HuePermission.objects.order_by('app', 'description')) if 'organization' in self.fields: self.fields['organization'] = forms.ChoiceField( choices=((get_user_request_organization().id, get_user_request_organization()), ), initial=get_user_request_organization())
def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) if self.instance.id and 'username' in self.fields: self.fields['username'].widget.attrs['readonly'] = True if 'desktop.auth.backend.LdapBackend' in desktop_conf.AUTH.BACKEND.get( ): self.fields['password1'].widget.attrs['readonly'] = True self.fields['password2'].widget.attrs['readonly'] = True self.fields['password_old'].widget.attrs['readonly'] = True self.fields['first_name'].widget.attrs['readonly'] = True self.fields['last_name'].widget.attrs['readonly'] = True self.fields['email'].widget.attrs['readonly'] = True if 'is_active' in self.fields: self.fields['is_active'].widget.attrs['readonly'] = True if 'is_superuser' in self.fields: self.fields['is_superuser'].widget.attrs['readonly'] = True if 'unlock_account' in self.fields: self.fields['unlock_account'].widget.attrs['readonly'] = True if 'groups' in self.fields: self.fields['groups'].widget.attrs['readonly'] = True if ENABLE_ORGANIZATIONS.get(): organization = self.instance.organization if self.instance.id else get_user_request_organization( ) self.fields['groups'].choices = [ (group.id, group.name) for group in organization.organizationgroup_set.all() ]
class Meta(django.contrib.auth.forms.UserChangeForm.Meta): model = User fields = [ "first_name", "last_name", "email", "ensure_home_directory" ] if ENABLE_ORGANIZATIONS.get(): fields.append('organization') # Because of import logic
def get_shared_search_collections(self): # Those are the ones appearing in the menu if USE_NEW_EDITOR.get(): qattr = {'owner__email__in' if ENABLE_ORGANIZATIONS.get() else 'owner__username__in': SAMPLE_USER_OWNERS} return Document2.objects.filter(Q(owner=self.user) | Q(**qattr), type='search-dashboard').order_by('-id') else: docs = Document.objects.filter(Q(owner=self.user) | Q(owner__username__in=SAMPLE_USER_OWNERS), extra='search-dashboard') return [d.content_object for d in docs.order_by('-id')]
def find_user(username): lookup = {'email': username} if ENABLE_ORGANIZATIONS.get() else {'username': username} try: user = User.objects.get(**lookup) LOG.debug("Found user %s in the db" % username) except User.DoesNotExist: user = None return user
def is_admin(user): is_admin = False if hasattr(user, 'is_superuser'): is_admin = user.is_superuser if not is_admin and user.is_authenticated() and not ENABLE_ORGANIZATIONS.get(): # Admin group not activated in organization mode. try: user = rewrite_user(user) is_admin = user.has_hue_permission(action="superuser", app="useradmin") except Exception: LOG.exception("Could not validate if %s is a superuser, assuming False." % user) return is_admin
def setUpClass(cls): if not ENABLE_ORGANIZATIONS.get(): # Skip for now as depends on DB changes raise SkipTest cls.user1 = create_user('*****@*****.**', 'test', is_superuser=False) cls.user2 = create_user('*****@*****.**', 'test', is_superuser=True) cls.user3 = create_user('*****@*****.**', 'test', is_superuser=False) cls.user4 = create_user('*****@*****.**', 'test', is_superuser=False) cls.client1 = make_logged_in_client(username=cls.user1.username) cls.client2 = make_logged_in_client(username=cls.user2.username)
def _has_access(self, fs): from desktop.auth.backend import rewrite_user # Avoid cyclic loop try: filebrowser_action = fs.filebrowser_action() #if not filebrowser_action (hdfs) then handle permission via doas else check permission in hue if not filebrowser_action: return True lookup = {'email' if ENABLE_ORGANIZATIONS.get() else 'username': self.getuser()} user = rewrite_user(User.objects.get(**lookup)) return user.is_authenticated() and user.is_active and (is_admin(user) or not filebrowser_action or user.has_hue_permission(action=filebrowser_action, app="filebrowser")) except User.DoesNotExist: LOG.exception('proxyfs.has_access()') return False
def authenticate(self, request): authorization_header = request.META.get('HTTP_AUTHORIZATION') if not authorization_header: LOG.debug('JwtAuthentication: no authorization header') return None header, access_token = authorization_header.split(' ') if header != 'Bearer': LOG.debug('JwtAuthentication: no Bearer header') return None if not access_token: LOG.debug('JwtAuthentication: no Bearer value') return None LOG.debug('JwtAuthentication: got access token %s' % access_token) try: payload = jwt.decode( access_token, 'secret', algorithms=["RS256"], verify=AUTH.VERIFY_CUSTOM_JWT.get() ) except jwt.DecodeError: raise exceptions.AuthenticationFailed('JwtAuthentication: Invalid token') except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('JwtAuthentication: Token expired') except Exception as e: raise exceptions.AuthenticationFailed(e) if payload.get('user') is None: LOG.debug('JwtAuthentication: no user ID in token') return None LOG.debug('JwtAuthentication: got user ID %s and tenant ID %s' % (payload.get('user'), payload.get('tenantId'))) user = find_or_create_user(payload.get('user'), is_superuser=False) ensure_has_a_group(user) user = rewrite_user(user) # Persist the token (to reuse for communicating with external services as the user, e.g. Impala) if ENABLE_ORGANIZATIONS.get(): user.token = access_token else: user.profile.update_data({'jwt_access_token': access_token}) user.profile.save() return (user, None)
def get_default_user_group(**kwargs): default_user_group = DEFAULT_USER_GROUP.get() if default_user_group is None: return None if ENABLE_ORGANIZATIONS.get(): group, created = Group.objects.get_or_create(name=default_user_group, organization=default_organization()) else: group, created = Group.objects.get_or_create(name=default_user_group) if created: group.save() return group
def _fitered_queryset(queryset, by_owner=False): request = CrequestMiddleware.get_request() # Avoid infinite recursion on very first retrieval of the user if ENABLE_ORGANIZATIONS.get() and \ request and hasattr(request, 'user') and hasattr(request.user, '_wrapped') and type(request.user._wrapped) is not object and \ request.user.is_authenticated(): if by_owner: filters = {'owner__organization': request.user.organization} else: filters = {'organization': request.user.organization} queryset = queryset.filter(**filters) return queryset
def get_default_user_group(**kwargs): default_user_group = DEFAULT_USER_GROUP.get() if default_user_group is None: return None attributes = {'name': default_user_group} if ENABLE_ORGANIZATIONS.get() and kwargs.get('user'): attributes['organization'] = kwargs['user'].organization group, created = Group.objects.get_or_create(**attributes) if created: group.save() return group
def create_user(username, password, is_superuser=True): if ENABLE_ORGANIZATIONS.get(): organization = get_organization(email=username) lookup = {'email': username, 'organization': organization} else: lookup = {'username': username} LOG.info("Materializing user %s in the database" % lookup) user = User(**lookup) if password is None: user.set_unusable_password() else: user.set_password(password) user.is_superuser = is_superuser user.save() return user
def __str__(self): return '%s (%s)' % (self.name, self.dialect) def to_dict(self): return { 'id': self.id, 'type': str(self.id), 'name': self.name, 'description': self.description, 'dialect': self.dialect, 'settings': self.settings, 'last_modified': self.last_modified } if ENABLE_ORGANIZATIONS.get(): class ConnectorManager(models.Manager): def get_queryset(self): """Restrict to only organization's connectors""" queryset = super(ConnectorManager, self).get_queryset() return _fitered_queryset(queryset) def natural_key(self): return ( self.organization, self.name, ) class Connector(BaseConnector): organization = models.ForeignKey('useradmin.Organization',
def authenticate(self, request): authorization_header = request.META.get('HTTP_AUTHORIZATION') if not authorization_header: LOG.debug('JwtAuthentication: no authorization header from %s' % request.path) return None header, access_token = authorization_header.split(' ') if header != 'Bearer': LOG.debug('JwtAuthentication: no Bearer header from %s' % request.path) return None if not access_token: LOG.debug('JwtAuthentication: no Bearer value from %s' % request.path) return None LOG.debug('JwtAuthentication: got access token from %s: %s' % (request.path, access_token)) public_key_pem = '' if AUTH.JWT.VERIFY.get(): public_key_pem = self._handle_public_key(access_token) params = { 'jwt': access_token, 'key': public_key_pem, 'issuer': AUTH.JWT.ISSUER.get(), 'audience': AUTH.JWT.AUDIENCE.get(), 'algorithms': ["RS256"] } if sys.version_info[0] > 2: params['options'] = {'verify_signature': AUTH.JWT.VERIFY.get()} else: params['verify'] = AUTH.JWT.VERIFY.get() try: payload = jwt.decode(**params) except jwt.DecodeError: LOG.error('JwtAuthentication: Invalid token') raise exceptions.AuthenticationFailed( 'JwtAuthentication: Invalid token') except jwt.ExpiredSignatureError: LOG.error('JwtAuthentication: Token expired') raise exceptions.AuthenticationFailed( 'JwtAuthentication: Token expired') except jwt.InvalidIssuerError: LOG.error('JwtAuthentication: issuer not match') raise exceptions.AuthenticationFailed( 'JwtAuthentication: issuer not matching') except jwt.InvalidAudienceError: LOG.error('JwtAuthentication: audience not match or no audience') raise exceptions.AuthenticationFailed( 'JwtAuthentication: audience not matching or no audience') except Exception as e: LOG.error('JwtAuthentication: %s' % str(e)) raise exceptions.AuthenticationFailed(e) if payload.get('user') is None: LOG.debug('JwtAuthentication: no user ID in token') return None LOG.debug('JwtAuthentication: got user ID %s and tenant ID %s' % (payload.get('user'), payload.get('tenantId'))) user = find_or_create_user(payload.get('user'), is_superuser=False) ensure_has_a_group(user) user = rewrite_user(user) # Persist the token (to reuse for communicating with external services as the user, e.g. Impala) if ENABLE_ORGANIZATIONS.get(): user.token = access_token else: user.profile.update_data({'jwt_access_token': access_token}) user.profile.save() return (user, None)
def dt_login(request, from_modal=False): if request.method == 'GET': redirect_to = request.GET.get('next', '/') else: redirect_to = request.POST.get('next', '/') is_first_login_ever = first_login_ever() backend_names = auth_forms.get_backend_names() is_active_directory = auth_forms.is_active_directory() is_ldap_option_selected = 'server' not in request.POST or request.POST.get('server') == 'LDAP' or \ request.POST.get('server') in auth_forms.get_ldap_server_keys() if is_active_directory and is_ldap_option_selected: UserCreationForm = auth_forms.LdapUserCreationForm AuthenticationForm = auth_forms.LdapAuthenticationForm else: UserCreationForm = auth_forms.UserCreationForm if 'ImpersonationBackend' in backend_names: AuthenticationForm = ImpersonationAuthenticationForm else: AuthenticationForm = auth_forms.AuthenticationForm if ENABLE_ORGANIZATIONS.get(): UserCreationForm = OrganizationUserCreationForm AuthenticationForm = OrganizationAuthenticationForm if request.method == 'POST': request.audit = { 'operation': 'USER_LOGIN', 'username': request.POST.get('username', request.POST.get('email')) } # For first login, need to validate user info! first_user_form = is_first_login_ever and UserCreationForm(data=request.POST) or None first_user = first_user_form and first_user_form.is_valid() if first_user or not is_first_login_ever: auth_form = AuthenticationForm(data=request.POST) if auth_form.is_valid(): # Must login by using the AuthenticationForm. It provides 'backend' on the User object. user = auth_form.get_user() userprofile = get_profile(user) login(request, user) # If Test cookie exists , it should be deleted if request.session.test_cookie_worked(): request.session.delete_test_cookie() if request.fs is None: request.fs = fsmanager.get_filesystem(request.fs_ref) try: ensure_home_directory(request.fs, user) except (IOError, WebHdfsException) as e: LOG.error('Could not create home directory at login for %s.' % user, exc_info=e) if require_change_password(userprofile): return HttpResponseRedirect('/hue' + reverse('useradmin:useradmin.views.edit_user', kwargs={'username': user.username})) userprofile.first_login = False userprofile.last_activity = datetime.now() if userprofile.creation_method == UserProfile.CreationMethod.EXTERNAL: # This is to fix a bug in Hue 4.3 userprofile.creation_method = UserProfile.CreationMethod.EXTERNAL.name userprofile.update_data({'auth_backend': user.backend}) userprofile.save() msg = 'Successful login for user: %s' % user.username request.audit['operationText'] = msg access_warn(request, msg) if from_modal or request.GET.get('fromModal', 'false') == 'true': return JsonResponse({'auth': True}) else: return HttpResponseRedirect(redirect_to) else: request.audit['allowed'] = False msg = 'Failed login for user: %s' % request.POST.get('username', request.POST.get('email')) request.audit['operationText'] = msg access_warn(request, msg) if from_modal or request.GET.get('fromModal', 'false') == 'true': return JsonResponse({'auth': False}) else: first_user_form = None auth_form = AuthenticationForm() # SAML/OIDC user is already authenticated in djangosaml2.views.login if hasattr(request, 'fs') and ( 'KnoxSpnegoDjangoBackend' in backend_names or 'SpnegoDjangoBackend' in backend_names or 'OIDCBackend' in backend_names or 'SAML2Backend' in backend_names ) and request.user.is_authenticated: if request.fs is None: request.fs = fsmanager.get_filesystem(request.fs_ref) try: ensure_home_directory(request.fs, request.user) except (IOError, WebHdfsException) as e: LOG.error('Could not create home directory for %s user %s.' % ('OIDC' if 'OIDCBackend' in backend_names else 'SAML', request.user)) if request.user.is_authenticated and not from_modal: return HttpResponseRedirect(redirect_to) if is_active_directory and not is_ldap_option_selected and \ request.method == 'POST' and request.user.username != request.POST.get('username'): # local user login failed, give the right auth_form with 'server' field auth_form = auth_forms.LdapAuthenticationForm() if not from_modal and SESSION.ENABLE_TEST_COOKIE.get() : request.session.set_test_cookie() if 'SAML2Backend' in backend_names: request.session['samlgroup_permitted_flag'] = samlgroup_check(request) renderable_path = 'login.mako' if from_modal: renderable_path = 'login_modal.mako' response = render(renderable_path, request, { 'action': reverse('desktop_auth_views_dt_login'), 'form': first_user_form or auth_form, 'next': redirect_to, 'first_login_ever': is_first_login_ever, 'login_errors': request.method == 'POST', 'backend_names': backend_names, 'active_directory': is_active_directory, 'user': request.user }) if not request.user.is_authenticated: response.delete_cookie(LOAD_BALANCER_COOKIE) # Note: might be re-balanced to another Hue on login. return response
def orm_user_lookup(): return 'email' if ENABLE_ORGANIZATIONS.get() else 'username'
class Meta(object): model = Group fields = ["name"] if ENABLE_ORGANIZATIONS.get(): fields.append("organization")
def connect_to_thrift(conf): """ Connect to a thrift endpoint as determined by the 'conf' parameter. Note that this does *not* open the transport. Returns a tuple of (service, protocol, transport) """ if conf.transport_mode == 'http': mode = THttpClient(conf.http_url) mode.set_verify(conf.validate) else: if conf.use_ssl: try: from ssl import PROTOCOL_TLS PROTOCOL_SSLv23 = PROTOCOL_TLS except ImportError: try: from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS PROTOCOL_SSLv23 = PROTOCOL_TLS except ImportError: PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 mode = TSSLSocketWithWildcardSAN(conf.host, conf.port, validate=conf.validate, ca_certs=conf.ca_certs, keyfile=conf.keyfile, certfile=conf.certfile, ssl_version=PROTOCOL_SSLv23) else: mode = TSocket(conf.host, conf.port) if conf.timeout_seconds: # Thrift trivia: You can do this after the fact with # _grab_transport_from_wrapper(self.wrapped.transport).setTimeout(seconds*1000) mode.setTimeout(conf.timeout_seconds * 1000.0) if conf.transport_mode == 'http': if conf.use_sasl and conf.mechanism != 'PLAIN': mode.set_kerberos_auth(service=conf.kerberos_principal) elif USE_THRIFT_HTTP_JWT.get(): from desktop.auth.backend import find_user, rewrite_user # Cyclic dependency user = rewrite_user(find_user(conf.username)) if user is None: raise Exception("JWT: User not found.") if ENABLE_ORGANIZATIONS.get() and user.token: token = user.token elif user.profile.data.get('jwt_access_token'): token = user.profile.data['jwt_access_token'] else: raise Exception( "JWT: Could not retrive saved token from user.") mode.set_bearer_auth(token) else: mode.set_basic_auth(conf.username, conf.password) if conf.transport_mode == 'socket' and conf.use_sasl: def sasl_factory(): saslc = sasl.Client() saslc.setAttr("host", str(conf.host)) saslc.setAttr("service", str(conf.kerberos_principal)) if conf.mechanism == 'PLAIN': saslc.setAttr("username", str(conf.username)) saslc.setAttr( "password", str(conf.password) ) # Defaults to 'hue' for a non-empty string unless using LDAP else: saslc.setAttr("maxbufsize", SASL_MAX_BUFFER.get()) saslc.init() return saslc transport = TSaslClientTransport(sasl_factory, conf.mechanism, mode) elif conf.transport == 'framed': transport = TFramedTransport(mode) else: transport = TBufferedTransport(mode) protocol = TBinaryProtocol(transport) if conf.multiple: protocol = TMultiplexedProtocol(protocol, conf.service_name) service = conf.klass(protocol) return service, protocol, transport
def update_app_permissions(**kwargs): """ Keep in sync apps and connectors permissions into the database table. Map app + action to a HuePermission. v2 Based on the connectors. Permissions are either based on connectors instances or Hue specific actions. Permissions can be deleted or added dynamically. v1 This is a 'migrate' callback. We never delete permissions automatically, because apps might come and go. Note that signing up to the "migrate" signal is not necessarily the best thing we can do, since some apps might not have models, but nonetheless, "migrate" is typically run when apps are installed. """ created_tables = connection.introspection.table_names() if ENABLE_ORGANIZATIONS.get( ) and 'useradmin_organization' not in created_tables: return if u'useradmin_huepermission' in created_tables: # Check if Useradmin has been installed. current = {} try: for dp in HuePermission.objects.all(): current.setdefault(dp.app, {})[dp.action] = dp except: LOG.exception('failed to get permissions') return updated = 0 uptodate = 0 added = [] if ENABLE_CONNECTORS.get(): old_apps = list(current.keys()) ConnectorPerm = collections.namedtuple('ConnectorPerm', 'name nice_name settings') apps = [ ConnectorPerm(name=connector['name'], nice_name=connector['nice_name'], settings=[]) for connector in _get_installed_connectors() ] else: old_apps = [] apps = appmanager.DESKTOP_APPS for app in apps: app_name = app.name permission_description = "Access the %s connection" % app.nice_name if ENABLE_CONNECTORS.get( ) else "Launch this application" actions = set([("access", permission_description)]) actions.update(getattr(app.settings, "PERMISSION_ACTIONS", [])) if app_name not in current: current[app_name] = {} if app_name in old_apps: old_apps.remove(app_name) for action, description in actions: c = current[app_name].get(action) if c: if c.description != description: c.description = description c.save() updated += 1 else: uptodate += 1 else: new_dp = HuePermission(app=app_name, action=action, description=description) if ENABLE_CONNECTORS.get(): new_dp.connector = Connector.objects.get(id=app_name) new_dp.save() added.append(new_dp) # Only with v2 deleted, _ = HuePermission.objects.filter(app__in=old_apps).delete() # Add all permissions to default group except some. default_group = get_default_user_group() if default_group: for new_dp in added: if not (new_dp.app == 'useradmin' and new_dp.action == 'access') and \ not (new_dp.app == 'useradmin' and new_dp.action == 'superuser') and \ not (new_dp.app == 'metastore' and new_dp.action == 'write') and \ not (new_dp.app == 'hbase' and new_dp.action == 'write') and \ not (new_dp.app == 'security' and new_dp.action == 'impersonate') and \ not (new_dp.app == 'filebrowser' and new_dp.action == 's3_access' and not is_idbroker_enabled('s3a')) and \ not (new_dp.app == 'filebrowser' and new_dp.action == 'gs_access' and not is_idbroker_enabled('gs')) and \ not (new_dp.app == 'filebrowser' and new_dp.action == 'adls_access') and \ not (new_dp.app == 'filebrowser' and new_dp.action == 'abfs_access') and \ not (new_dp.app == 'oozie' and new_dp.action == 'disable_editor_access'): GroupPermission.objects.create(group=default_group, hue_permission=new_dp) available = HuePermission.objects.count() stale = available - len(added) - updated - uptodate if len(added) or updated or stale or deleted: LOG.info( "HuePermissions: %d added, %d updated, %d up to date, %d stale, %d deleted" % (len(added), updated, uptodate, stale, deleted))
def install_sample_user(django_user=None): """ Setup the de-activated sample user with a certain id. Do not create a user profile. """ from desktop.models import SAMPLE_USER_ID, get_sample_user_install from hadoop import cluster user = None django_username = get_sample_user_install(django_user) if ENABLE_ORGANIZATIONS.get(): lookup = {'email': django_username} django_username_short = django_user.username_short else: lookup = {'username': django_username} django_username_short = django_username try: if User.objects.filter( id=SAMPLE_USER_ID).exists() and not ENABLE_ORGANIZATIONS.get(): user = User.objects.get(id=SAMPLE_USER_ID) LOG.info('Sample user found with username "%s" and User ID: %s' % (user.username, user.id)) elif User.objects.filter(**lookup).exists(): user = User.objects.get(**lookup) LOG.info('Sample user found: %s' % lookup) else: user_attributes = lookup.copy() if ENABLE_ORGANIZATIONS.get(): user_attributes['organization'] = get_organization( email=django_username) else: user_attributes['id'] = SAMPLE_USER_ID user_attributes.update({ 'password': '******', 'is_active': False, 'is_superuser': False, }) user, created = User.objects.get_or_create(**user_attributes) if created: LOG.info('Installed a user "%s"' % lookup) if user.username != django_username and not ENABLE_ORGANIZATIONS.get(): LOG.warn( 'Sample user does not have username "%s", will attempt to modify the username.' % django_username) with transaction.atomic(): user = User.objects.get(id=SAMPLE_USER_ID) user.username = django_username user.save() except: LOG.exception('Failed to get or create sample user') # If sample user doesn't belong to default group, add to default group default_group = get_default_user_group(user=user) if user is not None and default_group is not None and default_group not in user.groups.all( ): user.groups.add(default_group) user.save() # If home directory doesn't exist for sample user, create it fs = cluster.get_hdfs() try: if not fs: LOG.info( 'No fs configured, skipping home directory creation for user: %s' % django_username_short) elif not fs.do_as_user(django_username_short, fs.get_home_dir): fs.do_as_user(django_username_short, fs.create_home_dir) LOG.info('Created home directory for user: %s' % django_username_short) else: LOG.info('Home directory already exists for user: %s' % django_username) except Exception as ex: LOG.exception('Failed to create home directory for user %s: %s' % (django_username, str(ex))) return user