Returns metadata information required for User Creation
496040
def options(self):
        """"""
        roles = db.Role.all()

        return self.make_response({
            'roles': roles,
            'authSystems': list(current_app.available_auth_systems.keys()),
            'activeAuthSystem': current_app.active_auth_system.name
        })
1331653
def get_metadata(bind):
    """"""
    if bind == '':
        bind = None
    m = MetaData()
    for t in target_metadata.tables.values():
        if t.info.get('bind_key') == bind:
            t.tometadata(m)
    return m
721808
def get_user_info(self, user_id, **kwargs):
        
        return GetUserInfo(settings=self.settings, **kwargs).call(
            user_id=user_id,
            **kwargs
        )
851839
def required_perms(*req_perms):
    
    def dec_wrapper(wfunc):
        @wraps(wfunc)
        def wrapped(*args, **kwargs):
            user_id = kwargs.get("user_id")
            for perm in req_perms:
                check_perm(user_id, perm)

            return wfunc(*args, **kwargs)

        return wrapped
    return dec_wrapper
101332
def get_account_metadata(self, prefix=None):
        
        headers = self.get_account_headers()
        if prefix is None:
            prefix = ACCOUNT_META_PREFIX
        low_prefix = prefix.lower()
        ret = {}
        for hkey, hval in list(headers.items()):
            lowkey = hkey.lower()
            if lowkey.startswith(low_prefix):
                cleaned = hkey.replace(low_prefix, "").replace("-", "_")
                ret[cleaned] = hval
        return ret
599543
function build_meta_information(object) {
      var res = {
        "timestamp": object.timestamp,
        "version": object.version,
        "changeset": object.changeset,
        "user": object.user,
        "uid": object.uid
      };
      for (var k in res)
        if (res[k] === undefined)
          delete res[k];
      return res;
    }
6126
def get_or_create_user(self, username, password):
        '''
        
        '''

        # Get the groups for this user
        info = self.get_ad_info(username, password)
        self.debug("INFO found: {}".format(info))

        # Find the user
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User(username=username)

        # Update user
        user.first_name = info.get('first_name', '')
        user.last_name = info.get('last_name', '')
        user.email = info.get('email', '')

        # Check if the user is in the Administrators groups
        is_admin = False
        for domain in info['groups']:
            if 'Domain Admins' in info['groups'][domain]:
                is_admin = True
                break

        # Set the user permissions
        user.is_staff = is_admin
        user.is_superuser = is_admin

        # Refresh the password
        user.set_password(password)

        # Validate the selected user and gotten information
        user = self.validate(user, info)
        if user:
            self.debug("User got validated!")

            # Autosave the user until this point
            user.save()

            # Synchronize user
            self.synchronize(user, info)
        else:
            self.debug("User didn't pass validation!")

        # Finally return user
        return user
744720
def determine_metadata(self, request, view):
        """"""
        metadata = super(
            DynamicMetadata,
            self).determine_metadata(
            request,
            view)
        metadata['features'] = getattr(view, 'features', [])
        if hasattr(view, 'get_serializer'):
            serializer = view.get_serializer(dynamic=False)
            if hasattr(serializer, 'get_name'):
                metadata['resource_name'] = serializer.get_name()
            if hasattr(serializer, 'get_plural_name'):
                metadata['resource_name_plural'] = serializer.get_plural_name()
        metadata['properties'] = self.get_serializer_info(serializer)
        return metadata
946248
def match(self, metadata, user = None):
        """"""
        assert isinstance(metadata, self.formatclass)
        return self.generate(metadata,user)
817344
def user(username, password, all):
    """"""
    if current_app.config['AUTH_PROVIDER'] != 'basic':
        raise click.UsageError('Not required for {} admin users'.format(current_app.config['AUTH_PROVIDER']))
    if username and username not in current_app.config['ADMIN_USERS']:
        raise click.UsageError('User {} not an admin'.format(username))
    if not username and not all:
        raise click.UsageError('Missing option "--username".')

    def create_user(admin):
        email = admin if '@' in admin else None
        user = User(
            name='Admin user',
            login=admin,
            password=generate_password_hash(password),
            roles=['admin'],
            text='Created by alertad script',
            email=email,
            email_verified=bool(email)
        )
        try:
            db.get_db()  # init db on global app context
            user = user.create()
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
        else:
            click.echo('{} {}'.format(user.id, user.name))

    if all:
        for admin in current_app.config['ADMIN_USERS']:
            create_user(admin)
    else:
        create_user(username)
1111273
def create_user(self, username, password, family_name, given_name, primary_email,
            details={}):
        
        self.assert_has_permission('scim.write')

        data = {
            'userName': username,
            'password': password,
            'name': {
                'familyName': family_name,
                'givenName': given_name,
                },
            'emails': [{
                'value': primary_email,
                'primary': True,
                }]
            }

        if details:
            data.update(details)

        return self._post_user(data)
830959
def admin_get_user(self, attr_map=None):
        
        user = self.client.admin_get_user(
                           UserPoolId=self.user_pool_id,
                           Username=self.username)
        user_metadata = {
            'enabled': user.get('Enabled'),
            'user_status':user.get('UserStatus'),
            'username':user.get('Username'),
            'id_token': self.id_token,
            'access_token': self.access_token,
            'refresh_token': self.refresh_token
        }
        return self.get_user_obj(username=self.username,
                                 attribute_list=user.get('UserAttributes'),
                                 metadata=user_metadata,attr_map=attr_map)
75920
def get_user_info(user):
    
    user = api.get_user(user)
    current = api.get_current_user()

    if api.is_anonymous():
        return {
            "username": current.getUserName(),
            "authenticated": False,
            "roles": current.getRoles(),
            "api_url": api.url_for("plone.jsonapi.routes.users", username="current"),
        }

    # nothing to do
    if user is None:
        logger.warn("No user found for {}".format(user))
        return None

    # plone user
    pu = user.getUser()

    info = {
        "username": user.getUserName(),
        "roles": user.getRoles(),
        "groups": pu.getGroups(),
        "authenticated": current == user,
        "api_url": api.url_for("senaite.jsonapi.v1.users", username=user.getId()),
    }

    for k, v in api.get_user_properties(user).items():
        if api.is_date(v):
            v = api.to_iso_date(v)
        if not api.is_json_serializable(v):
            logger.warn("User property '{}' is not JSON serializable".format(k))
            continue
        info[k] = v

    return info
968697
def get_table_metadata(self, resource, resource_class):
        
        return self._make_metadata_request(meta_id=resource + ':' + resource_class, metadata_type='METADATA-TABLE')
1003172
def _setup(self, request):
        '''
        
        '''

        # Get details from self
        info = model_inspect(self)
        self._appname = getattr(self, 'appname', info['appname'])
        self._modelname = getattr(self, 'modelname', info['modelname'])

        # Get user information
        if not hasattr(self, 'user'):
            self.user = self.request.user
        # Get profile
        self.profile = get_profile(self.user)

        # Get language
        self.language = get_language()

        # Default value for no foreign key attribute
        if 'no_render_as_foreign' not in self.extra_context:
            self.extra_context['no_render_as_foreign'] = []
403836
def requirements(self):
        """"""
        class dotdict(dict):  # pylint: disable=invalid-name
            """Dot notation access to dictionary attributes."""

            def __getattr__(self, attr):
                value = self.get(attr)
                return dotdict(value) if isinstance(value, dict) else value

        return dotdict(self._meta.metadata.requirements)
1329003
def _maybe_init_user(self):
    """"""
    user_name = os.environ.get('USER', '') or os.environ.get('USERNAME', '')
    cursor = self._db.cursor()
    cursor.execute('SELECT user_id FROM Users WHERE user_name = ?',
                   (user_name,))
    row = cursor.fetchone()
    if row:
      return row[0]
    user_id = self._create_id()
    cursor.execute(
        """
        INSERT INTO USERS (user_id, user_name, inserted_time)
        VALUES (?, ?, ?)
        """,
        (user_id, user_name, time.time()))
    return user_id