React doesn't recognize user attributes in Amplify app - javascript

I built an Amplify app with Cognito user pools for authentication/authorization. I am now trying to retrieve user attributes using Auth.currentAuthenticatedUser() . The example code they have (which works well) is the following:
import { Auth } from 'aws-amplify';
Auth.currentAuthenticatedUser({
bypassCache: false
})
.then((user) => console.log(user))
.catch((err) => console.log(err));
Here, the console.log(user) logs all of the current user data, as expected. I would like to now capture that data (or at least individual attributes of it) in a variable that I can use later on. However, if I try to define a variable using user it gives me an undefined error.
Here is an example of what I have tried and the error generated:
Code:
Auth.currentAuthenticatedUser({
bypassCache: false
})
.then((user) => console.log(user))
.catch((err) => console.log(err));
let userData = user;
Error:
'user' is not defined no-undef
I have also tried const and var but no matter what, it does not recognize userĀ . I don't understand how this is possible since it is successfully logged two lines above. Any ideas would be appreciated!

I was able to store the values within a const by putting it inside of a try/catch block:
try {
const user = await Auth.currentAuthenticatedUser();
const userGroup = user;
console.log(user);
} catch (err) {}
In my case, I only wanted the user group, so I actually narrowed it down to that parameter:
const userGroup = user.signInUserSession.accessToken.payload["cognito:groups"]

Related

Not able to extract custom error messages from Firebase Cloud Function

I have a firebase cloud function running locally. Its implemented like this
exports.verifyApp = functions.https.onRequest((req, res) => {
const {ref} = req.query;
// some business logic
if( ref === "123") return res.status(200).json({message: "success"});
return res.status(400).json({ error: "invalid-argument", message: "ref not provided" });
})
On frontend I am calling the cloud function like this
import {
getFunctions,
httpsCallableFromURL,
} from "firebase/functions";
const verifyClaim = httpsCallableFromURL(
getFunctions(),
"http://localhost:5001/{placeholder}/us-central1/verifyApp?ref=23"
);
verifyClaim()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.code, error.message);
});
I am not able to read/parse the custom error message being sent from the function. The .catch block only prints generic firebase error code and message i.e invalid-argument and internal. I can see the response in network tab though but .catch never seems to pick up the custom error message I am sending from cloud function.
You are mixing up Callable Cloud Functions and HTTP Cloud Functions.
You Cloud Function code corresponds to an HTTP one (functions.https.onRequest(...)) but the code in your front-end calls a Callable one (const verifyClaim = httpsCallableFromURL(...)).
You should adapt one or the other. It's difficult to advise which one to adapt with the few details shared in your answer.

404 error with GET request with correct credentials

I have switched my node package to the official shopify-api-node one and now the request isn't working it returns a 404 error.
The requests parameters seem to be fine after looking at the docs, and the shopName, access token etc are also correct i used the identical ones for the last package, (shopify-node-api) which i only stopped using because it returned a body in a strange coded language so i couldnt check it for errors, anyway here is the code:
The 'name' value is the order number by the way.
getOrderByNum: (req, res) => {
// const domain = req.params.domain;
const domain = 'chatbotdemo.myshopify.com'
const name = req.params.name;
console.log(req.body)
db.getStoreTocken(domain, (result) => {
const shopify = new Shopify({
shopName: domain,
accessToken: result,
autoLimit: true
});
shopify.order.get(name)
.then(order => {
console.log('console the order??!?!?!');
})
.catch(err => console.error('error??' + err));
Any help would be greatly appreciated,
the shopify docs:
https://www.npmjs.com/package/shopify-api-node

firebase SDK error- Cant find variable admin

When i am using the code below, i am getting an error :- cant find variable admin
admin.auth().getUserByEmail('svd#gmail.com')
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
//console.log("Successfully fetched user data:", userRecord.toJSON());
alert(userRecord.toJSON());
})
.catch(function(error) {
console.log("Error fetching user data:", error);
})
Try doing this and tell me whether this works for you or not. I'm also not sure whether it's a fetch issue or DB issue from your firebase JSON data.
As far as this admin variable is concerned, it looks like it is a firebase instance, make sure that you initialize your firebase in your project correctly. Follow this link and add it to your project, then import or initialize it in your particular class where you want to fetch the details.
Add Firebase to your JavaScript Project
Thinking that you might have stored some of the data. Doing code like this would work :
firebase.auth().getUserByEmail('svd#gmail.com')
.then((response) => response.json())
.then((responseJson) => {
/* check the data is it coming in your console or you can simply put it inside the alert() */
console.log(responseJSon);
})
.catch((error) => {
console.log("Error fetching user data:", error);
});
Note: Before implementing that make sure you have initialized the admin variable in your code, else it won't be able to perform an operation on null variable or non-defined variable. Ensure that as well.

Firebase Auth: updateProfile in Cloud Function?

I tried to use updateProfile() in my Cloud Function, triggered by HTTPS.
Error:
user.updateProfile is not a function
Cloud Function:
app.get("/user/create", (req, res) => {
res.setHeader('Content-Type', 'application/json')
admin.auth().verifyIdToken(req.query.token).then(user => {
let name = req.query.name
user.updateProfile({
displayName: name
}).then(() => {
res.send(JSON.stringify({
result: false,
error: err.message
}))
})
})
})
The error makes totally sense to me, but I've no clue how I can get a actual user reference to update the profile, any idea?
It looks like you're assuming that verifyIdToken() generates a promise that contains a User object. That's not the case here. According to the API docs, it provides a DecodedIdToken object. That object contains a uid property with the UID of the user represented by the token you passed to it.
If you want to get a UserRecord object from there, you can call admin.auth().getUser(uid) with that UID. However, that won't help you update the user's profile.
If you want to update the profile for a given UID, you can call admin.auth().updateUser(uid, properties).

Accessing firestore inside createUserWithEmailAndPassword method

i'm building the app using expo / react native and the firebase javascript web sdk. Could someone take a look at the code below and let me know whether they can figure out why my code isn't working? The code works fine when I'm using expo development mode, and the user profile gets set as expected. However in it's published state it is just not working. The new user is created and logged in, however it doesn't create the user profile.
firebase.auth().signInWithEmailAndPassword(email, password)
.then(user => loginUserSuccess(dispatch, user))
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((newUser) => {
var userRef = firebase.firestore().collection("users").doc(newUser.uid);
userRef.set({name: name, email: email, company: company, number: number, user: newUser.uid, adminEmail: '' })
.then(function (){
dispatch({ type: LOGIN_USER_SUCCESS, payload: newUser });
})
.catch(() => loginUserFail(dispatch)
);
})
.catch(() => loginUserFail(dispatch));
I've tried lots of different methods but keep having the same problem. According to the docs, the createUserWithEmailAndPassword method returns the User credentials. I've confirmed this with a debug statement and checked that I am accessing the uid property of said object.
Thanks

Categories