import { initializeApp } from "firebase/app";
import { getDatabase, set, ref, update, get, child, query } from "firebase/database";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut} from "firebase/auth"
import { getFirestore, collection } from "firebase/firestore";
async function fetchAllOwnedByUser(userId) {
const dbRef = ref(getDatabase());
const _query = query(
collection(dbRef, "users"),
where("userId", "==", userId),
orderBy("createdAt", "desc")
);
const { docs } = await getDocs(_query);
return docs.map()
}
fetchAllOwnedByUser()
function getUsersEmail() {
const dbRef = ref(getDatabase());
// const token = credential.accessToken;
get(child(dbRef, `users/` )).then((snapshot) => {
if (snapshot.exists()) {
console.table(snapshot.val());
} else {
console.log("No data available");
}
}).catch((error) => {
console.error(error);
});
}
getUsersEmail()
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.3/firebase-app.js";
import { getDatabase, set, ref, update } from "https://www.gstatic.com/firebasejs/9.9.3/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/9.9.3/firebase-auth.js"
const firebaseConfig = {
apiKey: "AIzaSyBtqZbY6PnEMXjuFAdT6yvOvb7UgHvM42k",
authDomain: "auth-examplec.firebaseapp.com",
databaseURL: "https://auth-examplec-default-rtdb.firebaseio.com",
projectId: "auth-examplec",
storageBucket: "auth-examplec.appspot.com",
messagingSenderId: "724261682760",
appId: "1:724261682760:web:12652068e198094cdee27d"
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth();
const signUp = document.getElementById('signUp');
const login = document.getElementById('login');
const logout = document.getElementById('logout');
const goSignUp = document.querySelector('.goSignUp');
const goSignIn = document.querySelector('.goSignIn');
let loggedTitle = document.querySelector('.loggedTitle');
goSignUp.style.display = 'none';
logout.style.display = 'none';
login.style.display = 'none';
loggedTitle.style.display = 'none';
//* юзер зарегистрировался
function accountIsRegistred() {
signUp.style.display = 'none';
goSignIn.style.display = 'none';
login.style.display = 'block';
goSignUp.style.display = 'block';
}
//* юзер авторизировался
function logged(){
let email = document.querySelector('.sign-form__email');
let password = document.querySelector('.sign-form__password');
login.style.display = 'none';
goSignUp.style.display = 'none';
logout.style.display = 'block';
email.style.display = 'none';
password.style.display = 'none';
loggedTitle.style.display = 'block';
}
//* переход к регистрации
function registration(){
goSignUp.style.display = 'none';
logout.style.display = 'none';
login.style.display = 'none';
signUp.style.display = 'block';
goSignIn.style.display = 'block';
}
//* переход к авторизации
function goLogin() {
accountIsRegistred();
logout.style.display = 'none';
}
goSignIn.addEventListener('click', (e) => {
accountIsRegistred(signUp)
goSignIn.style.display = "none";
})
goSignUp.addEventListener('click', (e) => {
registration();
})
signUp.addEventListener('click', (e) => {
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
// let username = document.getElementById('username').value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
set(ref(database, 'users/' + user.uid),{
// username: username,
email: email,
password: password,
})
alert("user created " + email);
accountIsRegistred();
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
});
})
login.addEventListener('click', (e) => {
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
const dt = new Date();
update(ref(database, 'users/' + user.uid),{
last_login: dt
})
alert('User loged in! ' + email);
logged();
loggedTitle.innerHTML =" You are logged as " + email;
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
});
});
const user = auth.currentUser;
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// No user is signed in.
}
});
logout.addEventListener('click', (e) => {
signOut(auth).then(() => {
// Sign-out successful.
alert('user loged out');
goLogin();
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
});
});
const listAllUsers = (nextPageToken) => {
// List batch of users, 1000 at a time.
getAuth()
.listUsers(1000, nextPageToken)
.then((listUsersResult) => {
listUsersResult.users.forEach((userRecord) => {
console.log('user', userRecord.toJSON());
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(listUsersResult.pageToken);
}
})
.catch((error) => {
console.log('Error listing users:', error);
});
};
// Start listing users from the beginning, 1000 at a time.
listAllUsers();
</script>
sendMessage.addEventListener("click", function (e) {
let logMessage;
let sendDate = new Date();
let sendMinuts = (sendDate.getMinutes() < 10 ? "0" : "") + sendDate.getMinutes();
let sendHours = sendDate.getHours();
let sendMessageDate = sendHours + ":" + sendMinuts;
logMessage = sendMessageDate;
chatWrapper.insertAdjacentHTML(
"beforeend",
'<div class="chat-user chat-body"><div class="chat-user__image"><img src="img/person2.png" alt=""></div><div class="chat-user__message chat-message"><p class="chat-user__text">' +
inputMessage.value +
'</p><div class="chat-user__time chat-time">'+logMessage+'</div></div></div>'
);