How to search users in Cognito userpool in React Native app - react-native

I'm building an app using React Native and Amplify (including authentication) and need to let users search for and follow other users also using the app.
The authentication flow is working fine, but I'm not able to search the cognito userpool for the list of users.
According to amplify-js/packages/amazon-cognito-identity-js/, one of the v1.0 functionality enabled "Search users in your pool using user attributes.", but so far I'm unable to find any additional documentation or examples.
I've tried using the Auth object from the aws-amplify module and the CognitoUserPool object from the amazon-cognito-identity-js module, and neither seems to offer the search functionality.
How should I be going about this?

Ended up with this:
AWS.config.update({
accessKeyId: "YOUR_ACCESS_KEY",
secretAccessKey: "YOUR_SECRET_ACCESS_KEY,
region: "YOUR_REGION"
});
const params = {
UserPoolId: 'THE_USER_POOL_ID',
AttributesToGet: [
'email',
],
};
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.listUsers(params, (err, data) => {
if (err) {
console.log(err);
}
else {
console.log("data", data);
}
})
The problem now becomes having to store the access keys on-device, which I can't do. Will likely create another table in Datastore to store user info for querying.

Related

Is the function "signInWithPopup" from firebase supported on Expo?

I am trying to implement an authentication login method through Azure AD with Firebase on my Expo app.
Here is an extraction of my code, which looks exactly like the Firebase documentation:
const signInWithMicrosoft = () => {
const auth = initializeAuth(firebaseApp);
signInWithPopup(auth, provider)
.then((result) => {
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
const idToken = credential.idToken;
navigation.navigate("Home")
})
.catch((error) => {
// Handle error.
});
}
When pressing the button to activate the function, the following error message shows up:
TypeError: (0, _auth.signInWithPopup) is not a function. (In '(0, _auth.signInWithPopup)(auth, provider)', '(0, _auth.signInWithPopup)' is undefined)
I tried importing the functions as:
import { signInWithPopup } from "firebase/auth"
and
import { signInWithPopup } from "firebase/compat/auth"
And neither of them seem to work.
Is there any way I can get this function to work, or the solution would be going another way around? I don't know if functions such as SignInWithPopup and SignInWithRedirect are supported in Expo, since it is a Mobile application.
If you have any tip, clue or information on using firebase auth methods in a Expo app, please share below and I will be very happy to read it and comment on.

Firebase Google Sign In not working in React Native

import firebase from 'firebase';
import React from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';
import App from './testlogin';
import { View, Text, Button } from 'react-native';
import { firebaseConfig } from './firebaseConfig';
const app = firebase.initializeApp(firebaseConfig);
const auth = app.auth();
const db = app.firestore();
const googleProvider = new firebase.auth.GoogleAuthProvider()
export const signInWithGoogle = async () => {
try {
const res = await auth.signInWithPopup(googleProvider);
const user = res.user;
const query = await db
.collection("users")
.where("uid", "==", user.uid)
.get();
if (query.docs.length === 0) {
await db.collection("users").add({
uid: user.uid,
name: user.displayName,
authProvider: "google",
email: user.email,
});
}
} catch (err) {
console.error(err);
alert(err.message);
}
};
This code accesses the google sign in method and should pop up a window, but I don't get anything when I click the button. I have been having difficulty with implementing Firebase in React Native and this is one of the examples. I need an example of easy Google sign in button in React Native.
I recommend you to use https://rnfirebase.io/ library (their docs are quite helpful).
Here are their instructions for Google Sign-in: https://rnfirebase.io/auth/social-auth#google.
According to them, you need to
ensure the "Google" sign-in provider is enabled on the Firebase Console.
also install #react-native-google-signin/google-signin',
then "Before triggering a sign-in request, you must initialize the Google SDK using your any required scopes and the webClientId, which can be found in the android/app/google-services.json"
Finally, as because following:
Starting April 2020, all existing applications using external 3rd party login services (such as Facebook, Twitter, Google etc) must ensure that Apple Sign-In is also provided. - You would also need to support iOS / and Apple Sign-in too. (if are building app also for iOS).
NOTE: I also remember that I had to put both, SHA1 and SHA256 hashes in the Firebase Console as some Firebase services were not working without it.
How to find SHA hashes in Android for Firebase (signing with Keystore that will be used in production should be already configured):
The debug signing certificate is optional to use Firebase with your app, but is required for Dynamic Links, Invites and Phone Authentication. To generate a certificate run
cd android && ./gradlew signingReport
and copy the SHA1 and SHA256 from the debug key. This generates two variant keys. You can copy the 'SHA1' that belongs to the debugAndroidTest variant key option.
Again, I recommend you to put both SHA hashes in Firebase Console.

React native with mongodb realm. Attempting google signin results in error code 10

Below code is provided at realm docs.
GoogleSignin.configure({
webClientId: clientId,
offlineAccess: true,
});
async function getGoogleAuthCode() {
try {
await GoogleSignin.hasPlayServices();
const {serverAuthCode} = await GoogleSignin.signIn();
return serverAuthCode;
}
catch (error) {}
Above code always returns 10 - DEVELOPER_ERROR,
Cross checked the client id. Since mongodb realm suggests to use web application type google oAuth. App's SHA is not registered at google end.
Google sign in is broken in the current beta.
References:
Open GitHub Issue involving 3 different Realm SDKs
MongoDB Developer Forum post confirming this is a problem on their side.

react-native-geocoding shows error not getting coordinates

I am using https://github.com/marlove/react-native-geocoding to get coordinates in react-native.
Sample code
`Geocoder.from("visakhapatnam,andhra pradesh,india")
.then(json => {
var location = json.results[0].geometry.location;
console.log("location",location)
})
.catch(error => console.warn("routeMap Err",error));`
I am getting error
{"code": 4, "message": "Error from the server while geocoding. The received datas are in the error's 'origin' field. Check it for more informations.", "origin": {"error_message": "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started", "results": [], "status": "REQUEST_DENIED"}}
To use the Geocoding API you must have an API key. The API key is a unique identifier that is used to authenticate requests associated with your project for usage and billing purposes.
To get an API key:
Visit the Google Cloud Platform Console.
Click the project drop-down and select or create the project for
which you want to add an API key.
Click the menu button and select APIs & Services > Credentials.
On the Credentials page, click Create credentials > API key. The API
key created dialog displays your newly created API key.
Click Close. The new API key is listed on the Credentials page under
API keys.
(Remember to restrict the API key before using it in production.)
OR You need try enable billing like an error message.
Go to the Payment Account Management page in the Google Cloud
Platform Console and log in.
Select the My Projects tab to display the list of projects and the
payment accounts associated with each project.
In the list of projects, locate the project for which you want to
re-enable payments, and then click the menu (more_vert) next to it.
Select Change payment and select the destination payment account you
want.
did you provide api key to geocoded like this
Geocoder.init('your api key'); // use a valid API key
I had this problem because my google cloud free trial plan ended. When I upgraded to Blaze plan the error stopped happening.
Try this:
import React, {useEffect} from 'react';
import Geocoder from 'react-native-geocoding';
import {keys} from '../env';
First ensure your billing info and geocoding API are properly setup
and enabled.Then set up code to grant permission to avert future
issues
const _getCurrentPosition = async () => {
Geocoder.init(keys.GOOGLE_MAP_APIKEY); // initialized with a valid API key
const status = await locationPermission(); // write the function
if (status === 'granted') {
const location = await getCurrentLocation(); // write the function
console.log('Location Permission granted!');
console.log({currentLoc: location});
Geocoder.from({
latitude: location.latitude,
longitude: location.longitude,
})
.then(addressJson => {
const _location = addressJson.results[0].formatted_address;
console.log('location_', _location);
})
.catch(error => console.warn(error));
//or for non-geometry positions (plain addresses)
//**IMPORTANT** make sure the address is valid to avoid errors
//one way to do this is to first google a valid address
Geocoder.from("visakhapatnam")
.then(addressJson => {
const _location = addressJson.results[0].geometry.location;
console.log('location_', _location);
})
.catch(error => console.warn(error));
} else {
console.log('Permission not grantedd!');
}
};
useEffect(() => {
_getCurrentPosition();
}, []);
Don't forget to ALWAYS consult the documentation: https://www.npmjs.com/package/react-native-geocoding

Send push notifications to a specific logged user with pinpoint

Im developing a react native app integrated with aws-amplify and aws mobile hub.
We currently logged our user into cognito.
im trying to send a push notification to a specific endpoint Id, but i cannot see how to set that endpointId, in the node js (im using lambda) documentation for pinpoint only exist getEnpoint, but requires EnpointId and i cannot find where is it.
app.post('/asdf/get/endpoint', function (req, res) {
pinpoint.getEndpoint({
ApplicationId: APP_ID_PINPOINT,
EndpointId: req.body.userId
}, (err, data) => {
if (err) {
res.json({ error: err });
} else {
res.json({ data: data });
}
});
});
How can set the enpointId (userId) to an already logged user and then, every time i need to send a push to him i just get that enpoint and send a push to all the devices attached to it?
Or, i have to store all the tokens from the user (DynamoDb), and send messages to all the devices separately? (with pinpoint sendMessage)