firebase SDK error- Cant find variable admin - javascript

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.

Related

My Insert Statement for Supabase will not work

I recently set up a supabase database and set up the client in my react app (I am using typescript with my react app). I am certain that I set up the keys for client and imported into my component correctly, because I successfully retrieved data from the database. However, when I attempt to add an api call to insert data, it doesn't work. Here is the function all from within my component, which I have linked up to a button and calling on click:
const createAccount = async () => {
console.log('in create');
const { data, error } = await supabase
.from('accounts')
.insert([
{ name: 'Test', type: 'test'},
])
console.log(error);
console.log(data);
}
I am also certain that the function is being called when I click the button (see by console.log('in create')). However, no data is being inserted to my database. When I console.log the error, I see simply 'FetchError: Failed to fetch' with no more details.
I have RLS disabled on my table, and my table is set to public. What is my data not being inserted?

How do I fix 'Permission Denied' when I'm downloading a file from Firebase?

My project uses Firebase authentication and storage, and is built using React JS.
I have a file which is in the storage bucket at:
gs://myproject.appspot.com/myfolder/fileId
The download URL with token is:
https://firebasestorage.googleapis.com/v0/b/myproject.appspot.com/o/myfolder%2FfileId?alt=media&token=myToken
I want to be able to download the file in my app, so I have the following function within the Firebase class:
doDownloadFile = (path: string) => {
app
.storage()
.ref()
.child(path)
.getDownloadURL()
.then((url) => {
console.log(url);
})
.catch((error) => {
console.log('Error: ', error);
});
};
(at the moment I'm just getting the URL, not downloading it).
The value of path is the downloadURL as given above (I've checked this by logging it at the top of the doDownloadFile function, and it's being passed in ok).
When I run this code, I get the following error:
Firebase Storage: User does not have permission to access 'https:/firebasestorage.googleapis.com/v0/b/myproject.appspot.com/o/myfolder%2FfileId?alt=media&token=myToken'. (storage/unauthorized)
On Googling I found 2 general solutions to this, but neither have worked for me.
The first is to set the security rules on the storage in the Firebase console. I've set this to:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth!=null;
}
}
}
The second is to add the user firebase-storage#system.gserviceaccount.com as Storage Admin in the GCP console. This has been done.
Neither of these has made any difference, though. I still get the same error.
Where am I going wrong?

Catching Error With Custom Rest API For FireStore Javascript

I have been watching a tutorial on making a Rest API for Firestore which appears to work but I cannot figure out how to catch an error.
The code below basically uses an end point to retrieve a document id from the firestore database.
The client uses javascript fetch to call the API.
I am trying to workout how to return something back to the client from the API if the document id is not there. I thought I might get a 404 status returned but I always get status 200.
This is the API code I used
app.get("/api/read/:id", (req, res) => {
(async () => {
try {
const document = db.collection("users").doc(req.params.id);
let product = await document.get();
let response = product.data();
return res.status(200).send(response);
} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
})
I'm fairly certain that the 404 message is for the server itself not being found (though I do need to brush up on my error codes).
However, if you're looking to check to see if a document exists there's a command specifically for that demonstrated in the examples in the firebase docs

How do I set nested object entries coming from an api?

I got an object where I keep track of several things that the user can fill out, delete, update, etc.
Now, when 'loading' such a project, I make an api call to my backend using axios to retrieve the specific data to send it back to the client. The api call looks like this:
axios.get(`/api/data/${this.$route.params.dataId}`)
.then((response) => {
//Why does this not work?
this.nestedObject = response.data.object
//This DOES work... Why?
this.nestedObject.recipes = response.data.object.recipes
this.nestedObject.cheffs= response.data.object.cheffs
})
.catch((err) => {
console.log("error retrieving data: ", err);
});
Whenever I just set this.nestedObject equal to the data that is coming from the server, it does not work. nestedObject is not updated with the new values. But when I set the individual entries in the object equal to the data that is coming from the server, it does work and nestedObject is updated appropriately. Why is that?

How to create Microsoft Account Sign-in to my website, similar to Google?

I'm working on a web project (HTML, CSS, JavaScript, with back-end in PHP). I've successfully got a Google Sign-in working, using their simple API, but can't get the Microsoft equivalent to function. The official online solutions to this seem to rely on .NET or PHP Composer. I'll try composer if that's the only way but a pure JS/PHP method would be easiest.
I've tried to use the following:
https://github.com/microsoftgraph/msgraph-sdk-javascript
https://github.com/AzureAD/microsoft-authentication-library-for-js
The code below is the closest I've come to a working solution. I can get some kind of user ID (which appears to be unique and constant for each user). This might be enough to set up the login system I want, but it would be ideal if I could also fetch their name and profile picture.
<script class="pre">
var userAgentApplication = new Msal.UserAgentApplication("MY CLIENT ID", null, function (errorDes, token, error, tokenType) {
// this callback is called after loginRedirect OR acquireTokenRedirect (not used for loginPopup/aquireTokenPopup)
})
userAgentApplication.loginPopup(["user.read"]).then(function (token) {
var user = userAgentApplication.getUser(); //this is good
//user.userIdentifier seems to be a unique ID
//I will store this and use it for future verification
console.log(user);
//START
// get an access token
userAgentApplication.acquireTokenSilent(["user.read"]).then(function (token) {
console.log("ATS promise resolved");
}, function (error) {
console.log(error);
// interaction required
if (error.indexOf("interaction_required") != -1) {
userAgentApplication.acquireTokenPopup(["user.read"]).then(function (token) {
// success
console.log("s2");
}, function (error) {
console.log("e2");
// error
});
}
});
//END
// signin successful
}, function (error) {
console.log(error);
// handle error
});
</script>
(this code won't run as I've pasted it because it relies on the MSAL script from the second github link, and needs an application client ID)
After getting the access token with scope user.read , you could call microsoft graph api to get sign-in user's profile information such as displayName , businessPhones :
https://graph.microsoft.com/v1.0/me
Content-Type:application/json
Authorization:Bearer {token}
To get user's profile photo :
GET https://graph.microsoft.com/v1.0/me/photo/$value
In addition , if you are using Microsoft Graph JavaScript Client Library in first link , you could get user's displayName and profile photo by :
client
.api('/me')
.select("displayName")
.get((err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res);
});
// Example of downloading the user's profile photo and displaying it in an img tag
client
.api('/me/photo/$value')
.responseType('blob')
.get((err, res, rawResponse) => {
if (err) throw err;
const url = window.URL;
const blobUrl = url.createObjectURL(rawResponse.xhr.response);
document.getElementById("profileImg").setAttribute("src", blobUrl);
});
Please refer to code sample here .

Categories