ReCaptcha API with different language on android - android

I am using reCaptcha API on android through SafetyNet API as given on Android Developer site.
My application is multilingual application. When I all together change phones language setting, my reCaptcha appears in that language. But I want to change language according to selected locale on app level without changing phone language settings. Google docs has given language codes here. Can anyone help me with implementing this thing. Any help or any suggestion will be appreciated.
This is my current code. This works with default phone language very well. I explored available methods for specifying language but no luck.
public void verify() {
SafetyNetClient client = SafetyNet.getClient(activity);
Task<SafetyNetApi.RecaptchaTokenResponse> verifierTask = client.verifyWithRecaptcha(activity.getResources().getString(R.string.site_key));
verifierTask.addOnSuccessListener(activity, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
#Override
public void onSuccess(SafetyNetApi.RecaptchaTokenResponse recaptchaTokenResponse) {
String userResponseToken = recaptchaTokenResponse.getTokenResult();
if (!userResponseToken.isEmpty()) {
new CaptchaVerificationTask().execute(userResponseToken);
} else {
captchaVerificationListener.onFailure();
}
}
}
).addOnFailureListener(activity, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException) {
// An error occurred when communicating with the
// reCAPTCHA service. Refer to the status code to
// handle the error appropriately.
ApiException apiException = (ApiException) e;
int statusCode = apiException.getStatusCode();
Log.d("Login ReCaptcha", "Error: " + CommonStatusCodes
.getStatusCodeString(statusCode));
} else {
// A different, unknown type of error occurred.
Log.d("Login ReCaptcha", "Error: " + e.getMessage());
}
captchaVerificationListener.onFailure();
}
});
}

Related

In-Mobi Ad platform always return NO_FILL eventhough it is in test version

I am integrating my android app with inmobi sdk for ads. However, I always get NO_FILL error from the ad server even though my placement is set to test globally. I am using an emulator.
I double-check the account id and placement id but everything seems okay.
JSONObject consentObject = new JSONObject();
try {
// Provide correct consent value to sdk which is obtained by User
consentObject.put(InMobiSdk.IM_GDPR_CONSENT_AVAILABLE, true);
// Provide 0 if GDPR is not applicable and 1 if applicable
//consentObject.put("gdpr", "1");
} catch (JSONException e) {
e.printStackTrace();
}
InMobiSdk.init(Mytoz.getInstance().getApplicationContext(), "MY_ACCOUNT_ID", consentObject);
InMobiSdk.setLogLevel(InMobiSdk.LogLevel.DEBUG);
MY_ACCOUNT_ID being my real id, this the code that I am initializing the
sdk.
InterstitialAdEventListener mInterstitialAdEventListener = new InterstitialAdEventListener() {
// implementation for other events
// onAdLoadSucceeded, onAdDisplayed, etc
#Override
public void onRewardsUnlocked(InMobiInterstitial inMobiInterstitial, Map<Object, Object> map) {
Log.e(TAG, "Ad rewards unlocked!");
interstitialAd.load();
}
#Override
public void onAdLoadSucceeded(InMobiInterstitial inMobiInterstitial) {
Log.e(TAG, "Ad can now be shown!");
canShowAd = true;
}
#Override
public void onAdLoadFailed(InMobiInterstitial ad, InMobiAdRequestStatus requestStatus) {
Log.e(TAG, "onAdLoadFailed: " + requestStatus.getMessage() + " " + requestStatus.getStatusCode());
canShowAd = false;
}
};
interstitialAd = new InMobiInterstitial(MainActivity.this, MY_PLACEMENT_ID, mInterstitialAdEventListener);
interstitialAd.load();
MY_PLACEMENT_ID being my real placement id
I am expecting to see a test ad but no, I am getting NO_FILL
InMobi provides very few initial ads from emulator. After that on emulator it will start giving NO_FILL. You must use real device to test the ads.

Android: SafetyNet Attest Device Verification Response Network Error

I'm calling SafetyNet Api using Google Client but it not responding the correct response.
SafetyNet.SafetyNetApi.attest(mGoogleApiClient, generateNonce())
.setResultCallback(new ResultCallback<SafetyNetApi.AttestationResult>() {
#Override
public void onResult(SafetyNetApi.AttestationResult result) {
Status status = result.getStatus();
String data = decodeJws(result.getJwsResult());
if (status.isSuccess()) {
// Indicates communication with the service was successful.
// Use result.getJwsResult() to get the result data.
} else {
// An error occurred while communicating with the service.
}
}
});
I'm getting below error message in result method.
Status{statusCode=NETWORK_ERROR, resolution=null}
Any kind of help would be highly appreciated.
This doesn't work because you are using SafetyNetApi, which is no longer supported.
Starting with Google Play Services 11.0.0, you should now get an API key, and use SafetyNetClient instead.
You may also want to take a look at 10 things you might be doing wrong when using the SafetyNet Attestation API.
First you have to generate nonce by following method
private static byte[] getRequestNonce() {
String data = String.valueOf(System.currentTimeMillis());
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[24];
Random random = new Random();
random.nextBytes(bytes);
try {
byteStream.write(bytes);
byteStream.write(data.getBytes());
}catch (IOException e) {
return null;
}
return byteStream.toByteArray();
}
Afterwords use safety net client attestation api
SafetyNet.getClient(context).attest(nonce, <API KEY>).addOnSuccessListener(new OnSuccessListener<SafetyNetApi.AttestationResponse>() {
#Override
public void onSuccess(SafetyNetApi.AttestationResponse attestationResponse) {
// parse response
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// An error occurred while communicating with the service.
}
});
}
Reference: Sample Code Offline verification
Sample Code Online verification using google api

Safetynet Issue Status{statusCode=NETWORK_ERROR, resolution=null}

We have follow Scottyab Safetynet Library.
We are facing error of “Status{statusCode=NETWORK_ERROR, resolution=null}” event though 4G internet connectivity available in our android device with package name com.safetynet.sample where as sample project is working fine with package name com.scottyab.safetynet.sample. We have check this solution but not work.
Below code where we have facing this issue
private void runSafetyNetTest() {
Log.v(TAG, "running SafetyNet.API Test");
requestNonce = generateOneTimeRequestNonce();
requestTimestamp = System.currentTimeMillis();
writeLog("running SafetyNet.API Test");
SafetyNet.SafetyNetApi.attest(googleApiClient, requestNonce)
.setResultCallback(new ResultCallback<SafetyNetApi.AttestationResult>() {
#Override
public void onResult(final SafetyNetApi.AttestationResult result) {
writeLog("running SafetyNet.API Result");
//result = Status{statusCode=NETWORK_ERROR, resolution=null}
if (!validateResultStatus(result)) {
return;
}
final String jwsResult = result.getJwsResult();
final SafetyNetResponse response = parseJsonWebSignature(jwsResult);
lastResponse = response;
writeLog("Res :: " + response);
//validate payload of the response
if (validateSafetyNetResponsePayload(response)) {
if (!TextUtils.isEmpty(googleDeviceVerificationApiKey)) {
//if the api key is set, run the AndroidDeviceVerifier
AndroidDeviceVerifier androidDeviceVerifier = new AndroidDeviceVerifier(googleDeviceVerificationApiKey, jwsResult);
androidDeviceVerifier.verify(new AndroidDeviceVerifier.AndroidDeviceVerifierCallback() {
#Override
public void error(String errorMsg) {
callback.error(RESPONSE_ERROR_VALIDATING_SIGNATURE, "Response signature validation error: " + errorMsg);
}
#Override
public void success(boolean isValidSignature) {
if (isValidSignature) {
callback.success(response.isCtsProfileMatch(), response.isBasicIntegrity());
} else {
callback.error(RESPONSE_FAILED_SIGNATURE_VALIDATION, "Response signature invalid");
}
}
});
} else {
Log.w(TAG, "No google Device Verification ApiKey defined");
callback.error(RESPONSE_FAILED_SIGNATURE_VALIDATION_NO_API_KEY, "No Google Device Verification ApiKey defined. Marking as failed. SafetyNet CtsProfileMatch: " + response.isCtsProfileMatch());
}
} else {
callback.error(RESPONSE_VALIDATION_FAILED, "Response payload validation failed");
}
}
}
);
}
This might be related to the fact that the attestation API has been marked as deprecated. The new one doesn't depend on the google client API, you should check this. Also Google released an example app using the new api, you can check here.
As per this discussion, the wrong API_KEY may be the reason for the error.

How to get aws-iot thing shadow on android app

want to start development with AWS IOT using Android app
I am seeking for example for IOT in android. need to start basic configuration on AWS console and android app. i already tested temperature demo but didn't get any clue from that! need a basic steps on shadow, policy , role. how to configure them step by step and use of cognito.
below getshadow() method is called onCreate , need to update value on real time basis not ony onCreate.
public void getShadows() {
GetShadowTask getControlShadowTask = new GetShadowTask("TemperatureControl");
getControlShadowTask.execute();
}
private class GetShadowTask extends AsyncTask<Void, Void, AsyncTaskResult<String>> {
private final String thingName;
public GetShadowTask(String name) {
thingName = name;
}
#Override
protected AsyncTaskResult<String> doInBackground(Void... voids) {
try {
GetThingShadowRequest getThingShadowRequest = new GetThingShadowRequest()
.withThingName(thingName);
GetThingShadowResult result = iotDataClient.getThingShadow(getThingShadowRequest);
// Toast.makeText(getApplication(),result.getPayload().remaining(),Toast.LENGTH_LONG).show();
byte[] bytes = new byte[result.getPayload().remaining()];
result.getPayload().get(bytes);
String resultString = new String(bytes);
return new AsyncTaskResult<String>(resultString);
} catch (Exception e) {
Log.e("E", "getShadowTask", e);
return new AsyncTaskResult<String>(e);
}
}
#Override
protected void onPostExecute(AsyncTaskResult<String> result) {
if (result.getError() == null) {
JsonParser parser=new JsonParser();
JsonObject jsonObject= (JsonObject) parser.parse(result.getResult());
response=result.getResult();
setPoint=jsonObject.getAsJsonObject("state").getAsJsonObject("reported")
.get("current_date").getAsString();
textView.setText(setPoint);
// Toast.makeText(getApplication(),setPoint,Toast.LENGTH_LONG).show();
Log.i(GetShadowTask.class.getCanonicalName(), result.getResult());
} else {
Log.e(GetShadowTask.class.getCanonicalName(), "getShadowTask", result.getError());
Toast.makeText(getApplication(),result.getError().toString(),Toast.LENGTH_LONG).show();
}
}
}
UPDATE
Thing Shadow
{
"desired": {
"welcome": "aws-iot"
},
"reported": {
"welcome": "aws-iot",
"current_date": "06-Sep-2017 1:26:40 PM"
}
}
AWS has provided a complete Github repo of Android samples. In the samples do the PubSubWebSocket to connect, subscribe and publish the data to the shadow.
If you have a closer look into the PubSubWebSocket example you will find a detailed information on how to to make a thing policy and role. It cannot be more concise and clear than that.
For understanding and using Cognito follow AmazonCognitoAuthDemo example to make the identity pool and use it in the PubSubWebSocket example.
To get a better understanding of roles and Cognito. Please read the AWS documentation.
Update:
In the IoT thing policy did you give appropriate permissions to connect, subscribe and publish. The option can be found in AWS IoT->Security->Policy->Create Policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:*",
"Resource": "arn:aws:iot:us-east-2:293751794947:topic/replaceWithATopic"
}
]
}
The above policy gives all access to the user. Also, make sure your pool which you created is for unauthenticated users.
To get the changes to the shadow type the following in the sample android(WebSocketAwsPubSub) edit box $aws/things/thing_name/shadow/update/accepted
And to publish the data to the shadow type $aws/things/thing_name/shadow/update
Update 2:
Android Code where you will receive the reported messaged. Its suscribing to the device. Its the copy of the snippet from PubSubWebSocketSample.
public void AwsSubscribe(){
final String topic = "$aws/things/D1/shadow/update/accepted";
Log.d(LOG_TAG, "topic = " + topic);
try {
mqttManager.subscribeToTopic(topic, AWSIotMqttQos.QOS0,
new AWSIotMqttNewMessageCallback() {
#Override
public void onMessageArrived(final String topic, final byte[] data) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
String message = new String(data, "UTF-8");
Log.d(LOG_TAG, "Message arrived:");
Log.d(LOG_TAG, " Topic: " + topic);
Log.d(LOG_TAG, " Message: " + message);
tvLastMessage.setText(message);
} catch (UnsupportedEncodingException e) {
Log.e(LOG_TAG, "Message encoding error.", e);
}
}
});
}
});
} catch (Exception e) {
Log.e(LOG_TAG, "Subscription error.", e);
}
}
If you want to create a topic, just change the value of this variable final String topic = "YOUR TOPIC" then subscribe to it by using the sample code.

How to logout/change Twitter account with Parse

I know how to login:
ParseTwitterUtils.logIn(loginView.getCurrentContext(), new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
String welcomeMessage = "";
if (parseUser.isNew()) {
welcomeMessage = "Hello new guy!";
} else {
welcomeMessage = "Welcome back!";
}
loginView.showLoginSuccess(parseUser, welcomeMessage);
} else {
String errorMessage = "Seems we have a problem : " + e.getLocalizedMessage();
loginView.showLoginFail(errorMessage);
}
}
});
And to logout :
ParseUser.logOutInBackground(new LogOutCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
homeView.goLogin(true, "See you soon");
} else {
homeView.goLogin(false, "Error detected : " + e.getLocalizedMessage());
}
}
});
But when I want to log in again, I don't have the alert dialog asking me to choose accounts (i use the webview since Twitter app is not installed on the emulator).
How to truly logout from Parse using Twitter login?
In iOS, you can revise the source code of Parse in PFOauth1FlowDialog.m
- (void)loadURL:(NSURL *)url queryParameters:(NSDictionary *)parameters {
NSMutableDictionary *_parameter = [[NSMutableDictionary alloc] init];
[_parameter setObject:#"true" forKey:#"force_login"];
[_parameter addEntriesFromDictionary:parameters];
_loadingURL = [[self class] _urlFromBaseURL:url queryParameters:_parameter];
NSURLRequest *request = [NSURLRequest requestWithURL:_loadingURL];
[_webView loadRequest:request];
}
Then everything should work fine, And this should also work in Android.
Use the unlink functions from ParseTwitterUtils:
https://parse.com/docs/android/api/com/parse/ParseTwitterUtils.html#unlink(com.parse.ParseUser)
This will remove the link between the twitter account and the parse user.
The confusion seems to stem from the fact that the api is so straightforward.
What you're doing in the login is associating a twitter account with a parse user and logging in as that parse user. Then when you are logging out, you are only logging out of the parse user, and the twitter account is still linked to the parse user. Therefore when you go to log in again it automatically uses the twitter account to log in as the parse user.

Categories

Resources