Flutter Web Error: [firebase_functions/internal] internal - flutter

I have a HTTP Callable Cloud Function written in Python that does some calculations and updates some Firestore documents.
It is actually working for both the android emulator and Chrome (Flutter-Web).
Still, I get the following error when I trigger it from Chrome (Flutter-Web):
Instance of '_Future<HttpsCallableResult<dynamic>>'
Error: [firebase_functions/internal] internal
at Object.throw_ [as throw] (http://localhost:54521/dart_sdk.js:5067:11)
at https_callable_web.HttpsCallableWeb.new.call (http://localhost:54521/packages/cloud_functions_web/https_callable_web.dart.lib.js:45:23)
at call.throw (<anonymous>)
at http://localhost:54521/dart_sdk.js:40576:38
at _RootZone.runBinary (http://localhost:54521/dart_sdk.js:40445:59)
at _FutureListener.thenAwait.handleError (http://localhost:54521/dart_sdk.js:35374:33)
at handleError (http://localhost:54521/dart_sdk.js:35947:51)
at Function._propagateToListeners (http://localhost:54521/dart_sdk.js:35973:17)
at _Future.new.[_completeError] (http://localhost:54521/dart_sdk.js:35823:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:54521/dart_sdk.js:35859:31)
at Object._microtaskLoop (http://localhost:54521/dart_sdk.js:40708:13)
at _startMicrotaskLoop (http://localhost:54521/dart_sdk.js:40714:13)
at http://localhost:54521/dart_sdk.js:36191:9
In the GCP Log I do not have any error shown.
This is what I return from the CF return '{"status":"200", "data": "OK"}'
In the chrome developers tools under the Network tab and status I get a CORS error. I did read quite a lot of SO Questions and I did understand that the CORS error is apparently no the real reason of the error.
Also in the same tab (Network) under Headers -> Request Headers there is shown the following Provisional headers are shown, in the Payload the value {data:null} and Response has nothing to show, which is weird since I am returning a "data": "OK".
I am fully confused, since the error thrown: internal error is not leading me anywhere.

I finally fixed it by omitting region() on the cloud function.
My original code:
exports.checkAuth = functions.region("asia-southeast1").https.onCall(async (data, context: functions.https.CallableContext) => {
return `uid: ${context.auth?.uid ?? "X"} - email: ${context.auth?.token.email ?? "X"}`;
});
I changed it to:
exports.checkAuth = functions.https.onCall(async (data, context: functions.https.CallableContext) => {
return `uid: ${context.auth?.uid ?? "X"} - email: ${context.auth?.token.email ?? "X"}`;
});
===UPDATE===
The real root cause is the region you specified in the cloud functions and the firebase functions are different, for example in my original code I used:
functions.region("asia-southeast1").https.onCall()
So, when I instantiate firebase functions in main.dart I must do this:
void main() async {
...
final firebaseFunctions = FirebaseFunctions.instanceFor(region: 'asia-southeast1');
...
}

Related

CERTIFICATE_VERIFY_FAILED when trying to import data from API

I'm trying to learn Flutter/Dart and I'm having to much problems. Now I'm trying to obtain some values from an API. My code is:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:myapp01_apirequest/src/models/uplink_models.dart';
class UplinksProvider{
String _url = 'xxx.yyy.com';
Future<List<Uplink>> getEnCines() async{
try{
final url = Uri.https(_url, ':14442/api/external/login', {
'username': 'Joe689',
'password': '15.Job_1825zz'
});
final resp = await http.get(url);
final decodedData = json.decode(resp.body);
print('Patata');
print(decodedData);
return [];
}catch (error){
print('++++++++++///////++++++++++++++++');
print(error);
print('++++++++++*******++++++++++++++++');
}
}
}
Reading the Uri constructor documentation I understood that I have to split in 3 my url.
First one is authority. In my case I think is xxx.yyy.com.
Second is the unencodedPath. In my case I think is :14442/api/external/login.
Finally a map with params in my case the username and pass (the only thing I'm pretty sure is correct in my code).
If I do this, any problem appears, but the print('Patata'); and print(decodeData); don't appear. In addition, a file called io_client.dart opens and marks the next line.
var ioRequest = (await _inner.openUrl(request.method, request.url))
The console shows nothing (I think):
Launching lib\main.dart on LG M700 in debug mode...
lib\main.dart:1
Formato de par�metros incorrecto:
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:55883/KBAtv2-Jljc=/ws
Why no errors appears but I can't obtain my desired data?
EDIT:
According for what #Preet Shah's said I press the "VS run button" and appears the following exception three times:
I/flutter ( 1932): ++++++++++///////++++++++++++++++
I/flutter ( 1932): HandshakeException: Handshake error in client (OS Error:
I/flutter ( 1932): CERTIFICATE_VERIFY_FAILED: Hostname mismatch(handshake.cc:354))
I/flutter ( 1932): ++++++++++*******++++++++++++++++
And finally appears:
I/Choreographer( 1932): Skipped 148531 frames! The application may be doing too much work on its main thread.
D/vndksupport( 1932): Loading /vendor/lib/hw/android.hardware.graphics.mapper#2.0-impl.so from current namespace instead of sphal namespace.
D/vndksupport( 1932): Loading /vendor/lib/hw/gralloc.msm8937.so from current namespace instead of sphal namespace.
I/Choreographer( 1932): Skipped 35 frames! The application may be doing too much work on its main thread.
Then the problem is a certification problem, CERTIFICATE_VERIFY_FAILED. As I feel more comfortable with python, I have done some tests to understand the problem. I have been able to verify that this API requires having all the certification verifications in false, otherwise it never leaves the loop. Here is my Python code (just to show what I'm saying).
import requests
import json
log_params = {'username': 'Joe689', 'password': '15.Job_1825zz'}
headers = {'Content-type': 'application/json'}
url = 'https://xxx.yyy.com:14442/api/external/login'
response = requests.post(url, data=json.dumps(params), headers=self.headers, verify=False)
finalRes = json.loads(response.text)
As I said, this code is just for me to understand the problem because I am a newbie to Dart. Here I found this answer and it seems has the solution but I don't know how to implement it, using my Uri.https estructure (maybe it's not possible).
I tried this, but isn't working:
Map<String, String> requestHeaders = {
'Content-type': 'application/json'
};
final resp = await http.get(url, headers:requestHeaders);
Thank you very much.
Try this:
HttpClient client = new HttpClient();
client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
String url ='xxx.yyy.com:14442/api/external/login';
Map map = {
"email" : "Joe689" ,
"password" : "15.Job_1825zz"
};
HttpClientRequest request = await client.getUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
Now, check what reply contains. And accordingly, return the data.

Class variable is undefined... despite being defined

I have a class called RouteBinder that looks like this:
class RouteBinder
constructor: (#server, #pool) ->
bindRoute: (name, fn, method = "post", useDb = true) ->
#server[method]("/api/accounts/v1/" + name, (req, res, next) ->
client = await #pool.connect() if useDb?
await fn req, res, next, client
await #pool.release() if useDb?
)
I declare it and call it like this:
binder = new RouteBinder server, pool
binder.bindRoute "login", controllers.login
(Pool is node-postgres's Pool and is declared and tested earlier like this)
pool = new Pool
[...]
try
client = await pool.connect()
await client.query 'SELECT 1=1'
catch e
console.fatal "Could not connect to database: #{e}"
return
finally
try client.release() if client?
catch e
console.fatal "Couldn't release client: #{e}"
return
console.info 'Database is OK!'
When running this, I get this error:
02/14 18:44:34 error (node:11855) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'connect' of undefined
at _callee2$ (/home/vi/[redacted]_accounts/main.js:136:38)
at tryCatch (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:45:40)
at Generator.invoke [as _invoke] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:271:22)
at Generator.prototype.(anonymous function) [as next] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:97:21)
at asyncGeneratorStep (/home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:3:24)
at _next (/home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:25:9)
at /home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at /home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:21:12
at /home/vi/[redacted]_accounts/main.js:166:26
02/14 18:44:34 error (node:11855) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
02/14 18:44:34 error (node:11855) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm using CoffeeScript compiled transpiled with Babel. My .babelrc looks like this:
{
"presets": ["#babel/env"],
"plugins": [
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
Sorry if it's a rookie question, I'm still learning and would love all the advice I can get.
I figured out my mistake. Both #pool and #server were defined, however, the inline function (handler) for #server[method] was running in the context of that function.
The solution was to bind it to the RouteBinder instance using .bind(#) (or .bind(this), if you prefer)
bindRoute: (name, fn, method = "post", useDb = true) ->
#server[method]("/api/accounts/v1/" + name, ((req, res, next) ->
console.log "pool", #pool
client = await #pool.connect() if useDb?
await fn req, res, next, client
await #pool.release() if useDb?
).bind(#))

Salesforce making REST calls using access token uses local host rather instance url

I am using a ionic app and have implemented oauth using forcejs described here https://github.com/ccoenraets/forcejs/blob/master/README.md
my code looks like below:
getContacts(){
let service = DataService.getInstance();
service.query('select id, Name from contact LIMIT 50')
.then(response => {
let contacts = response.records;
console.log(JSON.stringify(contacts))
});
}
login(){
let oauth = OAuth.createInstance('mycousmerappid','','http://localhost:8100/tabs/tab1');
oauth.login().then(oauthResult => {
DataService.createInstance(oauthResult);
console.log("Logged Into Salesforce Successfully:::" + JSON.stringify(oauthResult));
this.getContacts()
});
}
the oauth token instance url and refresh token all comes up in login but get contact throws error as below
zone-evergreen.js:2952 GET http://localhost:8100/tabs/services/data/v41.0/query?q=select%20id%2C%20Name%20from%20contact%20LIMIT%2050 404 (Not Found)
scheduleTask # zone-evergreen.js:2952
scheduleTask # zone-evergreen.js:378
onScheduleTask # zone-evergreen.js:272
core.js:9110 ERROR Error: Uncaught (in promise): XMLHttpRequest: {"__zone_symbol__readystatechangefalse":[{"type":"eventTask","state":"scheduled","source":"XMLHttpRequest.addEventListener:readystatechange","zone":"angular","runCount":8}],"__zone_symbol__xhrSync":false,"__zone_symbol__xhrURL":"http://localhost:8100/tabs/services/data/v41.0/query?q=select%20id%2C%20Name%20from%20contact%20LIMIT%2050","__zone_symbol__xhrScheduled":true,"__zone_symbol__xhrErrorBeforeScheduled":false,"__zone_symbol__xhrTask":{"type":"macroTask","state":"scheduled","source":"XMLHttpRequest.send","zone":"angular","runCount":0}}
at resolvePromise (zone-evergreen.js:797)
at resolvePromise (zone-evergreen.js:754)
at zone-evergreen.js:858
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:34182)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
at drainMicroTaskQueue (zone-evergreen.js:559)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:469)
at invokeTask (zone-evergreen.js:1603)
based on link i am not expecting it to use the base url localhost. Please advise how to fix this issue
i dont know how to resolve the same way but then i used direct http rest format using the accessToken and instanceUrl coming from oAuth. That works just fine

GitHub Probot : ERROR probot: Bad Request

I am developing an application for Probot. I have configured .envand already downloaded PEM file in the folder.
Here is the content of file index.js.
module.exports = (robot) => {
robot.on('issues.opened', async context => {
const params = context.issue({ body: 'Hello World!' })
return context.github.issues.createComment(params)
})
}
But I am getting this error.
ERROR probot: Bad Request
Error: Bad Request
at Request.callback (/media/ashutosh/ASHUTOSH ( PERSONAL )/Gsoc/probot/practice/ashutosh-probot/node_modules/superagent/lib/node/index.js:696:15)
at IncomingMessage.parser (/media/ashutosh/ASHUTOSH ( PERSONAL )/Gsoc/probot/practice/ashutosh-probot/node_modules/superagent/lib/node/index.js:906:18)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
How to fix this issue?
This error not because of Probot, but the error is on GitHub ends.
This error is possibly because you have entered wrong User authorization call back URL, while creating a new GitHub application. Updating this will fix the issue.

Google authentication

I got a problem on google authenticate, it worked for a month but since a few days I got this error :
Fatal error: Uncaught exception 'apiAuthException' with message
'Invalid token format' in /home/project/html/google/auth/apiOAuth2.php:127 Stack trace:
#0 /home/project/html/google/auth/apiOAuth2.php(89): apiOAuth2->setAccessToken('{? "access_tok...')
#1 /home/project/html/google/apiClient.php(132): apiOAuth2->authenticate(Array)
#2 /home/project/html/hk/connects/google.php(22): apiClient->authenticate()
#3 {main} thrown in /home/project/html/google/auth/apiOAuth2.php on line 127
In apiOAuth2.php I have the code :
$accessToken = json_decode($accessToken, true);
if (! isset($accessToken['access_token']) || ! isset($accessToken['expires_in']) || ! isset($accessToken['refresh_token'])) {
throw new apiAuthException("Invalid token format");
}
I noticed that google doesn't send me the $accessToken['refresh_token'].
It doesn't seem to come from google cause I did a correct connexion on http://stackoverflow.com
Maybe it's cause of my code :
session_start();
$client = new apiClient();
$plus = new apiPlusService($client);
if (!isset($_GET['code'])) {
header('Location: '.$client->createAuthUrl()); // Calls the same page
} else {
$client->authenticate(); // Fails at this level
}
EDIT:
I figured a way to do it, like I don't know what is refresh_token made for I added this line :
if (!isset($accessToken['refresh_token'])) $accessToken['refresh_token'] = 12345678910;
It works for the moment...
There is a new explicit parameter called "access_type" required by the google authentication api to obtain a valid refresh token.
With this parameter you declare that you need offline access to the account and the api provides you a refresh token.
Download the latest google PHP SDK that automatically handles the new required parameter