Receing null on activeuser after signing is done - javascript

I am using local storage to store username and password
I am getting null on active user after this line of code, I dont know why
console.log("I am the Active user: " + activeUser);
const menuChannelIcon = $(".menu-channel-icon");
const bellIcon = $(".bell-btn");
const uploadButtonIcon = $(".upload-btn");
const signInMainPageIcon = $(".signInMainPage");
const signUpMainPageIcon = $(".signUpMainPage");
const signOutMainPageIcon = $(".signOutMainPage");
const videoSectionMainPage = $(".video-section");
const signin = () => {
console.log("signin button clicked")
if (localStorage.getItem("formData")) {
// as long as you are getting items from the local storage... do..
JSON.parse(localStorage.getItem("formData")).forEach((data) => {
let x = $("#signEmail").val();
let z = $("#signinPassword").val();
if (data.email == x && data.pwd == z) {
isLogged = true;
activeUser = localStorage.getItem(email);
console.log("I am the Active user: " + activeUser);
menuChannelIcon.show();
bellIcon.show();
uploadButtonIcon.show();
signInMainPageIcon.hide();
signUpMainPageIcon.hide();
signOutMainPageIcon.show();
singIn_formContainer.hide();
videoSectionMainPage.show();
console.log("You are LOGGED");
}
});
}
};
Edit: email and pwd are set during signup

Answer posted by Barmar in the comments:
localStorage.getItem("email")
Alternative answer:
Shouldn't the active user be x when the email and password match something from formData? Why are you getting the active user from local storage?

Related

I want to the signup form details and login using those details in localstorage with NodeJS

I'm trying for 5 days. I couldn't come up with the solution.I'm a student.
function createUser(){
let user_name = document.getElementById("name").value;
let user_ph = document.getElementById("tel").value;
let user_dob = document.getElementById("date").value;
let new_passwd = document.getElementById("new-password").value;
let user_passwd = document.getElementById("confirm-password").value;
let user_data = new Array();
user_data = JSON.parse(localStorage.getItem("users"))?JSON.parse(localStorage.getItem("users")):[]
if(user_data.some((v)=>{return v.user_ph!=user_ph}))
{user_data.push({
"user_name": user_name,
"user_ph": user_ph,
"user_dob": user_dob,
"user_passwd": user_passwd
})
alert("account created for this mobile number");
localStorage.setItem("users",JSON.stringify(user_data));
window.location.href="./login.html";
}
else
{
alert("This number is already linked with another account");
window.location.href = "./reg.html";
}
}
I tried this code and it actually store the data in array even with the empty data and the page don't go to the other page. It stays there.
function login(){
let user_tel = document.getElementById("tel").value;
let user_passwd = document.getElementById("password").value;
user_data = JSON.parse(localStorage.getItem("users"))?JSON.parse(localStorage.getItem("users")):[]
if(user_data.some((v)=>{return v.user_ph==user_ph && v.user_passwd==user_passwd})){
alert("welcome!");
//window.location.href="../profiles/home.html";
}
else
{
alert("Phone number and password is not right")
window.location.href="./login.html"
}
}
this is code for my login page

Firebase Web Read from Real-Time Database

I'm trying to display the user's price that they entered in the database, but I'm getting "undefined' back instead of the value that was entered. I didn't get any errors in the console either. How can I fix this? I am using HTML, JavaScript, and CSS. I have provided a screenshot and my code.
Studio Dashboard JavaScript code:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const database = firebase.database();
const auth = firebase.auth();
//const auth = getAuth();
firebase.auth().onAuthStateChanged((user) => {
if (user) {
readData();
// ...
} else {
window.location.href = "login.html?error";
alert("No active user please sign or sign up.");
}
});
function readData() {
const user = firebase.auth().currentUser;
database.ref('/studiopick/studio/users/' + user.uid).get().then(snapshot => {
// Tab One Display
document.getElementById("studioName").innerText = snapshot.val().studioName;
document.getElementById("profile-name").innerText = snapshot.val().studioName;
document.getElementById("firstName").innerText = snapshot.val().firstName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("email").innerText = snapshot.val().email;
document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber;
// Tab Two Display
document.getElementById("servicePrice").innerText = snapshot.val().numberInput;
}).catch(e => { console.log(e) })
}
function updatePrice() {
// Get data
numberInput = document.getElementById("numberInput").value;
const user = firebase.auth().currentUser;
// Enter database location
firebase
.database()
.ref('/studiopick/studio/users/' + user.uid + "/prices/roomA/serviceOne")
.update({
//studioName : studioName,
numberInput: numberInput,
});
}
You should use the on method instead of get
function readData() {
const user = firebase.auth().currentUser;
database.ref('/studiopick/studio/users/' + user.uid).on('value', (snapshot) => {
//Tab One Display
document.getElementById("studioName").innerText = snapshot.val().studioName;
document.getElementById("profile-name").innerText = snapshot.val().studioName;
document.getElementById("firstName").innerText = snapshot.val().firstName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("email").innerText = snapshot.val().email;
document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber;
//Tab Two Display
document.getElementById("servicePrice").innerText = snapshot.val().numberInput;
}, (e) => { console.log(e) })
}

checking browser local storage for item in array

I have created a login button that is supposed to take the Array stored in the browser local storage, read each item and check if the username and password written in the input boxes are inside the Array).
The Array is successfuly taken from storage, but when the code is supposed to read it and compare the items to the input for some reason it always says the input isn't in the Array. How could I fix that? Code follows:
const loginForm = document.getElementById("loginForm");
const loginButton = document.getElementById("loginButton");
const loginError = document.getElementById("loginError");
const registerForm = document.getElementById("registerForm");
const registerButton = document.getElementById( "registerButton");
const registerError = document.getElementById("registerError");
/*HERE IS THE PROBLEMATIC LOGIN BUTTON*/
loginButton.addEventListener("click", (e)=> {
e.preventDefault();
const username = loginForm.username.value;
const password = loginForm.password.value;
const user ={ username, password};
let checkUser =[];
checkUser = JSON.parse(localStorage.getItem("registred users"));
let checkUserInfo = checkUser.includes(user, 0);
if( checkUserInfo == true){
alert("Login sucessful!");
location.reload();
} else {
loginError.style.opacity = 2;
}
})
registerButton.addEventListener("click", (e)=> {
e.preventDefault();
const registerUsername = registerForm.registerUsername.value;
const registerPassword = registerForm.registerPassword.value;
const confirmPassword = registerForm.confirmPassword.value;
const registerEmail = registerForm.registerEmail.value;
const userData = {registerUsername, registerPassword};
let registredUserData = [];
if(registerPassword.length > 8 && registerPassword.match(/[a-z]+/) && registerPassword.match(/[A-Z]+/) && registerPassword.match(/[0-9]+/) && registerPassword.match(/[$##&!]+/) && registerPassword === confirmPassword && registerEmail.match(/[#/]+/ ) ){
registredUserData = JSON.parse(localStorage.getItem("registred users"));
registredUserData.push(userData);
localStorage.setItem("registred users",JSON.stringify(registredUserData));
location.reload();
} else {
registerError.style.opacity = 2;
}
})
You are comparing two objects for equality. Even though you use includes, it still checks if the value you put in is equal to an element in the array.
If you need to check for both username and password, loop through the array with some and see if the properties of one of the objects are equal to the provided input.
let checkUserInfo = checkUser.some(u => u.username === user.username && u.password === user.password);
Also keep in mind that this type of client side authentication is dummy auth for demonstration purposes only; it will not function as real authentication for any service.
You shouldn't use the includes to search for a similar object in an array of objects. You have to search one by one. You should use a filter type method like find() or some().
Your code would be something like:
/*HERE IS THE PROBLEMATIC LOGIN BUTTON*/
loginButton.addEventListener("click", (e)=> {
e.preventDefault();
const username = loginForm.username.value;
const password = loginForm.password.value;
const user ={ username, password};
let checkUser =[];
checkUser = JSON.parse(localStorage.getItem("registred users"));
let checkUserInfo = checkUser.some(item => item.username === user.username && item.password === user.password);
if( checkUserInfo == true){
alert("Login sucessful!");
location.reload();
} else {
loginError.style.opacity = 2;
}
})
Obs.: This is a extremely bad way to store password data. You should use some library that uses hash like bcryptjs.

Retrieving Firebase Child Value in Javascript

function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid);
if (adaRef.orderByChild("Role").equalTo("admin")) {
location.href = "DB.html";
} else {
location.href = "index.html";
}
}
I would like to link my "admin" account to DB.html and "user" account to index.html but i think i always failed in Retrieving the Child Value.
You're not retrieving the data from the server. Remember you need to call .once('value') to get your query and then iterate through the remaining code based onw hether their value is of admin or user. Firebase Docs has more explination I've amended your code and put it below
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
return snapshot.forEach(snapshot=>{
if (snapshot.child("Role").val()==="admin") {
location.href = "DB.html";
} else {
location.href = "index.html";
}
return console.log("added");
})
})
}
If you just wanted to find out who was of the user type admin...i'd use this below...much more efficient.
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
//you now have all the users that are just admins
return snapshot.forEach(snapshot=>{
location.href = "DB.html";
return console.log("added");
})
})
}

Update roles only allowing one to the user at a time

Currently, the user is able to choose as many roles given within the section, however, I would like to be able to do something along the lines of:
(roleA OR roleB) AND (roleC OR roleD) AND roleE etc
The above is all meant to be triggered by checking what reactions they've already submitted and removing them if the new selection contradicts the current.
Users are able to apply reaction roles to themselves by reacting to a specified message. Depending on whether a certain choice is made, it's to be able to add/remove from another role i.e
How old are you?
- 18-24
- 25-30
- 31+
What's your Gender?
- Male
- Female
What Continent are you in?
- IDK, I'm running out of
- Bogus Questions
- To fill in space.
if user clicks, 25-30, but then realises they're 24, and click that instead, I'd like the prior reaction & role to be removed without manual interference required.
Not only 1 option will be available, so would like to have multiple selections available as well.
bot.on("raw", event =>{
console.log(event);
const eventName = event.t;
if(eventName === 'MESSAGE_REACTION_ADD')
{
if(event.d.message_id === '<REMOVED ID>')
{
var reactionChannel = bot.channels.get(event.d.channel_id);
if(reactionChannel.messages.has(event.d.message_id))
return;
else {
reactionChannel.fetchMessage(event.d.message_id)
.then(msg => {
var msgReaction = msg.reactions.get(event.d.emoji.name + ":" + event.d.emoji.id);
var user = bot.users.get(event.d.user_id);
bot.emit('messageReactionAdd', msgReaction, user);
})
.catch(err => console.log(err));
}
}
}
else if (eventName === 'MESSAGE_REACTION_REMOVE')
{
if(event.d.message_id === '<REMOVED ID>')
{
var reactionChannel = bot.channels.get(event.d.channel_id);
if(reactionChannel.messages.has(event.d.message_id))
return;
else{
reactionChannel.fetchMessage(event.d.message_id)
.then(msg => {
var msgReaction = msg.reactions.get(event.d.emoji.name + ":" + event.d.emoji.id);
var user = bot.users.get(event.d.user_id);
bot.emit('messageReactionRemove', msgReaction, user);
})
.catch(err => console.log(err));
}
}
}
});
bot.on('messageReactionAdd', (messageReaction, user) => {
var roleName = messageReaction.emoji.name;
var role = messageReaction.message.guild.roles.find(role => role.name.toLowerCase() === roleName.toLowerCase());
if(role)
{
var member = messageReaction.message.guild.members.find(member => member.id === user.id);
if(member)
{
member.addRole(role.id);
console.log('Success. Added role.');
}
}
});
bot.on('messageReactionRemove', (messageReaction, user) => {
var roleName = messageReaction.emoji.name;
var role = messageReaction.message.guild.roles.find(role => role.name.toLowerCase() === roleName.toLowerCase());
if(role)
{
var member = messageReaction.message.guild.members.find(member => member.id === user.id);
if(member)
{
member.removeRole(role.id);
console.log('Success. Removed role.');
}
}
});```
In your messageReactionAdd event, you can try to find a reaction or role applied by/to the user that corresponds with a specific choice. If there is one, that means they had already chose that answer. You can then remove them before adding the new role to the user. If not, the code should continue as usual.
bot.on('messageReactionAdd', async (messageReaction, user) => { // async needed for 'await'
const name = messageReaction.emoji.name.toLowerCase();
const message = messageReaction.message;
const role = message.guild.roles.find(role => role.name.toLowerCase() === name);
const member = message.guild.member(user);
if (!role || !member) return;
const emojis = message.reactions.map(emoji => emoji.name);
const conflictingReaction = message.reactions.find(reaction => reaction.users.get(user.id) && emojis.includes(reaction.emoji.name));
const conflictingRole = member.roles.find(role => emojis.includes(role.name.toLowerCase());
try {
if (conflictingReaction || conflictingRole) {
await conflictingReaction.remove(user);
await member.removeRole(conflictingRole);
}
await member.addRole(role);
console.log('Success.');
} catch(err) {
console.error(err);
}
});

Categories