Validate a userId format and signature on displayName, and return its address
337630
def validate_userid_signature(user: User) -> Optional[Address]:
    
    # display_name should be an address in the USERID_RE format
    match = USERID_RE.match(user.user_id)
    if not match:
        return None

    encoded_address = match.group(1)
    address: Address = to_canonical_address(encoded_address)

    try:
        displayname = user.get_display_name()
        recovered = recover(
            data=user.user_id.encode(),
            signature=decode_hex(displayname),
        )
        if not (address and recovered and recovered == address):
            return None
    except (
            DecodeError,
            TypeError,
            InvalidSignature,
            MatrixRequestError,
            json.decoder.JSONDecodeError,
    ):
        return None
    return address
788523
def get(method, hmc, uri, uri_parms, logon_required):
        """"""
        query_str = uri_parms[0]
        try:
            console = hmc.consoles.lookup_by_oid(None)
        except KeyError:
            raise InvalidResourceError(method, uri)
        result_user_patterns = []
        filter_args = parse_query_parms(method, uri, query_str)
        for user_pattern in console.user_patterns.list(filter_args):
            result_user_pattern = {}
            for prop in user_pattern.properties:
                if prop in ('element-uri', 'name', 'type'):
                    result_user_pattern[prop] = user_pattern.properties[prop]
            result_user_patterns.append(result_user_pattern)
        return {'user-patterns': result_user_patterns}
24487
async function getUsersIdsToNotify(thing, checkValueAccess) {
	
	if (!thing)
		throw new utils.ErrorCustom(httpStatusCodes.INTERNAL_SERVER_ERROR, "Thing can't be null", 26);
	
	let UsersIdsToNotify = new Set();
	
	for(let r of thing.usersRights) {
	
		if (!(
			((r.userStatus & (thConstants.ThingUserStates.Ok | thConstants.ThingUserStates.WaitForAuth)) != 0) &&
				((r.userVisibility & thConstants.ThingUserVisibility.Visible) != 0))
		)
			continue;

		let userId = r.userId;
		let username = r.username;
	
		if (!userId && !username)
			throw new utils.ErrorCustom(httpStatusCodes.INTERNAL_SERVER_ERROR, "Both userId and username can't be empty", 27);
		
		let user = userId ? await usersManager.findUserById(userId) : await	usersManager.findUserByUsername(username);
		if (!user)
			continue;

		if (checkValueAccess) {
			let thingUserClaims = getThingUserClaims(user, thing, user.isSuperAdministrator);
			if ((thingUserClaims.change & thConstants.ThingUserChangeClaims.CanChangeValue) == 0)
				continue;
		}
			
		UsersIdsToNotify.add(userId);
	}
	
	return UsersIdsToNotify;
}
1331358
function formatAddress(address) {
  const result = address
  if (result) {
    result.formatted =
      `${result.street_address}\n${result.postal_code} ${result.locality}\n${result.country}`
    return result
  }
  return null
}
1073353
def validate_address(self, address_deets):
        """"""
        request = self._post('addresses/validate', address_deets)
        return self.responder(request)
661479
private static int checkFormalTypeParameter(final String signature, int pos) {
        // FormalTypeParameter:
        // Identifier : FieldTypeSignature? (: FieldTypeSignature)*

        pos = checkIdentifier(signature, pos);
        pos = checkChar(':', signature, pos);
        if ("L[T".indexOf(getChar(signature, pos)) != -1) {
            pos = checkFieldTypeSignature(signature, pos);
        }
        while (getChar(signature, pos) == ':') {
            pos = checkFieldTypeSignature(signature, pos + 1);
        }
        return pos;
    }
658917
def authenticated_userid(request):
    
    user = getattr(request, 'user', None)
    key = user.pk_field()
    return getattr(user, key)
864598
function $formatter(type, d, {user,sId,ip,ref}) {
  if (!config.log || !config.log.trk[type]) return
  var ident = user != null ? `${user.name||user._id}`.gray : `${sId.substring(0,12)}`.cyan

  var jdata = type == 'view'
    ? `${(d.url||'').cyan} ${ref?ref.replace(/https\:\/\/|http\:\/\//g,'<<< ').replace('www.','').blue:''}`
    : JSON.stringify(d.data||{}).replace(/^\{/,'').replace(/\}$/,'').replace(/\"([^(\")"]+)\":/g,"$1:".dim).gray
  var label = type
  if (type == 'event') label = d.name
  if (type == 'view') label = `VIEW:${d.type}`
  $logIt(`trk.${type}`
    , label.toUpperCase()
    , `${ip.replace(':ffff','')}`.cyan+`\t${ident}`
    , jdata
  )
}
1295179
function getIdentity(urlStr, urlTemplates, www) {
     var identity = {};

     urlObj = urlParser.parse(urlStr);
        
     // Loop all the urlMappings for site object
     for(var y = 0; y <= urlTemplates.length-1; y++){
        urlTemplate = urlTemplates[y];

        // remove http protocol    
        urlTemplate = removeHttpHttps(urlTemplate);
        
        // if the urlTemplate contains a username or userid parse it
        if (urlTemplate != '' && (urlTemplate.indexOf('{username}') > -1 || urlTemplate.indexOf('{userid}') > -1)) {
            
            // break up url template
            var parts = urlTemplate.split(/\{userid\}|\{username\}/),
                startMatch = false,
                endMatch = false,
                user = urlObj.href

            // remove protocol, querystring and fragment
            user = user.replace(urlObj.hash, '');
            user = user.replace(urlObj.search, ''); 
            user = removeHttpHttps(user); 
            

            // remove www if subdomain is optional
            if(www){
                user = user.replace('www.', '') ;
                urlStr = urlStr.replace('www.', '') ;
            }

            // remove any trailing /
            if (endsWith(user,'/'))
                user = user.substring(0, user.length - 1); 
              

            // remove unwanted front section of url string
            if (user.indexOf(parts[0]) === 0){
                startMatch = true;
                part = parts[0];
                user = user.substring(part.length, user.length);
            }
            
            // remove unwanted end section of url string
            if (parts.length === 2){
                // if no end part or its just and trailing /
                if (parts[1].length > 0 && parts[1] !== '/'){
                    // end part matches template
                    if (endsWith(user,parts[1])){
                        endMatch = true;
                        user = user.replace(parts[1], '');
                    } else if (endsWith(user,parts[1] + '/')) {
                        // end part matches template with a trailing /
                        endMatch = true;
                        user = user.replace(parts[1] + '/', '');
                    }
                } else {
                    endMatch = true;
                }
            }
            


            // if the user contain anymore / then do not use it
            if (user.indexOf("/") > -1)
                endMatch = false;


            if (startMatch && endMatch){
                
                identity = {}; 
                identity.domain = urlObj.host; 
                identity.matchedUrl = urlStr;

                if (urlTemplate.indexOf("{username}") > -1){
                    identity.userName = user;
                    identity.sgn = "sgn://" + urlObj.host + "/?ident=" + user;
                }

                if (urlTemplate.indexOf("{userid}") > -1){
                    identity.userId = user;
                    identity.sgn = "sgn://" + urlObj.host + "/?pk=" + user;
                }

                break;
            }                       
        } 
    } 

    return identity;
}
518440
def verifymessage(self, address, signature, message):
        """"""
        return self.req("verifymessage", [address, signature, message])
1059572
def http_signature(message, key_id, signature):
    """"""
    template = ('Signature keyId="%(keyId)s",algorithm="hmac-sha256",'
                'headers="%(headers)s",signature="%(signature)s"')
    headers = ['(request-target)', 'host', 'accept', 'date']
    return template % {
        'keyId': key_id,
        'signature': signature,
        'headers': ' '.join(headers),
    }
43707
def check_user(user_id, u_pass):
        '''
        
        '''
        user_count = TabMember.select().where(TabMember.uid == user_id).count()
        if user_count == 0:
            return -1
        the_user = TabMember.get(uid=user_id)
        if the_user.user_pass == tools.md5(u_pass):
            return 1
        return 0
113191
def verify_signature(self, address, signature, hexdata):
        """"""
        try:
            address = deserialize.address(self.testnet, address)
            data = deserialize.binary(hexdata)
            signature = deserialize.signature(signature)
            return control.verify_signature(self.testnet, address,
                                            signature, data)
        except exceptions.InvalidAddress:
            return False
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
975750
function(userId, messageId, callback) {
      if (!userId) return callback(new Error(utils.i18n.messages.userId));
      messageId = utils.toUUID(messageId);
      if (!messageId) return callback(new Error(utils.i18n.messages.mid));
      utils.debug('Message getFromUser: ' + userId + ', ' + messageId);

      request.get({
        path: '/users/' + querystring.escape(userId) + '/messages/' + messageId
      }, callback);
    }
53579
def _usernamesToSidObjects(cls, val, **kwargs):
        '''
        
        '''
        if not val:
            return val
        if isinstance(val, six.string_types):
            val = val.split(',')
        sids = []
        for _user in val:
            try:
                sid = win32security.LookupAccountName('', _user)[0]
                sids.append(sid)
            # This needs to be more specific
            except Exception as e:
                log.exception('Handle this explicitly')
                raise CommandExecutionError((
                    'There was an error obtaining the SID of user "{0}". Error '
                    'returned: {1}'
                    ).format(_user, e))
        return sids
1049344
def _sign(self, subject, sig, **prefs):
        
        user = prefs.pop('user', None)
        uid = None
        if user is not None:
            uid = self.get_uid(user)

        else:
            uid = next(iter(self.userids), None)
            if uid is None and self.parent is not None:
                uid = next(iter(self.parent.userids), None)

        if sig.hash_algorithm is None:
            sig._signature.halg = uid.selfsig.hashprefs[0]

        if uid is not None and sig.hash_algorithm not in uid.selfsig.hashprefs:
            warnings.warn("Selected hash algorithm not in key preferences", stacklevel=4)

        # signature options that can be applied at any level
        expires = prefs.pop('expires', None)
        notation = prefs.pop('notation', None)
        revocable = prefs.pop('revocable', True)
        policy_uri = prefs.pop('policy_uri', None)

        if expires is not None:
            # expires should be a timedelta, so if it's a datetime, turn it into a timedelta
            if isinstance(expires, datetime):
                expires = expires - self.created

            sig._signature.subpackets.addnew('SignatureExpirationTime', hashed=True, expires=expires)

        if revocable is False:
            sig._signature.subpackets.addnew('Revocable', hashed=True, bflag=revocable)

        if notation is not None:
            for name, value in notation.items():
                # mark all notations as human readable unless value is a bytearray
                flags = NotationDataFlags.HumanReadable
                if isinstance(value, bytearray):
                    flags = 0x00

                sig._signature.subpackets.addnew('NotationData', hashed=True, flags=flags, name=name, value=value)

        if policy_uri is not None:
            sig._signature.subpackets.addnew('Policy', hashed=True, uri=policy_uri)

        if user is not None and uid is not None:
            signers_uid = "{:s}".format(uid)
            sig._signature.subpackets.addnew('SignersUserID', hashed=True, userid=signers_uid)

        # handle an edge case for timestamp signatures vs standalone signatures
        if sig.type == SignatureType.Timestamp and len(sig._signature.subpackets._hashed_sp) > 1:
            sig._signature.sigtype = SignatureType.Standalone

        sigdata = sig.hashdata(subject)
        h2 = sig.hash_algorithm.hasher
        h2.update(sigdata)
        sig._signature.hash2 = bytearray(h2.digest()[:2])

        _sig = self._key.sign(sigdata, getattr(hashes, sig.hash_algorithm.name)())
        if _sig is NotImplemented:
            raise NotImplementedError(self.key_algorithm)

        sig._signature.signature.from_signer(_sig)
        sig._signature.update_hlen()

        return sig