I am trying to change the useridentity with different credentials. It gets successful login with realm but the new Userid is not getting updated in Mobilefirst console. Console still shows the old userID.
I am using the following code.
function submitAuthentication(username, password){
userIdentity = {
userId: username,
displayName: "sample",
attributes: {
foo: "bar"
}
};
WL.Server.setActiveUser("AuthRealm", null);
WL.Server.setActiveUser("AuthRealm", userIdentity);
return {
authStatus: "complete" ,
result: "Success"
};
// }
}
I just saw below error at android client side, challengehandler class/handleChallenge method
07-12 07:14:34.265 13001-13078/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.worklight.wlclient.WLRequest.shouldFailOnChallengeCancel()' on a null object reference
07-12 07:14:34.266 13001-13078/com.mfp W/System.err: at com.worklight.wlclient.api.WLClient$InvokeProcedureRequestListener.onFailure(WLClient.java:1376)
07-12 07:14:34.266 13001-13078/com.mfp W/System.err: at com.worklight.wlclient.WLRequest.triggerUnexpectedOnFailure(WLRequest.java:337)
07-12 07:14:34.266 13001-13078/com.mfp W/System.err: at com.worklight.wlclient.WLRequest.requestFinished(WLRequest.java:295)
07-12 07:14:34.266 13001-13078/com.mfp W/System.err: at com.worklight.wlclient.WLRequestSender.run(WLRequestSender.java:52)
07-12 07:14:34.266 13001-13078/com.mfp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
07-12 07:14:34.266 13001-13078/com.mfp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
07-12 07:14:34.266 13001-13078/com.mfp W/System.err: at java.lang.Thread.run(Thread.java:818)
07-12 07:14:34.333 13001-13007/com.mfp W/art: Suspending all threads took: 66.075ms
The below was the issue
activeRequest(WLRequest object) in BaseChallengeHandler was null while calling submitSuccess(); in ChallengeHandler
That was the reason I was getting above error . I was not able to resolve the main issue but I was able to get ride of above mentioned error.
The below place was the place where activeRequest was not given right value.
As request.getOptions().isFromChallenge() is always true so the value of activeRequest was not set to right value.Its null after this.
So I made fromChallenge as false.
public void startHandleChallenge(WLRequest request, T challenge) {
synchronized(this) {
if(!request.getOptions().isFromChallenge()) {
if(this.activeRequest != null) {
this.requestWaitingList.add(request);
return;
}
this.activeRequest = request;
}
}
this.handleChallenge(challenge);
}
Related
Here is my thought, I want to present the data when the user searching via $artistName then combine framework could help me to request the data from the server.
I don't know which step I'm wrong. When I try to fetch the data via the simulator. It will show the unknown error and the rest of these.
2020-10-23 03:56:38.220523+0800 PodcastSearchV2[42967:667554] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
Fetch failed: Unknown error
2020-10-23 03:56:40.114906+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.115071+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.115255+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.115360+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.115516+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_connected_local_endpoint [C2] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection
2020-10-23 03:56:40.115613+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_connected_remote_endpoint [C2] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection
2020-10-23 03:56:40.115723+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_connected_path [C2] Client called nw_connection_copy_connected_path on unconnected nw_connection
2020-10-23 03:56:40.115924+0800 PodcastSearchV2[42967:667546] Connection 2: unable to determine interface type without an established connection
2020-10-23 03:56:40.116069+0800 PodcastSearchV2[42967:667546] Connection 2: unable to determine interface classification without an established connection
2020-10-23 03:56:40.116381+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.120441+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_metadata [C2] Client called nw_connection_copy_metadata on unconnected nw_connection
2020-10-23 03:56:40.120579+0800 PodcastSearchV2[42967:667546] Connection 2: unable to determine interface type without an established connection
2020-10-23 03:56:40.121823+0800 PodcastSearchV2[42967:667546] Connection 2: unable to determine interface type without an established connection
This is my response.
struct DataResponseSpotify: Codable {
var episodes: PodcastItemSpotify
}
struct PodcastItemSpotify: Codable {
var items: [PodcastItemsDetailsSpotify]
}
struct PodcastItemsDetailsSpotify: Codable, Identifiable {
let id: String
let description: String
let images: [Images]
let name: String
let external: String
var externalURL: URL? {
return URL(string: external)
}
enum CodingKeys: String, CodingKey {
case id
case description
case images
case name
case external = "external_urls"
}
}
struct Images: Codable {
let url: String
var imageURL: URL? {
return URL(string: url)
}
enum CodingKeys: String, CodingKey {
case url
}
}
struct Token: Codable {
let accessToken: String
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
}
}
This is how I write in the model.
class DataObserverSpotify: ObservableObject {
#Published var artistName = ""
#Published var token = ""
#Published var fetchResult = [PodcastItemsDetailsSpotify]()
var subscriptions: Set<AnyCancellable> = []
let podsURLComponents = PodsFetcher()
init() {
getToken()
$artistName
.debounce(for: .seconds(2), scheduler: RunLoop.main)
.removeDuplicates()
.compactMap { query in
let url = self.podsURLComponents.makeURLComponentsForSpotify(withName: query, tokenAccess: self.token)
return URL(string: url.string ?? "")
}
.flatMap(fetchDatatesting)
.receive(on: DispatchQueue.main)
.assign(to: \.fetchResult, on: self)
.store(in: &subscriptions)
}
func fetchDatatesting(url: URL) -> AnyPublisher<[PodcastItemsDetailsSpotify], Never> {
URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: DataResponseSpotify.self, decoder: JSONDecoder())
.map(\.episodes.items)
.replaceError(with: [])
.eraseToAnyPublisher()
}
func getToken() {
let parameters = "grant_type=refresh_token&refresh_token=[example-refresh-token]"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://accounts.spotify.com/api/token")!,timeoutInterval: Double.infinity)
request.addValue("Basic exampleBasicAuth=", forHTTPHeaderField: "Authorization")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("inapptestgroup=; __Host-device_id=example_id; __Secure-example=; csrf_token=example", forHTTPHeaderField: "Cookie")
request.httpMethod = "POST"
request.httpBody = postData
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
if let token = try? decoder.decode(Token.self, from: data) {
DispatchQueue.main.async {
self.token = token.accessToken
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
You call getToken that sets the token asynchronously, yet without waiting you immediately attempt to create a URL assuming that the token is available inside .compactMap - and it's not yet available by that time.
So, you have to "wait" for it, which, with Combine, you could do in multiple ways.
The simplest (cheapest) change with what you currently have is to combine the $token with the $artistName publishers:
$artistName
.debounce(for: .seconds(2), scheduler: RunLoop.main)
.removeDuplicates()
.combineLatest($token.filter { !$0.isEmpty }) // waits for a non-empty token
.compactMap { (query, token) in
var url = ... // construct URL from query and token
return url
}
.flatMap(fetchDatatesting)
.receive(on: DispatchQueue.main)
// I used sink, since assign causes a self retain cycle
.sink { [weak self] result in self?.fetchResult = result }
.store(in: &subscriptions)
But you really should redesign your getToken method - it's not written well because it's an async function, yet it doesn't have a completion handler.
For example, like this:
func getToken(_ completion: #escaping (Token) -> Void) {
// set-up, etc..
URLSession.shared.dataTask(with: request) { data, response, error in
// error handling, etc...
if let token = try? decoder.decode(Token.self, from: data) {
completion(token)
}
}.resume()
}
// usage
getToken {
self.token = $0
}
Or, since you're using Combine, you can re-write it to return a publisher (I'm ignoring errors here to keep it concise):
func getToken() -> AnyPublisher<Token?, Never> {
// ...
}
When wrong user login ios app is crashing and no log displayed. But in Android is working with out crash. Why?
Thread 26: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/user/FlutterHome/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_aws_amplify_cognito-1.0.0+7/ios/Classes/SwiftFlutterAwsAmplifyCognito.swift, line 275
Future<dynamic> login(
{String username,
String password,
GlobalKey<ScaffoldState> globalKey}) async {
return FlutterAwsAmplifyCognito.signIn(username, password)
.then((SignInResult result) {
debugPrint('------------------------${result}');
switch (result.signInState) {
case SignInState.SMS_MFA:
// TODO: Handle this case.
break;
case SignInState.PASSWORD_VERIFIER:
// TODO: Handle this case.
break;
case SignInState.CUSTOM_CHALLENGE:
// TODO: Handle this case.
break;
case SignInState.DEVICE_SRP_AUTH:
// TODO: Handle this case.
break;
case SignInState.DEVICE_PASSWORD_VERIFIER:
// TODO: Handle this case.
break;
case SignInState.ADMIN_NO_SRP_AUTH:
// TODO: Handle this case.
break;
case SignInState.NEW_PASSWORD_REQUIRED:
// TODO: Handle this case.
break;
case SignInState.DONE:
break;
case SignInState.UNKNOWN:
// TODO: Handle this case.
break;
case SignInState.ERROR:
// TODO: Handle this case.
break;
}
return result.codeDetails;
}).catchError((error) {
if (error.code == 'Error') {
globalKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text(LocalizationsUtils(
Locale.fromSubtags(languageCode: AppPreferences().language))
.errorIncorrectEmailPassword),
));
}
});
}
github link
https://github.com/jonsaw/amazon-cognito-identity-dart
Had the same problem. There is just a missing return in code.
static func signIn(result: #escaping FlutterResult, username: String, password: String) {
AWSMobileClient.default().signIn(username: username, password: password){(signinResult, error) in
if (error != nil) {
DispatchQueue.main.async {
result(FlutterError(code: "Error", message: "Error signing in", details: error?.localizedDescription))
}
return // this return was missing!!!
}
FYI: If you run the Application with Xcode, the debugger will point you to the bug.
PS: the return is missing in every error, so the app might crash on other functionCalls too, for example if you try to get Tokens without being loggedIn.
I keep getting this error in the Android version of my React Native app. The iOS version of the app has zero problems with the React Native switch that I've used. This app is currently running on RN 0.54
Just in case, here's the code that uses the switch:
<View style={styles.feedbackSwitchWrapper}>
<Switch
value={this.props.feedbackCancellation}
onValueChange={() => {
this.feedbackCancellationToggle()
}}
onTintColor="#xxxx"
/>
</View>
And here is the error I get when I hit the switch.
Here's the updated code that ended up fixing the issue:
this.feedbackCancellation = SomeBluetoothEventEmitter.addListener('feedbackMode', event => {
// console.log('show me feedback mode object: ', event);
if (!event) {
return;
}
let feedbackCancellation = event.feedbackMode;
if (this.cancellationFeedbackDeferred) {
this.cancellationFeedbackDeferred.resolve(event.feedbackMode);
let trueOrFalseValue = this.convertIntToBool(feedbackCancellation);
/*
NOTE: for both feedbackCancellation and noiseReduction, we are getting the value
of each FROM THE DEVICE. We will use setFeedbackCancellationFunc to set the value in PROPS,
then we will use toggleFeedbackCancellationFunc to TOGGLE the values during
normal use.
*/
this.props.setFeedbackCancellationFunc(trueOrFalseValue);
} else {
if (this.mounted === true) { this.setState({ feedbackCancellation }) }
}
})
I'm having some issues with JSONStore on Android. It works fine using mfpdev app preview.
Intialization code (runs successfully):
let collections = {
workorders: {
searchFields: {id: 'integer'}
}
}
WL.JSONStore.init(collections).then((success) => {
console.log("Jsonstore init success");
},
(failure) => {
console.log("Jsonstore init failed", failure);
});
Put code (doesn' work, see error logs below):
put(data) : void {
console.log("JSONStore put function called: " + JSON.stringify(data));
if (!Array.isArray(data))
{
console.log("data is not array");
data = this.json2array(data);
}
if (Array.isArray(data)){
console.log("data is array");
}
let collectionName = "workorders";
let options = {
replaceCriteria: ['id'],
addNew: true,
markDirty: false
};
WL.JSONStore.get(collectionName).change(data, options).then((success)=> {
console.log("JSONStore put success");
},
(failure) => {
console.log("JSONstore put failed: " + JSON.stringify(failure), failure);
});
}
Errors from android logcat:
03-24 15:29:36.656 8362 8362 I chromium: [INFO:CONSOLE(40796)] "JSONStore put function called: {"enddate":"2017-03-03","description":"Test work order 0","id":1,"ts":"Ban","status":"In progress"}", source: file:///android_asset/www/build/main.js (40796)
03-24 15:29:36.656 8362 8362 D SystemWebChromeClient: file:///android_asset/www/build/main.js: Line 40798 : data is not array
03-24 15:29:36.656 8362 8362 I chromium: [INFO:CONSOLE(40798)] "data is not array", source: file:///android_asset/www/build/main.js (40798)
03-24 15:29:36.657 8362 8362 D SystemWebChromeClient: file:///android_asset/www/build/main.js: Line 40802 : data is array
03-24 15:29:36.657 8362 8362 I chromium: [INFO:CONSOLE(40802)] "data is array", source: file:///android_asset/www/build/main.js (40802)
03-24 15:29:36.662 8362 8362 D SystemWebChromeClient: file:///android_asset/www/build/main.js: Line 40813 : JSONstore put failed: {"src":"store","err":10,"msg":"BAD_PARAMETER_EXPECTED_DOCUMENT_OR_ARRAY_OF_DOCUMENTS","col":"workorders","usr":"jsonstore","doc":{},"res":{}}
03-24 15:29:36.662 8362 8362 I chromium: [INFO:CONSOLE(40813)] "JSONstore put failed: {"src":"store","err":10,"msg":"BAD_PARAMETER_EXPECTED_DOCUMENT_OR_ARRAY_OF_DOCUMENTS","col":"workorders","usr":"jsonstore","doc":{},"res":{}}", source: file:///android_asset/www/build/main.js (40813)
The error is BAD_PARAMETER_EXPECTED_DOCUMENT_OR_ARRAY_OF_DOCUMENTS, however I have in my code to make it an array if its not already an array.
Also, I can't find any documentation on the change() method on a JSONStore collection, but I found it is used in this example: https://mobilefirstplatform.ibmcloud.com/labs/developers/8.0/advancedmessenger/
Can anyone spot what the problem might be?
I finally found out what the issue was.
The error BAD_PARAMETER_EXPECTED_DOCUMENT_OR_ARRAY_OF_DOCUMENTS seems to be somewhat misleading. It always failed if I sent a single JSONObject. After I converted it to a JSONArray using the below code, it worked:
if (!Array.isArray(data))
{
console.log("data is not array");
data = JSON.parse('[' + JSON.stringify(data) + ']');
console.log("data is now an array: " + JSON.stringify(data));
}
Ref: https://github.com/balderdashy/skipper/issues/49
Adapter: skipper-gridfs
Basic controller code:
req.file('fileTest')
.upload({
// You can apply a file upload limit (in bytes)
maxBytes: maxUpload,
adapter: require('skipper-gridfs'),
uri: bucketConnect,
saveAs : function (__newFileStream,cb) {
cb(null, __newFileStream.filename);
}
}, function whenDone(err, uploadedFiles) {
if (err) {
var error = { "status": 500, "error" : err };
return res.serverError(error);
}else {
I have a jQuery-File-Upload client ( https://blueimp.github.io/jQuery-File-Upload/ ) impementing the "cancel" procedure by using jqXHR abort described here (https://github.com/blueimp/jQuery-File-Upload/wiki/API ):
$('button.cancel').click(function (e) {
jqXHR.abort();
});
After the client aborts, the server crashes with the following message:
events.js:72
throw er; // Unhandled 'error' event
^
Error: Request aborted
at IncomingMessage.onReqAborted (.../node_modules/sails/node_modules/skipper/node_modules/multiparty/index.js:175:17)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at abortIncoming (http.js:1911:11)
at Socket.serverSocketCloseListener (http.js:1923:5)
at Socket.EventEmitter.emit (events.js:117:20)
at TCP.close (net.js:466:12)
I've used try/catch but it didn't work, the server crashes anyway.
I am not sure if this is a Skipper issue or a Multiparty issue -- my knowledge stops here ( https://github.com/andrewrk/node-multiparty/blob/master/index.js ):
function onReqAborted() {
waitend = false;
self.emit('aborted');
handleError(new Error("Request aborted"));
}
function onReqEnd() {
waitend = false;
}
function handleError(err) {
var first = !self.error;
if (first) {
self.error = err;
req.removeListener('aborted', onReqAborted);
req.removeListener('end', onReqEnd);
if (self.destStream) {
self.destStream.emit('error', err);
}
}
cleanupOpenFiles(self);
if (first) {
self.emit('error', err);
}
}
At first I thought this was the way the jqXHR request was aborted, but it seems to be a generic Skipper issue on aborted uploads, since the simple act of closing the tab during an upload will crash the server (different message):
_stream_writable.js:233
cb(er);
^
TypeError: object is not a function
at onwriteError (_stream_writable.js:233:5)
at onwrite (_stream_writable.js:253:5)
at WritableState.onwrite (_stream_writable.js:97:5)
at Writable.<anonymous> (.../node_modules/skipper-gridfs/index.js:179:25)
at Writable.g (events.js:180:16)
at Writable.EventEmitter.emit (events.js:117:20)
at PassThrough.<anonymous> (.../node_modules/skipper-gridfs/index.js:194:36)
at PassThrough.g (events.js:180:16)
at PassThrough.EventEmitter.emit (events.js:117:20)
at .../node_modules/sails/node_modules/skipper/standalone/Upstream/prototype.fatalIncomingError.js:55:17
I have tried aborting the upload by closing the tab while using a simple upload controller (not Skipper) and there is no crash:
var uploadFile = req.file('fileTest');
console.log(uploadFile);
uploadFile.upload(function onUploadComplete (err, files) { // Files will be uploaded to .tmp/uploads
if (err) return res.serverError(err); // IF ERROR Return and send 500 error with error
console.log(files);
res.json({status:200,file:files});
});
So, did anybody see this happening and is there any workaround?
This issue has been solved in skipper#0.5.4 and skipper-disk#0.5.4
Ref.: https://github.com/balderdashy/skipper/issues/49
Also there is an Issue in skipper-gridfs#0.5.3
Link: https://github.com/willhuang85/skipper-gridfs/issues/20