Get value from push key generated - javascript

I want to get points of respectived logged in user to be displayed from database corresponding to its push key i tried many ways but i just couldn't make it possible here is my code
const autoid=firebase.database().ref("user").push().key;
firebase.database().ref("/").child(autoid).set({
email :email,
password : password,
points :"500",
Id:autoid
})
And below is my firebase realtime database picture:
The following code inserts the email, password, points and ID on realtime database with different key for every user that registers and i want to show the user when he is logged in to see his email and points? I tried trying different methods but I was unsuccessful anyway to do that?
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((credential) => {
firebase.database().ref("/users/" + credential.user.uid).set({
email: credential.user.email,
uid: credential.user.uid
});
alert("signed in");
})
I also tried this above code to get uid as a parent file rather then getting a random push id, but I have failed to do so and I don't know where the error is the rules used for my database is:-
{
"rules":{
".read": true,
".write":true
}
}
Do I need to change the rule?

To write the data in a node for the currently signed in user, you'd do:
const uid = firebase.auth().currentUser.uid;
firebase.database().ref("users").child(uid).set({
email: email,
password : password,
points: "500"
});
To subsequently read the data for the currently signed in user, you'd do:
const uid = firebase.auth().currentUser.uid;
firebase.database().ref("users").child(uid).once("value").then((snapshot) => {
console.log(snapshot.val());
});

Related

How to use an action code and then get the current user with firebase?

I am designing 2 pages for a user signing up. The first page is where the user enters their email only. I then perform this code.
await createUserWithEmailAndPassword(auth, email.value, bcrypt.hashSync(email.value, 6))
.then(async (userCredential) => {
sendEmailVerification(userCredential.user)
loading = false
navigate('/verifyEmail')
})
.catch((error) => {
log.error(`Error registering user: ${error}`)
errorMessage = error.message
isEmailInvalid = true
loading = false
})
This sends the user a verification email, which they then click on to set their password and name:
let oobCode = ''
oobCode = window.location.href.split('oobCode=')[1].split('&')[0]
const email = window.location.href.split('email=')[1].split('/')[0]
let user = auth.currentUser
await applyActionCode(auth, oobCode)
.then(async (result) => {
console.log(auth.currentUser)
Promise.all([
updateProfile(auth.currentUser, {displayName: firstName + ' ' + lastName}),
updatePassword(auth.currentUser, password),
])
console.log('Welcome', firstName, lastName)
await setUser('local', undefined, auth.currentUser)
})
However at this point, auth.currentUser will be null if the user has clicked on this link on a different browser. A quick workaround would be to create a user with password 'password' and then sign them in after applying the action code. However this has a big security flaw obviously, my current idea just encrypts their email as a temporary password in hopes they cannot guess it and sign in.
I guess my question is, how do I update the user upon applying an action code? If I can't do this what flow of operations should I change?
My question is, how do I update the user upon applying an action code?
If the user is using another browser it is not possible since he/she does not know the password.
If I can't do this what flow of operations should I change?
IMHO you are overcomplexifying the onboarding process. The common approach is to create the account with the password being chosen by the user (which, in your case, should happen in the first screen) and send the email for verification.
In parallel you deny access to the Firebase back-ends (DBs, Cloud Storage, etc.) to users with non verified email via the Security Rules.
Upon email verification you sign in the user:
If it is from the same browser the users is actually already signed in (side effect of the use of createUserWithEmailAndPassword()
If it is in a different browser the user just has to enter his email and password (which he/she knows)

How do I fetch user information to display in a feed of posts using firebase storage solutions?

I'm building a forum-style application where users post content that displays on a global feed. I want to display information about the user in posts (photoURL, displayName) similar to Twitter.
I have firebase v9 using the authentication and firestore for the posts. The reason I want to reference the auth is that I can catch changes to the user's information as it happens, this way the feed is up to date.
I save the user's unique ID with the post so I am able to reference who to display. I can successfully reference the post title and description with doc.title & doc.description however I get stuck when retrieving user information. I'm trying doc.UserID.displayName for the display name but I know this is incorrect. I can't find anything in the docs for this specific use case, is this something that I can do with just firestore and auth?
Do I need to create a reference to the auth storage with doc.UserID?
Here is the code:
// add a new post
addPostForm.addEventListener('submit', (e) => {
e.preventDefault();
onAuthStateChanged(auth, (user) => {
const colRef = collection(db, 'Posts');
console.log(hiddenURL.value);
addDoc(colRef, {
UserID: user.uid,
beatURL: hiddenURL.value,
title: addPostForm.postTitle.value,
description: addPostForm.postDescription.value,
})
.then(() => {
console.log("Document written with ID: ", doc.id);
addPostModal.classList.remove('open');
addPostForm.querySelector('.error').textContent = "";
})
.catch(error => {
addPostForm.querySelector('.error').textContent = error.message;
alert(error);
})
})
});
export const initApp = async () => {
initFirebaseAuth;
const posts = await collection(db, 'Posts');
// render data to the page
return renderPosts(posts);
};
const renderPosts = (posts) => {
const main = document.getElementById("feed");
onSnapshot(posts, (snapshot) => {
let cardsArray = []
snapshot.docs.forEach((doc, user) => {
cardsArray.push({ ...doc.data(), id: doc.id })
name.textContent = `${doc.UserID.displayName}`; // users display name
avatar.src = doc.UserID.photoURL; //user's image
description.textContent = `${post.description}`;
title.textContent = `${post.title}`;
});
console.log(cardsArray);
});
};
There are two cases and approaches at first sight:
1. Your users profiles are only available in the Auth Service
In this case, via the JS SDK, a user X cannot "query" the Auth profile of a user Y.
This means that you need to save the author's displayName together with the author uid when the post is created.
2. Your users profiles are also available in a users collection (a common pattern)
In this case, when you display a post, you could fetch the user's document to get the author's displayName.
However, in the NoSQL world, you should not be afraid to duplicate data and denormalize your data model. When designing your data-model you should think about it from a query perspective, trying to minimize the number of queries for a given screen/use case. So approach #1 is recommended, even if you maintain a user's collection.
In case of changes in the user's profile, in order to synchronyse the post documents and user's data a common approach is to use a set of Cloud Functions (which are executed in the back-end) to update the post documents. The link between the posts and the users profile being the user's uid.

How can I fix this issie with logging in users and storing them in a firestore database?

This code i used to store users in firebase.
this.db
.doc('/users/' + user.uid)
.set({
name: user.displayName,
email: user.email,
})
.then(() => console.log('user saved successfully'))
.catch((reason: any) => console.log('user save failed:', reason));
Users also have a isAdmin property that gets set elsewhere.
When I login as a new user, the user gets a name and email.
If i make the user admin i can visit admin only pages.
issue is, if i refresh on an admin page i get kicked of the page.
I think the issue is the set method, since it doesnt contain the isAdmin property
When I use update instead of set, it works fine when I refresh, but now I cant create new records for new users.
What is the best way to tackle this?
You're looking to merge the data in your set call with the existing data (if any), which you can do by specifying set options:
this.db
.doc('/users/' + user.uid)
.set({
name: user.displayName,
email: user.email,
}, { merge: true }) // 👈
Also see: https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document

Check for firebase's auth user's role when or after logging in

My firebase app has two different roles: user and admin. I assign these during the creation, which is done as follows:
const admin = require('firebase-admin')
...
const user = await admin.auth().createUser({
email,
emailVerified: true,
password,
displayName: name,
disabled: false
})
await admin.auth().setCustomUserClaims(user.uid, { role: 'user' })
For creating the admin we obviously do the same, but the last line becomes as follows:
await admin.auth().setCustomUserClaims(user.uid, { role: 'admin' })
These separate roles are use in the firebase rules to keep users from accessing certain collections as well as some cloud functions to prevent them from doing certain operations.
What I would like to do is on my client app to limit access to certain sections by checking the user role.
As it stands, when I authenticate I do not have access to the user role, so I don't know how to limit their access based on their role. Here is my authentication code:
// authenticating a user
const handle = firebase.auth().onAuthStateChanged(user => {
console.log('Authenticated user', user)
// do stuff
})
The issue here is that at this point the user object given to me by onAuthStateChanged doesn't have the role.
From the providerData attribute all I have is the following:
displayName
email
phoneNumber
photoURL
providerId
uid
The question is how can I access the user role on the client app to be able to block certain types of users from accessing restricted parts of the client app?
Try the following snippet:
firebase.auth().currentUser.getIdTokenResult()
.then((idTokenResult) => {
// Confirm the user is an Admin.
if (!!idTokenResult.claims.admin) {
// Show admin UI.
showAdminUI();
} else {
// Show regular user UI.
showRegularUI();
}
})
.catch((error) => {
console.log(error);
});
Source:
Firebase Auth

how to store signup data into redis with node.js

i want to store signup data it contains name and email and password.
i will store this data in mongodb like this
db.save({"name":"xxxx","email":"xxxxx","password":'xxxxxxxx'},function(err,result){});
when user login ,they surely give their email id or username with password so i will find this user exist in db or not by using like this
db.find({'email:'xxxxxxx','password':'xxxxxxxxx'},function(err,result){});
i have tried to do same in redis,by like this
db.hmset('key' name xxxxx email xxxx pass xxxxxx,function(){});
it is stored but how can i check email id usename already exist becz user will give email and password only.if i know key then only i can find that data.even if i know key i can get only data i could not be found data already exist ot not like mongodb
how can i solve this?
You could store your users both in a Set and a Hash for details.
You can then check in the Set if a user exists with: http://redis.io/commands/sismember
I think you should break things down into chunks instead of trying to do everything with one query. So, for example, to add a new user, first check if the user exists:
(My example assumes a Mongoose User Model has been defined)
User.findOne({$or : [{'email': req.body.email}, {'username': req.body.username}],
function(err, result) {
if (err) {next(err);}
if (result) {
// you found an existing user
res.send(309, {'message':'Error: User exists'});
} else {
// no user found
var user = new User({
'email': req.body.email,
'username': req.body.username,
'password': req.body.password,
'and-so-on': req.body.moredata
});
user.save(function(err){
if (err) {next(err);}
res.send(200, {'message':'User Registered Successfully'});
});
}
Honestly though, I wouldn't recommend writing a user authentication system from scratch, because it is pretty limiting in todays world of auth methods. I personally use Passport, because it gives you the ability to use multiple auth systems with your app, including Facebook, Twitter, and so on and so forth.

Categories

Resources