Return a SECURITY_ATTRIBUTES structure with the SID set to the
	specified user (uses current user if none is specified).
760672
def get_security_attributes_for_user(user=None):
	
	if user is None:
		user = get_current_user()

	assert isinstance(user, security.TOKEN_USER), (
		"user must be TOKEN_USER instance")

	SD = security.SECURITY_DESCRIPTOR()
	SA = security.SECURITY_ATTRIBUTES()
	# by attaching the actual security descriptor, it will be garbage-
	# collected with the security attributes
	SA.descriptor = SD
	SA.bInheritHandle = 1

	ctypes.windll.advapi32.InitializeSecurityDescriptor(
		ctypes.byref(SD),
		security.SECURITY_DESCRIPTOR.REVISION)
	ctypes.windll.advapi32.SetSecurityDescriptorOwner(
		ctypes.byref(SD),
		user.SID, 0)
	return SA
946948
def user_model_attributes(user, service):
    
    ignore_fields = ['id', 'password']
    attributes = {}
    for field in user._meta.fields:
        if field.name not in ignore_fields:
            attributes[field.name] = getattr(user, field.name)
    return attributes
1294518
def get_auth_token(self, user):
        
        data = [str(user.id),
                self.security.hashing_context.hash(encode_string(user._password))]
        return self.security.remember_token_serializer.dumps(data)
322614
def get_user_from_session(session_key):
    
    session = Session.objects.get(session_key=session_key)
    session_data = session.get_decoded()
    uid = session_data.get('_auth_user_id')
    user = get_user_model().objects.filter(id=uid).first()  # get object or none
    return user
224459
def user(self, username=None):
        
        if username is None:
            username = self.__getUsername()

        url = "%s/%s" % (self.root, username)
        return User(url=url,
                    securityHandler=self._securityHandler,
                    proxy_url=self._proxy_url,
                    proxy_port=self._proxy_port,
                    initalize=True)
735635
def to_user(user):
        
        from sevenbridges.models.user import User
        if not user:
            raise SbgError('User is required!')
        elif isinstance(user, User):
            return user.username
        elif isinstance(user, six.string_types):
            return user
        else:
            raise SbgError('Invalid user parameter!')
872707
def user(self):
        
        if self._user is not None:
            return self._user

        cert = self.transport.getPeerCertificate()
        self._user = user = userForCert(self.store, cert)
        return user
885910
def __sid_to_username(sid):
        '''
        
        '''
        if sid is None or sid == '':
            return ''
        try:
            sid_bin = win32security.GetBinarySid(sid)  # pylint: disable=no-member
        except pywintypes.error as exc:  # pylint: disable=no-member
            raise ValueError(
                    'pkg: Software owned by {0} is not valid: [{1}] {2}'.format(sid, exc.winerror, exc.strerror)
                )
        try:
            name, domain, _account_type = win32security.LookupAccountSid(None, sid_bin)  # pylint: disable=no-member
            user_name = '{0}\\{1}'.format(domain, name)
        except pywintypes.error as exc:  # pylint: disable=no-member
            # if user does not exist...
            # winerror.ERROR_NONE_MAPPED = No mapping between account names and
            # security IDs was carried out.
            if exc.winerror == winerror.ERROR_NONE_MAPPED:  # 1332
                # As the sid is from the registry it should be valid
                # even if it cannot be lookedup, so the sid is returned
                return sid
            else:
                raise ValueError(
                          'Failed looking up sid \'{0}\' username: [{1}] {2}'.format(sid, exc.winerror, exc.strerror)
                        )
        try:
            user_principal = win32security.TranslateName(  # pylint: disable=no-member
                            user_name,
                            win32api.NameSamCompatible,  # pylint: disable=no-member
                            win32api.NameUserPrincipal)  # pylint: disable=no-member
        except pywintypes.error as exc:  # pylint: disable=no-member
            # winerror.ERROR_NO_SUCH_DOMAIN The specified domain either does not exist
            # or could not be contacted, computer may not be part of a domain also
            # winerror.ERROR_INVALID_DOMAINNAME The format of the specified domain name is
            # invalid. e.g. S-1-5-19 which is a local account
            # winerror.ERROR_NONE_MAPPED No mapping between account names and security IDs was done.
            if exc.winerror in (winerror.ERROR_NO_SUCH_DOMAIN,
                                winerror.ERROR_INVALID_DOMAINNAME,
                                winerror.ERROR_NONE_MAPPED):
                return '{0}@{1}'.format(name.lower(), domain.lower())
            else:
                raise
        return user_principal
777847
def security():
    """"""
    sessions = SessionActivity.query_by_user(
        user_id=current_user.get_id()
    ).all()
    master_session = None
    for index, session in enumerate(sessions):
        if SessionActivity.is_current(session.sid_s):
            master_session = session
            del sessions[index]
    return render_template(
        current_app.config['ACCOUNTS_SETTINGS_SECURITY_TEMPLATE'],
        formclass=RevokeForm,
        sessions=[master_session] + sessions,
        is_current=SessionActivity.is_current
    )
375808
def _getUserSid(user):
    '''
    
    '''
    ret = {}

    sid_pattern = r'^S-1(-\d+){1,}$'

    if user and re.match(sid_pattern, user, re.I):
        try:
            sid = win32security.GetBinarySid(user)
        except Exception as e:
            ret['result'] = False
            ret['comment'] = 'Unable to obtain the binary security identifier for {0}.  The exception was {1}.'.format(
                user, e)
        else:
            try:
                win32security.LookupAccountSid('', sid)
                ret['result'] = True
                ret['sid'] = sid
            except Exception as e:
                ret['result'] = False
                ret['comment'] = 'Unable to lookup the account for the security identifier {0}.  The exception was {1}.'.format(
                    user, e)
    else:
        try:
            sid = win32security.LookupAccountName('', user)[0] if user else None
            ret['result'] = True
            ret['sid'] = sid
        except Exception as e:
            ret['result'] = False
            ret['comment'] = 'Unable to obtain the security identifier for {0}.  The exception was {1}.'.format(
                user, e)
    return ret
817306
def get_attributes(user, service):
    
    attributes = {}
    for path in get_callbacks(service):
        callback = import_string(path)
        attributes.update(callback(user, service))
    return attributes
638451
def _sidConversion(cls, val, **kwargs):
        '''
        
        '''
        if isinstance(val, six.string_types):
            val = val.split(',')
        usernames = []
        for _sid in val:
            try:
                userSid = win32security.LookupAccountSid('', _sid)
                if userSid[1]:
                    userSid = '{1}\\{0}'.format(userSid[0], userSid[1])
                else:
                    userSid = '{0}'.format(userSid[0])
            # TODO: This needs to be more specific
            except Exception:
                userSid = win32security.ConvertSidToStringSid(_sid)
                log.warning('Unable to convert SID "%s" to a friendly name.  The SID will be disaplayed instead of a user/group name.', userSid)
            usernames.append(userSid)
        return usernames
840271
def acc_security(self):
        
        if self._acc_security is None:
            self._acc_security = AccSecurity(self)
        return self._acc_security
1155541
def user_id(self):
        
        if self._user_id is None:
            if self.has_logged_in:
                self._user_id = self._req_get_user_aq()['data']['uid']
            else:
                raise AuthenticationError('Not logged in.')
        return self._user_id
106295
def authenticate(self, request, ticket, service):
        """"""
        client = get_cas_client(service_url=service, request=request)
        username, attributes, pgtiou = client.verify_ticket(ticket)
        if attributes and request:
            request.session['attributes'] = attributes

        if settings.CAS_USERNAME_ATTRIBUTE != 'uid' and settings.CAS_VERSION != 'CAS_2_SAML_1_0':
            if attributes:
                username = attributes.get(settings.CAS_USERNAME_ATTRIBUTE)
            else:
                return None

        if not username:
            return None
        user = None
        username = self.clean_username(username)

        if attributes:
            reject = self.bad_attributes_reject(request, username, attributes)
            if reject:
                return None

            # If we can, we rename the attributes as described in the settings file
            # Existing attributes will be overwritten
            for cas_attr_name, req_attr_name in settings.CAS_RENAME_ATTRIBUTES.items():
                if cas_attr_name in attributes and cas_attr_name is not req_attr_name:
                    attributes[req_attr_name] = attributes[cas_attr_name]
                    attributes.pop(cas_attr_name)

        UserModel = get_user_model()

        # Note that this could be accomplished in one try-except clause, but
        # instead we use get_or_create when creating unknown users since it has
        # built-in safeguards for multiple threads.
        if settings.CAS_CREATE_USER:
            user_kwargs = {
                UserModel.USERNAME_FIELD: username
            }
            if settings.CAS_CREATE_USER_WITH_ID:
                user_kwargs['id'] = self.get_user_id(attributes)

            user, created = UserModel._default_manager.get_or_create(**user_kwargs)
            if created:
                user = self.configure_user(user)
        else:
            created = False
            try:
                if settings.CAS_LOCAL_NAME_FIELD:
                    user_kwargs = {
                        settings.CAS_LOCAL_NAME_FIELD: username

                    }
                    user = UserModel._default_manager.get(**user_kwargs)
                else:
                    user = UserModel._default_manager.get_by_natural_key(username)
            except UserModel.DoesNotExist:
                pass

        if not self.user_can_authenticate(user):
            return None

        if pgtiou and settings.CAS_PROXY_CALLBACK and request:
            request.session['pgtiou'] = pgtiou

        if settings.CAS_APPLY_ATTRIBUTES_TO_USER and attributes:
            # If we are receiving None for any values which cannot be NULL
            # in the User model, set them to an empty string instead.
            # Possibly it would be desirable to let these throw an error
            # and push the responsibility to the CAS provider or remove
            # them from the dictionary entirely instead. Handling these
            # is a little ambiguous.
            user_model_fields = UserModel._meta.fields
            for field in user_model_fields:
                # Handle null -> '' conversions mentioned above
                if not field.null:
                    try:
                        if attributes[field.name] is None:
                            attributes[field.name] = ''
                    except KeyError:
                        continue
                # Coerce boolean strings into true booleans
                if field.get_internal_type() == 'BooleanField':
                    try:
                        boolean_value = attributes[field.name] == 'True'
                        attributes[field.name] = boolean_value
                    except KeyError:
                        continue

            user.__dict__.update(attributes)

            # If we are keeping a local copy of the user model we
            # should save these attributes which have a corresponding
            # instance in the DB.
            if settings.CAS_CREATE_USER:
                user.save()

        # send the `cas_user_authenticated` signal
        cas_user_authenticated.send(
            sender=self,
            user=user,
            created=created,
            username=username,
            attributes=attributes,
            pgtiou=pgtiou,
            ticket=ticket,
            service=service,
            request=request
        )
        return user
616694
def extract_user_id(self, request):
        
        payload = self.extract_payload(request)
        user_id_attribute = self.config.user_id()
        return payload.get(user_id_attribute, None)
131745
def get_user(id, opts = {})
      data, _status_code, _headers = get_user_with_http_info(id, opts)
      return data
    end