Uncaught Exception with try catch in Dart - flutter

I'm building a flutter app that uses SignalR. For this purpose I'm using signalr_core library. So far things work well when the server is up and running and I provide a valid authentication token, but when I provided a wrong token and start the connection I get the following error:
Error: Expected a value of type 'Error', but got one of type 'WebSocketChannelException'
at Object.throw_ [as throw] (http://localhost:64659/dart_sdk.js:4348:11)
at Object.castError (http://localhost:64659/dart_sdk.js:4319:15)
at Object.cast [as as] (http://localhost:64659/dart_sdk.js:4635:17)
at dart.LegacyType.new.as (http://localhost:64659/dart_sdk.js:6212:60)
at http://localhost:64659/packages/signalr_core/src/json_hub_protocol.dart.lib.js:2129:44
at _RootZone.runUnaryGuarded (http://localhost:64659/dart_sdk.js:37736:11)
at sendError (http://localhost:64659/dart_sdk.js:31344:26)
at _ControllerSubscription.new.[_sendError] (http://localhost:64659/dart_sdk.js:31359:11)
at _ControllerSubscription.new.[_addError] (http://localhost:64659/dart_sdk.js:31282:27)
at _SyncStreamController.new.[_sendError] (http://localhost:64659/dart_sdk.js:34230:39)
at _SyncStreamController.new.[_addError] (http://localhost:64659/dart_sdk.js:34042:27)
at _SyncStreamController.new.addError (http://localhost:64659/dart_sdk.js:34012:24)
at _RootZone.runBinaryGuarded (http://localhost:64659/dart_sdk.js:37753:11)
at sendError (http://localhost:64659/dart_sdk.js:31342:26)
at _ControllerSubscription.new.[_sendError] (http://localhost:64659/dart_sdk.js:31359:11)
at _ControllerSubscription.new.[_addError] (http://localhost:64659/dart_sdk.js:31282:27)
at _SyncStreamController.new.[_sendError] (http://localhost:64659/dart_sdk.js:34230:39)
at _SyncStreamController.new.[_addError] (http://localhost:64659/dart_sdk.js:34042:27)
at _SyncStreamController.new.addError (http://localhost:64659/dart_sdk.js:34012:24)
at _StreamSinkWrapper.new.addError (http://localhost:64659/dart_sdk.js:34339:24)
at _GuaranteeSink.new.[_addError] (http://localhost:64659/packages/stream_channel/src/stream_channel_controller.dart.lib.js:1223:26)
at _GuaranteeSink.new.addError (http://localhost:64659/packages/stream_channel/src/stream_channel_controller.dart.lib.js:1218:24)
at http://localhost:64659/packages/web_socket_channel/html.dart.lib.js:199:36
at _RootZone.runUnary (http://localhost:64659/dart_sdk.js:37810:58)
at _FutureListener.then.handleValue (http://localhost:64659/dart_sdk.js:32771:29)
at handleValueCallback (http://localhost:64659/dart_sdk.js:33319:49)
at Function._propagateToListeners (http://localhost:64659/dart_sdk.js:33357:17)
at _Future.new.[_complete] (http://localhost:64659/dart_sdk.js:33190:25)
at Object._cancelAndValue (http://localhost:64659/dart_sdk.js:38220:24)
at http://localhost:64659/dart_sdk.js:18845:17
at Object._checkAndCall (http://localhost:64659/dart_sdk.js:4558:16)
at Object.dcall (http://localhost:64659/dart_sdk.js:4563:17)
at WebSocket.<anonymous> (http://localhost:64659/dart_sdk.js:104962:23)
Although I did catch the exception in my code.
Here is the connection initialization code:
_connection = HubConnectionBuilder()
.withAutomaticReconnect() //
.withUrl(
_URL,
HttpConnectionOptions(
logging: (level, message) => print(message),
skipNegotiation: true,
transport: HttpTransportType.webSockets,
accessTokenFactory: () {
return Future.value('wrongToken');
},
)) //
.build(); //
As for connection start code:
void start() async {
try {
_streamingStateController.add(StreamingInfo(StreamingState.Starting));
await _connection.start();
_listenToGPSChange();
_streamingStateController.add(StreamingInfo(StreamingState.Started));
} on Exception catch (exception) {
_handleError('Oops. Unable to connect to the server.');
} on Error catch (error) {
_handleError('Oops. Unable to connect to the server.');
}
}
Please not that I get the same error when the connection succeeds (in case of valid parameters) but afterwards a shut down my server and send a message.
So the question is, how do I catch this type of errors?

Related

Why I get "Cannot read properties of undefined (reading 'default') while connecting with WalletConnectProvider"? in Flutter

I am getting the folling error when I want to connect to trustWallet or Metamask through walletconnect with flutter_web3 package.
Error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'default')
at WalletConnectProvider.fromRpc (wallet_connect.dart:86:7)
at web3_controller_notifier.Web3ControllerNotifier.new.connectWithWalletConnect (web3_controller_notifier.dart:73:52)
at connectWithWalletConnect.next (<anonymous>)
at runBody (async_patch.dart:84:54)
at Object._async [as async] (async_patch.dart:123:5)
at web3_controller_notifier.Web3ControllerNotifier.new.connectWithWalletConnect (web3_controller_notifier.dart:72:32)
at home_page.dart:86:51
at ink_well._InkResponseState.new.handleTap (ink_well.dart:1084:21)
at tap.TapGestureRecognizer.new.invokeCallback (recognizer.dart:282:24)
at tap.TapGestureRecognizer.new.handleTapUp (tap.dart:660:11)
at [_checkUp] (tap.dart:311:5)
at tap.TapGestureRecognizer.new.handlePrimaryPointer (tap.dart:244:7)
at tap.TapGestureRecognizer.new.handleEvent (recognizer.dart:647:9)
at [_dispatch] (pointer_router.dart:98:12)
at pointer_router.dart:143:9
at LinkedMap.new.forEach (linked_hash_map.dart:21:13)
at [_dispatchEventToRoutes] (pointer_router.dart:141:17)
at pointer_router.PointerRouter.new.route (pointer_router.dart:127:7)
at binding$5.WidgetsFlutterBinding.new.handleEvent (binding.dart:456:19)
at binding$5.WidgetsFlutterBinding.new.dispatchEvent (binding.dart:436:14)
at binding$5.WidgetsFlutterBinding.new.dispatchEvent (binding.dart:333:11)
at [_handlePointerEventImmediately] (binding.dart:391:7)
at binding$5.WidgetsFlutterBinding.new.handlePointerEvent (binding.dart:354:5)
at [_flushPointerEventQueue] (binding.dart:311:7)
at [_handlePointerDataPacket] (binding.dart:292:7)
at Object.invoke1 (platform_dispatcher.dart:1221:13)
at _engine.EnginePlatformDispatcher.new.invokeOnPointerDataPacket (platform_dispatcher.dart:243:5)
at [_onPointerData] (pointer_binding.dart:167:39)
at pointer_binding.dart:778:20
at pointer_binding.dart:707:14
at loggedHandler (pointer_binding.dart:317:16)
at pointer_binding.dart:199:80
at Object._checkAndCall (operations.dart:367:37)
at Object.dcall (operations.dart:372:39)
at ret (js_patch.dart:415:11)
Called method:
void connectWithWalletConnect() async {
_walletConnectProvider = WalletConnectProvider.fromRpc(
{56: 'https://bsc-dataseed1.binance.org:443'},
chainId: 56,
network: 'Binance Smart Chain',
bridge: 'https://bridge.walletconnect.org',
);
await _walletConnectProvider.connect();
print('wallet connect ${_walletConnectProvider.walletMeta}');
if (_walletConnectProvider.connected) {
print(_walletConnectProvider.accounts.first);
}
}

Flutter web Http GET throws unwaited function

I'm running an HTTP get using flutter for the web and after connecting it stops running and directs me to the browser_client.dart file highlighting this function
unawaited(xhr.onLoad.first.then((_) {
var body = (xhr.response as ByteBuffer).asUint8List();
completer.complete(StreamedResponse(
ByteStream.fromBytes(body), xhr.status!,
contentLength: body.length,
request: request,
headers: xhr.responseHeaders,
reasonPhrase: xhr.statusText));
}));
then afterward shows this on the debug console
Error: error
at Object.throw_ [as throw] (http://localhost:53840/dart_sdk.js:5061:11)
at searchListing (http://localhost:53840/packages/maimo/app/data/services/api.dart.lib.js:33:19)
at searchListing.next (<anonymous>)
at http://localhost:53840/dart_sdk.js:38640:33
at _RootZone.runUnary (http://localhost:53840/dart_sdk.js:38511:59)
at _FutureListener.thenAwait.handleValue (http://localhost:53840/dart_sdk.js:33713:29)
at handleValueCallback (http://localhost:53840/dart_sdk.js:34265:49)

Error: Unsupported operation: Attempted to change a read-only message (EntityUiPb) in dart by using flutter

I am just making an object of Google protocol buffer which I named OrganisasationUiPb and organisationUipb contain another protocol buffer message EntityUipb
my code
OrganisationUiPb uipb = new OrganisationUiPb();
uipb.dbInfo.id = "add";
uipb.name.canonicalName = "add";
print(uipb);
OrganisationUiPb
message OrganisationUiPb {
EntityUiPb dbInfo = 1;
NameUiPb name = 2;
TimeUiPb time = 3;
string orgCode = 4;
}
EntityUipb
message EntityUiPb {
string id = 1;
int32 version = 2;
StatusEnum lifeTime = 3;
LocaleUiPb locale = 4;
}
when I make an object of OrganisationUipb and start assign values I got this error in cosole
Error: Unsupported operation: Attempted to change a read-only message (EntityUiPb)
at Object.throw_ [as throw] (http://localhost:49885/dart_sdk.js:4463:11)
at Object.defaultFrozenMessageModificationHandler (http://localhost:49885/packages/protobuf/src/protobuf/type_registry.dart.lib.js:5888:15)
at protobuf._FieldSet.new.[_ensureWritable] (http://localhost:49885/packages/protobuf/src/protobuf/type_registry.dart.lib.js:2551:50)
at protobuf._FieldSet.new.[_validateField] (http://localhost:49885/packages/protobuf/src/protobuf/type_registry.dart.lib.js:3007:28)
at protobuf._FieldSet.new.[_$check] (http://localhost:49885/packages/protobuf/src/protobuf/type_registry.dart.lib.js:2800:27)
at protobuf._FieldSet.new.[_$set] (http://localhost:49885/packages/protobuf/src/protobuf/type_registry.dart.lib.js:2783:35)
at entityUiPb$46pb.EntityUiPb.__.$_setString (http://localhost:49885/packages/protobuf/src/protobuf/type_registry.dart.lib.js:3956:36)
at entityUiPb$46pb.EntityUiPb.__.set id [as id] (http://localhost:49885/packages/StudenceWebOrMObileUI/Protobuff/entityUiPb.pb.dart.lib.js:100:12)
at Object.main$ [as main] (http://localhost:49885/packages/StudenceWebOrMObileUI/main.dart.lib.js:491:20)
at main$ (http://localhost:49885/web_entrypoint.dart.lib.js:14:12)
at main$.next (<anonymous>)
at http://localhost:49885/dart_sdk.js:37175:33
at _RootZone.runUnary (http://localhost:49885/dart_sdk.js:37029:58)
at _FutureListener.thenAwait.handleValue (http://localhost:49885/dart_sdk.js:32116:29)
at handleValueCallback (http://localhost:49885/dart_sdk.js:32663:49)
at Function._propagateToListeners (http://localhost:49885/dart_sdk.js:32701:17)
at async._AsyncCallbackEntry.new.callback (http://localhost:49885/dart_sdk.js:32427:27)
at Object._microtaskLoop (http://localhost:49885/dart_sdk.js:37290:13)
at _startMicrotaskLoop (http://localhost:49885/dart_sdk.js:37296:13)
at http://localhost:49885/dart_sdk.js:32918:9
and on UI I got
errors.dart:165 Uncaught (in promise) Error: Unsupported operation: Attempted to change a read-only message (EntityUiPb)
at Object.throw_ [as throw] (errors.dart:214)
at Object.defaultFrozenMessageModificationHandler (field_set.dart:15)
at protobuf._FieldSet.new.[_ensureWritable] (field_set.dart:157)
at protobuf._FieldSet.new.[_validateField] (field_set.dart:794)
at protobuf._FieldSet.new.[_$check] (field_set.dart:512)
at protobuf._FieldSet.new.[_$set] (field_set.dart:493)
at entityUiPb$46pb.EntityUiPb.__.$_setString (generated_message.dart:456)
at entityUiPb$46pb.EntityUiPb.__.set id [as id] (entityUiPb.pb.dart:44)
at Object.main$ [as main] (main.dart:21)
at main$ (web_entrypoint.dart:9)
at main$.next (<anonymous>)
at async_patch.dart:45
at _RootZone.runUnary (zone.dart:1450)
at _FutureListener.thenAwait.handleValue (future_impl.dart:143)
at handleValueCallback (future_impl.dart:696)
at Function._propagateToListeners (future_impl.dart:725)
at async._AsyncCallbackEntry.new.callback (future_impl.dart:393)
at Object._microtaskLoop (schedule_microtask.dart:41)
at _startMicrotaskLoop (schedule_microtask.dart:50)
at async_patch.dart:166
please help me and provide solution of this so I can counter this problem
The reason for this is that the Dart protobuf implementation creates an immutable default value for the child objects of OrganisationUiPb so uipb.dbInfo is read-only from creation.
The workaround is to create the child object first, something like this:
EntityUiPb dbInfoTemp= new EntityUiPb();
dbInfoTemp.id = "add";
OrganisationUiPb uipb = new OrganisationUiPb()..dbInfo = dbInfoTemp;
...
print(uipb);
Mode discussion on the issue here:
https://github.com/dart-lang/protobuf/issues/305

Rx2 java, Consumer interface does not handle error (socket timeout). App crashes

I have the following subscriber for registering an accept from the http service provider, but when the url is malformed, I get an uncatchable exception as shown below, i.e. the try-catch doesn't work. (When the url is valid, no problems).
How do I make this waterproof? I want to receive "onError" but this is not part of the Consumer interface. At the moment, the app crashes on this error event. Perhaps it is better/simpler to use Http directly, instead of RX?
try {
someApi.setStationInfo(stationInfo)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread())
.subscribe(new Consumer<StationInfo>() {
#Override
public void accept(StationInfo abi) throws Exception {
System.out.println("TestAppZappPc received accept from endpoint, data: " + abi);
}
});
} catch (Exception e) {
e.printStackTrace();
}
THE EXCEPTION:
io.reactivex.exceptions.OnErrorNotImplementedException: connect timed out
at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:77)
at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.checkTerminated(ObservableObserveOn.java:276)
at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:172)
at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
at java.net.Socket.connect(Socket.java:586)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:71)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:240)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:160)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at com.jakewharton.retrofit2.adapter.rxjava2.CallObservable.subscribeActual(CallObservable.java:41)
at io.reactivex.Observable.subscribe(Observable.java:10955)
at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
2019-05-14 11:41:44.728 31475-32204/com.hdsl.a.zapp E/AndroidRuntime: at io.reactivex.Observable.subscribe(Observable.java:10955)
at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
... 7 more
There are 2 different ways to handle it.
Use the 2-parameter version of subscribe: subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError). The 2nd Consumer will be called when there's an exception
handle it inline:
someApi.setStationInfo(stationInfo)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread())
.toMaybe()
.onErrorComplete(any -> true)
.subscribe(abi ->
System.out.println("TestAppZappPc received accept from endpoint, data: "
+ abi)
);

Google OAuth2 callback error

Very, very new to user authentication. Looking to allow users to register with Google.
Current status: I'm successfully making it to this step -
(hiding my email(s))
But, when I click an account, I'm getting this error (500) (using longjohn for longer stack traces):
Error
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-google-oauth20/lib/strategy.js:95:21
at passBackControl (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:132:9)
at IncomingMessage.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:157:7)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
---------------------------------------------
at IncomingMessage.Readable.on (_stream_readable.js:689:35)
at ClientRequest.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:156:14)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at HTTPParser.parserOnIncomingClient (_http_client.js:522:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:411:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at TLSSocket.Readable.push (_stream_readable.js:136:10)
at TLSWrap.onread (net.js:560:20)
---------------------------------------------
at exports.OAuth2._executeRequest (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:147:11)
at exports.OAuth2._request (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:120:8)
at exports.OAuth2.get (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:227:8)
at Strategy.userProfile (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-google-oauth20/lib/strategy.js:84:16)
at loadIt (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:345:17)
at Strategy.OAuth2Strategy._loadUserProfile (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:360:25)
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:168:16
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:209:7
at passBackControl (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:134:9)
at IncomingMessage.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:157:7)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
---------------------------------------------
at IncomingMessage.Readable.on (_stream_readable.js:689:35)
at ClientRequest.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:156:14)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at HTTPParser.parserOnIncomingClient (_http_client.js:522:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:411:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at TLSSocket.Readable.push (_stream_readable.js:136:10)
at TLSWrap.onread (net.js:560:20)
---------------------------------------------
at exports.OAuth2._executeRequest (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:147:11)
at exports.OAuth2._request (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:120:8)
at exports.OAuth2.getOAuthAccessToken (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:190:8)
at loaded (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:164:20)
at NullStore.verify (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/state/null.js:9:3)
at Strategy.OAuth2Strategy.authenticate (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:210:26)
at attempt (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport/lib/middleware/authenticate.js:348:16)
at authenticate (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport/lib/middleware/authenticate.js:349:7)
at Layer.handle [as handle_request] (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/layer.js:95:5)
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:335:12)
at next (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:174:3)
at router (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:317:13)
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:335:12)
---------------------------------------------
at handleOperationCallback (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:454:24)
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:490:9
at authenticateStragglers (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:429:16)
at Connection.messageHandler (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:463:5)
at Socket.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:319:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (_stream_readable.js:136:10)
at TCP.onread (net.js:560:20)
My code surrounding this functionality is:
// routes.js
router.get('/auth/google', authController.google);
router.get('/oauth2callback', authController.googleCallback
);
// passport.js
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CONSUMER_KEY,
clientSecret: process.env.GOOGLE_CONSUMER_SECRET,
callbackURL: "http://localhost:21015/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
const user = new User();
user.google.id = profile.id;
user.google.token = accessToken;
user.google.name = profile.displayName;
user.google.email = profile.emails[0].value;
user.save(function(err) {
if (err) throw err;
return done(null, user);
});
}
));
// authController.js
const passport = require('passport');
exports.google = passport.authenticate('google', {
scope: 'https://www.google.com/m8/feeds'
});
exports.googleCallback = passport.authenticate('google', {
failureRedirect: '/login', // if fail, where to go
failureFlash: 'Failed Login!', // if fail, what to flash
successRedirect: '/', // if success, where to go
successFlash: 'You are now logged in!' // if success, what to flash
});
Apparently you can not use an IP address as and end-point, so try to change your callback-url to : http://localhost:21015/oauth2callback
Make sure you have enabled Google+ API in https://console.cloud.google.com.
To use google Auth you have to enable the API in google console. A very common mistake is when you go to Google Developer Console to enable an API for your project, first time for a project it asks you to create Credentials. The problem is after you create credentials the google+ API (or any other APIs) won't be enabled automatically and you should enable it from your project page in google developer console.
STEPS:
Go to Google Console
Select your project from the top nav (if you didn't yet)
Click on Enable APIS and Services
In the search box search for Google Plus
Select the first result , Google+ API
Click Enable
If you don't see the Enable button and see the 'Create Credentials' button,it means you didn't create credentials yet and follow the instructions on the page to create one. Don't forget to enable API after creating credentials.
For more information you can read this instruction from google Enable and disable APIs
Besides what mentioned above, you don't need to use an absolute URL for your callback and simply you can use a relative one like: /auth/google/callback
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CONSUMER_KEY,
clientSecret: process.env.GOOGLE_CONSUMER_SECRET,
callbackURL: "/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
const user = new User();
user.google.id = profile.id;
user.google.token = accessToken;
user.google.name = profile.displayName;
user.google.email = profile.emails[0].value;
user.save(function(err) {
if (err) throw err;
return done(null, user);
});
}
));