Authenticate a client based on their shared secret and/or their ipAddress

@param $appID
@param null $sharedSecret
@param null $ipAddress
@param bool $manual
@return Client|bool
548345
public function authenticate(
        $appID,
        $sharedSecret = null,
        $ipAddress = null,
        $manual = false
    ) {
        $test_prefix = false;
        $test_on_prod = false;
        if (substr($appID, 0, 4) == "TEST") {
            $appID = str_replace("TEST", "", $appID);
            $test_prefix = true;
            $test_on_prod = true;
        }

        $client = $this->getByAppID($appID);

        // No Client Exists
        if ($client === null) {
            $this->setMessage("Client does not exists");
            return false;
        }

        //if the client has passed their test app_id we need to set prefix to test prefix
        if ($client->test_app_id == $appID ) {
            $test_prefix = true;
        }

        // Client exists and it's a manual request
        if ($manual) {
            return $client;
        }

        //client exists and has been set to a test account via the app_id make sure that the test prefix is used

        if ($test_prefix) {
            $client['mode'] = "test";
        }

        // if sharedSecret is provided

        //if the test_app_id is being used compare provided shared secret with test_shared_secret
        if ($sharedSecret && $test_prefix && !$test_on_prod) {
            if ($client->test_shared_secret !== $sharedSecret) {
                $this->setMessage("Authentication Failed. Mismatch test shared secret provided");
                return false;
            }
            return $client;
        }elseif($sharedSecret){
            if ($client->shared_secret !== $sharedSecret) {
                $this->setMessage("Authentication Failed. Mismatch shared secret provided");
                return false;
            }
            return $client;
        }

        // ip address matching
        if ($ipAddress &&
            IPValidator::validate($ipAddress, $client->ip_address) === false
        ) {
            $this->setMessage("Authentication Failed. Mismatch IP Address. Provided IP Address: " . $ipAddress);
            return false;
        }

        return $client;
    }
1301531
function sendSharedAddressToPeer(device_address, shared_address, handle){
	var arrDefinition;
	var assocSignersByPath={};
	async.series([
		function(cb){
			db.query("SELECT definition FROM shared_addresses WHERE shared_address=?", [shared_address], function(rows){
				if (!rows[0])
					return cb("Definition not found for " + shared_address);
				arrDefinition = JSON.parse(rows[0].definition);
				return cb(null);
			});
		},
		function(cb){
			db.query("SELECT signing_path,address,member_signing_path,device_address FROM shared_address_signing_paths WHERE shared_address=?", [shared_address], function(rows){
				if (rows.length<2)
					return cb("Less than 2 signing paths found for " + shared_address);
				rows.forEach(function(row){
					assocSignersByPath[row.signing_path] = {address: row.address, member_signing_path: row.member_signing_path, device_address: row.device_address};
				});
				return cb(null);
			});
		}
	],
	function(err){
		if (err)
			return handle(err);
		sendNewSharedAddress(device_address, shared_address, arrDefinition, assocSignersByPath);
		return handle(null);
	});
}
610390
public function authenticateRequestWithSharedKey(
        RequestInterface $request,
        SharedAuthenticationKey $key
    ): RequestInterface {
        $mac = \ParagonIE_Sodium_Compat::crypto_auth(
            (string) $request->getBody(),
            $key->getString(true)
        );
        return $request->withAddedHeader(
            self::HEADER_AUTH_NAME,
            Base64UrlSafe::encode($mac)
        );
    }
1052258
public static MnoHttpClient getAuthenticatedClient(String key, String secret, String contentType) {
		MnoHttpClient client = new MnoHttpClient(contentType);
		String authStr = key + ":" + secret;
		client.basicAuthHash = "Basic " + DatatypeConverter.printBase64Binary(authStr.getBytes());

		return client;
	}
592580
public Iterable<DConnection> queryBySecret(java.lang.String secret) {
    return queryByField(null, DConnectionMapper.Field.SECRET.getFieldName(), secret);
  }
1228101
public function checkClientCredentials($client_id, $client_secret = null)
    {
        if ($result = $this->getObjectByType('client_table',$client_id)) {
            return $result['client_secret'] == $client_secret;
        }

        return false;
    }
810739
public function bindThirdPoi(array $deviceIdentifier, int $poiId, string $appId)
    {
        $params = [
            'device_identifier' => $deviceIdentifier,
            'poi_id' => $poiId,
            'type' => 2,
            'poi_appid' => $appId,
        ];

        return $this->httpPostJson('shakearound/device/bindlocation', $params);
    }
643896
public static function createForApp(string $appIdentifier, string $appSecret)
    {
        $httpClientConfigurator = new HttpClientConfigurator();
        $httpClientConfigurator
            ->setApiAppIdentifier($appIdentifier)
            ->setApiAppSecret($appSecret);

        return static::configure($httpClientConfigurator);
    }
848432
public function createAnonymousClient($applicationId, $applicationSecret)
    {
        return $this->createCommand()
            ->setRequest($this->client->post('client'))
            ->setBodyEntity(array(
                'application_id' => $applicationId,
                'application_secret' => $applicationSecret,
            ), 'urlencoded')
            ->setResponseClass('Maba\OAuthCommerceClient\Entity\SignatureCredentials')
        ;
    }
1256791
public function checkClientCredentials($client_id, $client_secret = null)
    {
        $client = $this->getClientDetails($client_id);
        return isset($client['client_secret'])
            && $client['client_secret'] == $client_secret;
    }
189119
public static function getOpenid($app_id, $app_secret, $code)
    {
        $url = WxpubOAuth::_createOauthUrlForOpenid($app_id, $app_secret, $code);
        $res = self::_getRequest($url);
        $data = json_decode($res, true);

        return $data['openid'];
    }
963178
def create_client(self, client_id, client_secret):
        
        assert self.is_admin, "Must authenticate() as admin to create client"
        return self.uaac.create_client(client_id, client_secret)
948910
private boolean verifyIpAddress(String ipAddress, X509Certificate certificate) {
        List<String> altNames = getSubjectAltNames(certificate, ALT_IPA_NAME);
        for (int i = 0, size = altNames.size(); i < size; i++) {
            if (ipAddress.equalsIgnoreCase(altNames.get(i))) {
                return true;
            }
        }

        X500Principal principal = certificate.getSubjectX500Principal();
        // RFC 2818 advises using the most specific name for matching.
        String cn = new DistinguishedNameParser(principal).findMostSpecific("cn");

        // NOTE: In case of empty Common Name (CN), not checking
        return (cn == null) || ipAddress.equalsIgnoreCase(cn);
    }
1164601
public CompletableFuture<Revision> createToken(Author author, String appId, String secret,
                                                   boolean isAdmin) {
        requireNonNull(author, "author");
        requireNonNull(appId, "appId");
        requireNonNull(secret, "secret");

        checkArgument(secret.startsWith(SECRET_PREFIX), "secret must start with: " + SECRET_PREFIX);

        final Token newToken = new Token(appId, secret, isAdmin, UserAndTimestamp.of(author));
        final JsonPointer appIdPath = JsonPointer.compile("/appIds" + encodeSegment(newToken.id()));
        final String newTokenSecret = newToken.secret();
        assert newTokenSecret != null;
        final JsonPointer secretPath = JsonPointer.compile("/secrets" + encodeSegment(newTokenSecret));
        final Change<JsonNode> change =
                Change.ofJsonPatch(TOKEN_JSON,
                                   asJsonArray(new TestAbsenceOperation(appIdPath),
                                               new TestAbsenceOperation(secretPath),
                                               new AddOperation(appIdPath, Jackson.valueToTree(newToken)),
                                               new AddOperation(secretPath,
                                                                Jackson.valueToTree(newToken.id()))));
        return tokenRepo.push(INTERNAL_PROJ, Project.REPO_DOGMA, author,
                              "Add a token: '" + newToken.id(), change);
    }
971298
public static function validateIpAddress($ipAddress) {
        if (strtolower($ipAddress) === 'unknown') {
            return false;
        }

        // generate ipv4 network address
        $ipAddress = ip2long($ipAddress);

        // if the ip is set and not equivalent to 255.255.255.255
        if ($ipAddress !== false && $ipAddress !== -1) {
            // make sure to get unsigned long representation of ip
            // due to discrepancies between 32 and 64 bit OSes and
            // signed numbers (ints default to signed in PHP)
            $ipAddress = sprintf('%u', $ipAddress);
            // do private network range checking
            if ($ipAddress >= 0 && $ipAddress <= 50331647) {
                return false;
            }
            if ($ipAddress >= 167772160 && $ipAddress <= 184549375) {
                return false;
            }
            if ($ipAddress >= 2130706432 && $ipAddress <= 2147483647) {
                return false;
            }
            if ($ipAddress >= 2851995648 && $ipAddress <= 2852061183) {
                return false;
            }
            if ($ipAddress >= 2886729728 && $ipAddress <= 2887778303) {
                return false;
            }
            if ($ipAddress >= 3221225984 && $ipAddress <= 3221226239) {
                return false;
            }
            if ($ipAddress >= 3232235520 && $ipAddress <= 3232301055) {
                return false;
            }
            if ($ipAddress >= 4294967040) {
                return false;
            }
        }
        return true;
    }
801505
public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException {
        String algorithm = detectKeyAlgorithm(key);
        writeUTF(algorithm);
        writeKey(key.getPublic());

        Signature sig = Signature.getInstance("SHA1with"+algorithm);
        sig.initSign(key.getPrivate());
        sig.update(key.getPublic().getEncoded());
        sig.update(sharedSecret);
        writeObject(sig.sign());
    }
907813
protected Single<Boolean> isValidClientCredentials(String clientId, String clientSecret) {
        return db.findClientCredentials(clientId)
                .map(creds -> creds.getSecret().equals(clientSecret))
                .switchIfEmpty(Single.just(false))
                ;
    }