Store access_token in the AsyncStorage - ruby-on-rails

After user enters ID and password, I am passing access_token from Rails.
I am using
itzikbenh/Rails-React-Auth and
itzikbenh/React-Native-on-Rails as reference.
But I am unable to save the access_token. Here is the code:
let res = await response.text();
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
console.log(accessToken);
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
//this.redirect('home');
alert(ACCESS_TOKEN )
} else {
//Handle error
let error = res;
throw error;
}

You can use AsyncStorage.setItem to store single items:
import { ... AsyncStorage } from 'react-native'
try {
await AsyncStorage.setItem('access_token', access_token);
} catch (error) { // Error saving data }
Then to retrieve it use AsyncStorage.getItem:
try {
const value = await AsyncStorage.getItem('access_token');
if (value !== null) console.log(value)
} catch (error) { // Error retrieving data }
For storing and retrieving multiple items you can see AsyncStorage.multiSet and AsyncStorage.multiGet.

Related

Data sharing between Safari and standalone iPhone 12 iOS 14.3

I tried to share data between Safari browser and standalone PWA on iPhone12 with iOS 14.3.
The information, that this should work are here: https://firt.dev/ios-14/
I#ve tried this: https://www.netguru.com/codestories/how-to-share-session-cookie-or-state-between-pwa-in-standalone-mode-and-safari-on-ios
Without success.
Are there any suggestions to running this? Or is it not possible ...
This is the code
const CACHE_NAME = "auth";
const TOKEN_KEY = "token";
const FAKE_TOKEN = "sRKWQu6hCJgR25lslcf5s12FFVau0ugi";
// Cache Storage was designed for caching
// network requests with service workers,
// mainly to make PWAs work offline.
// You can give it any value you want in this case.
const FAKE_ENDPOINT = "/fake-endpoint";
const saveToken = async (token: string) => {
try {
const cache = await caches.open(CACHE_NAME);
const responseBody = JSON.stringify({
[TOKEN_KEY]: token
});
const response = new Response(responseBody);
await cache.put(FAKE_ENDPOINT, response);
console.log("Token saved! 🎉");
} catch (error) {
// It's up to you how you resolve the error
console.log("saveToken error:", { error });
}
};
const getToken = async () => {
try {
const cache = await caches.open(CACHE_NAME);
const response = await cache.match(FAKE_ENDPOINT);
if (!response) {
return null;
}
const responseBody = await response.json();
return responseBody[TOKEN_KEY];
} catch (error) {
// Gotta catch 'em all
console.log("getToken error:", { error });
}
};
const displayCachedToken = async () => {
const cachedToken = await getToken();
console.log({ cachedToken });
};
// Uncomment the line below to save the fake token
// saveToken(FAKE_TOKEN);
displayCachedToken();
Without success means no result, i've tried to set data in safari and get them in standalone pwa

React native Apple login stuck in enter password screen in IOS?

In IOS after entering the password it shows loading and nothing happens after that.There are no console logs?It's working fine in android.
I have implemented V2 of react native apple authentication
https://github.com/invertase/react-native-apple-authentication
Tried 2 codes below same issue.
Code 1
const IOSAppleLogin = async () => {
try {
// performs login request
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME]
});
const credentialState = await appleAuth.getCredentialStateForUser(
appleAuthRequestResponse.user
);
if (credentialState === appleAuth.State.AUTHORIZED) {
console.log('appleAuthRequestResponse', appleAuthRequestResponse);
const response = appleAuthRequestResponse;
console.log('apple-response', response);
// you may also want to send the device's ID to your server to link a device with the account
// identityToken generated
if (response) {
if (response.identityToken) {
let device_identifier = DeviceInfo.getUniqueId();
let details = {
'identity_token': response.identityToken,
'first_name': response.fullName ? response.fullName.givenName : '-',
'last_name': response.fullName ? response.fullName.familyName : '-',
'device_identifier': device_identifier,
device: Platform.OS
};
props.appleLogin({ values: details });
}
}
// user is authenticated
}
} catch (error) {
if (appleAuth.Error.CANCELED === error.code) {
console.log('apple-error-CANCELED', JSON.stringify(error));
} else if (appleAuth.Error.FAILED === error.code) {
console.log('apple-error-FAILED', error);
} else if (appleAuth.Error.NOT_HANDLED === error.code) {
console.log('apple-error-NOT_HANDLED', error);
} else {
console.log('apple-error', error);
}
}
}
Code 2
const IOSAppleLogin = async () => {
try {
// performs login request
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME]
});
console.log('appleAuthRequestResponse', appleAuthRequestResponse);
const response = appleAuthRequestResponse;
console.log('apple-response', response);
// you may also want to send the device's ID to your server to link a device with the account
// identityToken generated
if (response) {
if (response.identityToken) {
let device_identifier = DeviceInfo.getUniqueId();
let details = {
'identity_token': response.identityToken,
'first_name': response.fullName ? response.fullName.givenName : '-',
'last_name': response.fullName ? response.fullName.familyName : '-',
'device_identifier': device_identifier,
device: Platform.OS
};
props.appleLogin({ values: details });
}
}
// user is authenticated
} catch (error) {
if (appleAuth.Error.CANCELED === error.code) {
console.log('apple-error-CANCELED', JSON.stringify(error));
} else if (appleAuth.Error.FAILED === error.code) {
console.log('apple-error-FAILED', error);
} else if (appleAuth.Error.NOT_HANDLED === error.code) {
console.log('apple-error-NOT_HANDLED', error);
} else {
console.log('apple-error', error);
}
}
}
Had this happen to me as well. Found the solution here https://github.com/invertase/react-native-apple-authentication/issues/162#issuecomment-723502035.
Basically, just use iOS 13 if you are on an emulator or iOS 14 on a real device.
This also happened with me when I am trying to run the code on simulator, Try this on real device it will work.
Don't forgot to add Sign In with Apple for both release and debug App in Signing & Capabilities .For this you should have an ADP Account.
Thank you.

Can't get a Lambda function to send back information

I just got my first Lambda function written, but it does not work at this point.
I tried a number of variations in the code; partly following what I could think of and partly following what I could come across on the net; but all failed.
I want the Lambda function to listUsers in a UserPool and get an email for a given sub passed as parameter.
Here is the Swift function making the call to the Lambda function:
func getLambdaInfo() {
let lambdaInvoker = AWSLambdaInvoker.default(),
jsonObject:[String: Any] = ["sub" : "MY-USER-SUB"]
lambdaInvoker.invokeFunction("myLambdaFunc", jsonObject: jsonObject)
.continueWith(block: {
(task:AWSTask<AnyObject>) -> Any? in
if( task.error != nil) {
print("Error: \(task.error!)")
return nil
}
print("\(#function) ---- WE ARE HERE!!!!")
// Handle response in task.result:
if let JSONDictionary = task.result as? NSDictionary {
print("Result: \(JSONDictionary)")
}
return nil
})
}
Here is the Lambda function:
var AWS = require('aws-sdk/dist/aws-sdk-react-native');
exports.handler = async (event,context) => {
var params = {
UserPoolId: 'MY-POOL-ID',
AttributesToGet: ['email'],
Limit: '2'
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.listUsers(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
// How can I get this data sent in the response is probably the issue ??
});
const response = {
inBound: event.sub,
statusCode: 200,
body: JSON.stringify('Hello from Lambda!')
};
return response;
}
Here is what can be seen in the Xcode debugging console:
getLambdaInfo() ---- WE ARE HERE!!!!
Result: {
body = "\"Hello from Lambda!\"";
inBound = "MY-USER-SUB";
statusCode = 200;
}
I hope someone with more AWSLambda than me will be able to give me some hints concerning the changes I need to make in my code to get the result (email address) I want (into my Swift getLambdaInfo()).
You need to move your return statement in the callback of listUsers:
cognitoidentityserviceprovider.listUsers(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
// return a 500 error ?
}
else {
console.log(data);
const response = {
inBound: event.sub,
statusCode: 200,
body: JSON.stringify(data)
}
return response;
}
});
Since you're using the async pattern you can also do:
try {
const data = await cognitoidentityserviceprovider.listUsers(params).promise() // note the await and .promise() here
const response = {
inBound: event.sub,
statusCode: 200,
body: JSON.stringify(data)
}
return response;
} catch (err) {
// do something with err
}
Otherwise your Lambda function returns before your callback gets executed (async nature of JavaScript).

How to "await" non-future variable?

I have DocumentReference locationDocumentRef; in my state.
I'm changing locationDocumentRef based on the references, whether I gather by querying or by adding new document.
So I have this function to check the documents, if there is one set its reference to the locationDocumentRef, or add a new one and set its ref to the locationDocumentRef. I'm resetting its value everytime by setting it to null, since I didn't want to get previous result. But it prints null.
So my question is, how can I resolve them and get the value? I think I'm resolving too early in my code, so I can't await a non-future value. How can I fix it?
void firestoreCheckAndPush() async {
setState(() {
locationDocumentRef = null;
});
bool nameExists = await doesNameAlreadyExist(placeDetail.name);
if (nameExists) {
print('name exist');
} else {
print('name will be pushed on firestore');
pushNameToFirestore(placeDetail);
}
var resolvedRef = await locationDocumentRef;
print(resolvedRef.documentID); // I get null here
}
These are the functions that I have used
Future<bool> doesNameAlreadyExist(String name) async {
QuerySnapshot queryDb = await Firestore.instance
.collection('locations')
.where("city", isEqualTo: '${name}')
.limit(1)
.getDocuments();
if (queryDb.documents.length == 1) {
setState(() {
locationDocumentRef = queryDb.documents[0].reference;
});
return true;
} else {
return false;
}
}
And the other
void pushNameToFirestore(PlaceDetails pd) async {
DocumentReference justAddedRef =
await Firestore.instance.collection('locations').add(<String, String>{
'city': '${pd.name}',
'image': '${buildPhotoURL(pd.photos[0].photoReference)}',
});
setState(() {
locationDocumentRef = justAddedRef;
});
}
there is two mistakes i saw first here
var resolvedRef = await locationDocumentRef;
why you await for locationDocumentRef,
second you dont wait for pushNameToFirestore(PlaceDetails pd) firestoreCheckAndPush() function which is weird since pushNameToFirestore(String) is sync and this means you wouldnt wait for it to finish so if you are adding a new name it would print null.
correct me if i am wrong.
you can find more about sync and future here https://www.dartlang.org/tutorials/language/futures
look at the graph at the middle of the page
Try this
Future<List<DocumentSnapshot>> doesNameAlreadyExist(String name) async {
QuerySnapshot data = await Firestore.instance
.collection('locations')
.where("city", isEqualTo: name)
.limit(1)
.getDocuments();
return data.documents;
}
void firestoreCheckAndPush() async {
var data = await doesNameAlreadyExist('yourname');
if (data.length > 0) {
print('name exist');;
print('Document id '+ data[0].documentID);
} else {
print('name will be pushed on firestore');
}
}
Take a look into following code.
void firestoreCheckAndPush() async {
DocumentReference documentReference;
var data = await doesNameAlreadyExist('yourname');
var dataRef = await doesNameAlreadyExist('yourname');
if (data.length > 0) {
print('name exist');
documentReference = dataRef[0].reference;
print('Document id ' + data[0].documentID);
documentReference = dataRef[0].reference;
print('Document reference ');
print(documentReference);
} else {
print('name will be pushed on firestore');
}
}

How to know the chain in the fabcar example?

For example, I have a car1 that was first owner by the manufacturer and then it was transferred over to the retailer and then to the user
In the fabcar example, I can know who is its current owner by i don't know who is the previous owner.
Is there a way to do it?
Here is the http://hyperledger-fabric.readthedocs.io/en/latest/write_first_app.html example I was following
Is not implemented in the chaincode. To do this you could implement a new method which returns the history of the asset.
Here the link to the official documentation for nodeJS (you can find it also for GoLang):
https://fabric-shim.github.io/ChaincodeStub.html#getHistoryForKey__anchor
Here an example:
async queryValueHistory(stub,args){
if (args.length != 1) {
throw new Error('Incorrect number of arguments. Expecting identifier ex: CAR01');
}
let carId = args[0];
let iterator = await stub.getHistoryForKey(carId);
let allResults = [];
while (true) {
let res = await iterator.next();
if (res.value && res.value.value.toString()) {
let jsonRes = {};
console.log(res.value.value.toString('utf8'));
jsonRes.TxId = res.value.tx_id;
jsonRes.Timestamp = res.value.timestamp;
jsonRes.IsDelete = res.value.is_delete.toString();
try {
jsonRes.Value = JSON.parse(res.value.value.toString('utf8'));
} catch (err) {
console.log(err);
jsonRes.Value = res.value.value.toString('utf8');
}
console.info(jsonRes);
allResults.push(jsonRes);
}
if (res.done) {
console.log('end of data');
try{
await iterator.close();
}catch(err){
console.log(err);
}
console.info(allResults);
return Buffer.from(JSON.stringify(allResults));
}
}
}

Resources