User is not getting created in Firebase web app - javascript

User is not getting created ! The same code works on another sample file I got from youtube , but when I copied and used in my code , it is not working. The user is successfully created in my database with my init-details on that sample file,so I dont think the problem is with my firebase , its somewhere here i think.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var user = firebase.auth().currentUser;
if(user != null){
}
} else {
// No user is signed in.
}
});
function login(){
var userEmail = document.getElementById("ie").value;
var userPass = document.getElementById("ip").value;
window.alert(userEmail+ " "+ userPass);
firebase.auth().createUserWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
// ...
});
}
function logout(){
firebase.auth().signOut();
}
<html>
<head>
<title>Admin Login</title>
<link href="index-css.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="login-page">
<div class="form">
<p>Admin Login</p>
<form class="login-form">
<input id="ie"type="text" placeholder="Email"/>
<input id="ip"type="password" placeholder="Password"/>
<button id="loginbtn" onclick="login()">Login</button>
</form>
</div>
</div>
<script src="https://www.gstatic.com/firebasejs/5.8.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyA8QeKSDbtgq6GiSS3MBjU2i43IZgYeMRE",
authDomain: "web-app-login-a90bb.firebaseapp.com",
databaseURL: "https://web-app-login-a90bb.firebaseio.com",
projectId: "web-app-login-a90bb",
storageBucket: "web-app-login-a90bb.appspot.com",
messagingSenderId: "695872421055"
};
firebase.initializeApp(config);
</script>
<script src="index.js"></script>
</body>
</html>

Related

firebase.auth().SignInWithPhoneNumber is not a function

window.onload=function(){
render();
};
function render(){
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
recaptchaVerifier.render().then(widgetId => {
window.recaptchaWidgetId = widgetId;
})
}
function phoneAuth(){
var number=document.getElementById('number').value;
firebase.auth().SignInWithPhoneNumber(number,window.recaptchaVerifier).then(function(confirmationResult){
//const sentCodeId = confirmationResult.verificationId;
//signInWithPhoneButton.addEventListener('click', () => signInWithPhone(sentCodeId));
window.confirmationResult = confirmationResult;
coderesult=confirmationResult;
console.log(coderesult);
alert("Message sent");
}).catch(function(error){
alert(error.message);
});
}
function codeverify(){
var code= document.getElementById('verificationCode').value
coderesult.confirm(code).then(function(result){
alert("Successfully register");
var user=result.user;
console.log(user);
}).catch(function(error){
alert(error.message);
});
}
<h1>Enter number</h1>
<form>
<input type="text" id ="number" placeholder="+49**********">
<div id="recaptcha-container"></div>
<button type="button" onclick="phoneAuth();">SendCode</button>
</form><br>
<h1>Enter Code</h1>
<form>
<input type="text" id ="verificationCode" placeholder="Enter verification Code">
<button type="button" onclick="codeverify();">Verify Code</button>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.2.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.3/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.3/firebase-performance.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<!--<script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-analytics.js"></script>-->
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "-",
authDomain: "-",
databaseURL: "-",
projectId: "-",
storageBucket: "-",
messagingSenderId: "-",
appId: "-",
measurementId: "-"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//firebase.analytics();
// make auth and firestore references
const auth = firebase.auth();
const db = firebase.firestore();
// update firestore settings
//db.settings({ timestampsInSnapshots: true });
</script>
<!-- Compiled and minified JavaScript -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!--<script src="scripts/auth.js"></script> -->
<script src="scripts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script src="script.js"></script>
Hello everyone! I want to use the Firebase-Phone-Authentication but it's not working, here my code.
Everytime I want to use it there is an error in the console "firebase.auth().SignInWithPhoneNumber is not a function".I have watched some videos on Youtube and also tried some code from the internet but nothing works. I'm thankful for every Help:)!

Why does it show up a null in the textarea twice?

When I type in the title it shows up as null even though it is there. Also the textarea shows up twice. Thank you any help is appreciated. I feel like I need to convert it to something for it actually read, but I am just a begineer.
I have tried parsing it to JSON,but feel free to show me how it is properly done.
Sorry for my English
var title_s = document.getElementById("TitleSearch");
var titlejson = JSON.parse(title_s);
var teststring = "test";
//This is to intialize everything and auth. with the firebase server
var config = {
apiKey: "AIzaSyB9p1VvVfhnbrcDwUKUuSqw9aQsqnDi4nQ",
authDomain: "html5project-870df.firebaseapp.com",
databaseURL: "https://html5project-870df.firebaseio.com",
projectId: "html5project-870df",
storageBucket: "html5project-870df.appspot.com",
messagingSenderId: "54935462861"
};
//firebase.initializeApp(config);
//checks if it has been init
if (!firebase.apps.length) {
firebase.initializeApp({});
}
//declare variables
var database = firebase.database();
//tells where the items are going to be
var Rootref = database.ref().child("users");
var ref = firebase.database().ref("users");
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
//var Rootref1 = database.ref().child("users").child("id: 113295907411766134791")/*.child("trans")*/;
//used to retrieve data
Rootref.on("child_added",snap => {
//gets the child of titles stores it as variable
var transcript_title = snap.child("titles").val();
//var transcript_title = (snap.val() && snap.val().titles);
//gets the actual title and stores it as a var
//var transcript = snap.child(transcript_title).val();
$('#transcrip').val(snap.child('users/id: 107621796826103613669'))
//jquery - way to add html elemnts with javascript
snap.child("titles").forEach(function(titleSnap) {
$("#read").append('<h4 id = "clicked">'+titleSnap.val()+'</h4>');
})
console.log(teststring);
$( "#TitleButton" ).click(function() {
var search = snap.child(title_s).val();
$("#ReadHere").append('<textarea placeholder="Shows up right here" col="50" row="10">'+search+'</textarea>');
});
//$("#read").append('<h4 >Test</h4>');
//when button view was clicked it will show the transcriptiodn
});
<!DOCTYPE html>
<html>
<head>
<!--Calling every thing required-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="54935462861-sedlkvk3ufqujgpo2hmevectur8p4o2u.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="https://www.gstatic.com/firebasejs/5.8.4/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyB9p1VvVfhnbrcDwUKUuSqw9aQsqnDi4nQ",
authDomain: "html5project-870df.firebaseapp.com",
databaseURL: "https://html5project-870df.firebaseio.com",
projectId: "html5project-870df",
storageBucket: "html5project-870df.appspot.com",
messagingSenderId: "54935462861"
};
firebase.initializeApp(config);
</script>
<!--Title on top left-->
<h1>View your Transcriptions</h1>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="read.js"></script>
</head>
<body>
<input type="text" id="TitleSearch">
<button id = "TitleButton">Search</button>
<center>
<ul id="read">
</ul>
</center>
<div id = "ReadHere">
</div>
<!--When clicked on you view it here-->
<h1>Viewed Right Here</h1>
<p id = "transcrip"></p>
</body>
</html>
{
"users" : {
"id: 110753432956858279660" : {
"Test" : "He",
"Test2" : "He",
"titles" : {
"201920201828" : "Test",
"201920202259" : "Test2"
}
},
"id: 113295907411766134791" : {
"test" : {
"text" : "text"
},
"test3" : {
"text" : "text"
}
}
}
}

Firebase Sign In With Email fails without providing an error

In my JavaScript Firebase application, I have tried to set up user authentication via email, and at the same time sync user data to Firebase's realtime database. While our Google sign in worked with no problems, the function that makes accounts, firebase.auth().createUserWithEmailAndPassword(email, password); fails to execute and (annoyingly) does not throw any error messages. Here is the code:
main.js: (The problematic section is submitAcc())
var config = {
apiKey: "censored",
authDomain: "censored",
databaseURL: "censored",
projectId: "censored",
storageBucket: "censored",
messagingSenderId: "censored"
};
firebase.initializeApp(config);
var database = firebase.database();
function showAccCreate() { //Hides and shows account create button
var x = document.getElementById("hiddenaccountcreation");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function submitAcc() { //On submit button pressed
alert("Signing in");
var email = document.getElementById("emailinput").value;
var password = document.getElementById("passinput").value;
var username = document.getElementById("usernameinput").value;
//console.log(email + password +username);
var user;
alert("recorded values");
firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(email,password).then(function(result) {
alert("Gets into .then");
var user = firebase.auth().currentUser;
var uidvalue = user.uid;
console.log(uidvalue);
console.log(uidvalue);
alert("User value recorded");
writeUserDataFromEmailSignin(email, username,uidvalue);
alert(user.uid);
}).catch(function(error) {
alert(error.message);
console.log(error.message);
console.log(error.code);
});
}
//Testing if auth state changes
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
alert("User is signed in.");
document.getElementById("debugtest").innerHTML = "Signed in";
}
});
function writeUserDataFromEmailSignin(email, name, uuid) { //Writes user data to database if user signs in
alert("Entered function");
database.ref('users/' + uuid).set({
"name": name,
"email": email,
"uid": uuid,
}).then(function() {
alert("Completed");
}).catch(function() {
console.log(error.message);
console.log(error.code);
})
}
function showsignin() {
var x = document.getElementById("hiddensignin");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function googlesignin() { //Signs people into app via Google
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope("https://www.googleapis.com/auth/contacts.readonly");
firebase.auth().languageCode = 'en';
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken; //Google Auth access token
var user = result.user; //Contains all user info that Google provided us
writeToDatabaseFromGoogle(user.email, user.displayName, user.uid, user.photoUrl);
}).catch(function(error) {
console.log(error.message);
console.log(error.code);
});
}
function writeToDatabaseFromGoogle(email, name, uuid, image_url) { //Writes user data to database from Google signin
database.ref("users/" + uuid).set({
"name": name,
"email": email,
//"imageUrl": image_url,
"uid": uuid,
}).catch(function(error) {
console.log(error.message);
console.log(error.code);
});
}
function signInUser() { //Uses email sign-in so signin to existing account
var email = document.getElementById("emailreauth");
var pass = document.getElementById("passreauth");
// noinspection JSUnresolvedFunction
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
//Handle errors here
let errorCode = error.code;
let errorMessage = error.MESSAGE;
console.log(errorCode);
console.log(errorMessage);
});
}
and the index.html file:
<!DOCTYPE html>
<!--suppress HtmlRequiredLangAttribute -->
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAhglAXFWaJhtvOrfeugAMgJHrBw5CUNEc",
authDomain: "projectcrosscomm.firebaseapp.com",
databaseURL: "https://projectcrosscomm.firebaseio.com",
projectId: "projectcrosscomm",
storageBucket: "projectcrosscomm.appspot.com",
messagingSenderId: "412861101382"
};
firebase.initializeApp(config);
</script>
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-database.js"></script>
<!-- Comment out (or don't include) services that you don't want to use -->
<!-- <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-storage.js"></script> -->
<script src="main.js" rel="script"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Cross Comm!</title>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<button id="accountcreate" onclick="showAccCreate()">Create your account here!</button>
<button id="showsignin" onclick="showsignin()">Already have an account?</button>
<button2 id="googlesignin" onclick="googlesignin()">Sign in with Google</button2>
<h1>Project Cross Comm!</h1>
<h2 id="subtitle">
Welcome to <strong>Project Cross Comm!</strong>
</h2>
<img height="200px" src="https://i.kym-cdn.com/entries/icons/mobile/000/013/564/doge.jpg" width="260px" alt="If you can't see this image you're a pleb">
<h2></h2>
<p id="desc"> Project Cross Comm is a free to use chatting program that runs in your browser. All the chats are encrypted, so no one can read your chats. Enjoy the program and chat away.</p>
<div id="hiddenaccountcreation">
<form>
<fieldset>
<legend>Account Creation</legend> <!--Create account via email sign-in-->
<p>
<label for="usernameinput">Username</label>
<input type="text" id="usernameinput" name="createUsername" placeholder="Username">
<p>
<label for="emailinput">Email</label>
<input type="email" id="emailinput" value="" placeholder="example#example.com" name="createEmail">
</p>
<p>
<label for="passinput">Password</label>
<input type="password" id="passinput" value="" placeholder="password" name="createPass">
</p>
<button id="submit" onclick="submitAcc()">SUBMIT</button>
</fieldset>
</form>
</div>
<div id="hiddensignin">
<form>
<fieldset>
<legend>Sign In</legend>
<p>
<label for="usernamereauth">Username</label>
<input type="text" id="usernamereauth" value="">
<p>
<label for="emailreauth">Email</label>
<input type="email" id="emailreauth" value="">
</p>
<p>
<label for="passreauth">Password</label>
<input type="password" id="passreauth" value="">
</p>
<button id="signin" onclick="signInUser()">SUBMIT</button>
</fieldset>
</form>
</div>
<div id="getthisblockoutofmygoddamnedway"> <!--Problematic code block that another member of my team put there -->
<a style = "color: white; "id="link" href="InfoPage.html">Click here for more information.</a>
<h6></h6>
<a style = "color: white; "id="link2" href="ChatLayout.html">Click Here To Chat</a>
<h6></h6>
<a style = "color: white; "id="link3" href="https://app.termly.io/document/privacy-policy/0ae020d8-ee05-4202-a0c7-d4ff19e8f661">Privacy Policy </a>
</div>
</body>
<footer>
<p id="debugtest" class="debug">Haven't Been Signed In Yet</p>
<noscript>Man, sucks for you! We only support modern, functioning browsers. Maybe you should get JavaScript </noscript>
</footer>
</html>
The farthest alert my program gets to is alert("recorded values");, no further alerts are executed. Javascript does not throw any errors during the process; the console is empty. Is there any way to find out what's wrong, or even to force Javascript to be more verbose and log its memory every so often?
Can you please try this? This works in my case.
firebase.auth().signInWithEmailAndPassword(email, password)
.then(response => {
const uid = response.user.uid; // you have uid
response.user.getIdToken()
.then(token => {
// do anything with token
})
.catch(error => {
// any error handling
})
})
.catch(error => {
// any error handling
})
Your Current issue is you are not able to store the Values into the DB with the method submitAcc().This method is called when the user creates the account. I have corrected and made some changes please test and let me know if that works for you.
I have added two functions logout() and status() to understand where the problem is. I'd suggest you remove them.
I have also observed in the method signInUser(). You have missed the .value to Email and Password and corrected it.
See below image once the user clicks to Create the Account.I have logged his input to console.
Database Saving user's info:
Code
var database = firebase.database();
function showAccCreate() { //Hides and shows account create button
var x = document.getElementById("hiddenaccountcreation");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function submitAcc() { //On submit button pressed
alert("Signing in");
var email = document.getElementById("emailinput").value;
var password = document.getElementById("passinput").value;
var username = document.getElementById("usernameinput").value;
console.log(email + password +username);
alert("recorded values");
firebase.auth().createUserWithEmailAndPassword(email,password).then(function(result) {
alert("Gets into .then");
var user = firebase.auth().currentUser;
var uidvalue = user.uid;
console.log(uidvalue);
console.log(uidvalue);
alert("User value recorded");
writeUserDataFromEmailSignin(email, username,uidvalue);
alert(user.uid);
}).catch(function(error) {
alert(error.message);
console.log(error.message);
console.log(error.code);
});
}
function writeUserDataFromEmailSignin(email, name, uuid) { //Writes user data to database if user signs in
alert("Entered function");
database.ref('users/' + uuid).set({
"name": name,
"email": email,
"uid": uuid,
}).then(function() {
alert("Completed");
}).catch(function() {
console.log(error.message);
console.log(error.code);
})
}
function logout()
{
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
}
function status()
{
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var emailv =user.email;
console.log("User is signed in. em ankunav enti "+ emailv);
} else {
console.log("No user is signed in.");
}
});
}
//Testing if auth state changes
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
alert("User is signed in.");
document.getElementById("debugtest").innerHTML = "Signed in";
}
else
{
document.getElementById("debugtest").innerHTML = "NOT LOGGED IN ";
}
});
function showsignin() {
var x = document.getElementById("hiddensignin");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function signInUser() { //Uses email sign-in so signin to existing account
var email = document.getElementById("emailreauth").value;
var pass = document.getElementById("passreauth").value;
// noinspection JSUnresolvedFunction
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
//Handle errors here
let errorCode = error.code;
let errorMessage = error.MESSAGE;
console.log(errorCode);
console.log(errorMessage);
});
}
<!DOCTYPE html>
<!--suppress HtmlRequiredLangAttribute -->
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "hmcalreac",
authDomain: "kbckyc",
databaseURL: "https://abc.dmc",
projectId: "test12d",
storageBucket: "t11",
messagingSenderId: "11"
};
firebase.initializeApp(config);
</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Cross Comm!</title>
</head>
<body>
<button id="accountcreate" onclick="showAccCreate()">Create your account here!</button>
<button id="showsignin" onclick="showsignin()">Already have an account?</button>
<button2 id="googlesignin" onclick="googlesignin()">Sign in with Google</button2>
<h1>Project Cross Comm!</h1>
<h2 id="subtitle">
Welcome to <strong>Project Cross Comm!</strong>
</h2>
<img height="200px" src="https://i.kym-cdn.com/entries/icons/mobile/000/013/564/doge.jpg" width="260px" alt="If you can't see this image you're a pleb">
<h2></h2>
<p id="desc"> Project Cross Comm is a free to use chatting program that runs in your browser. All the chats are encrypted, so no one can read your chats. Enjoy the program and chat away.</p>
<div id="hiddenaccountcreation">
<fieldset>
<legend>Account Creation</legend> <!--Create account via email sign-in-->
<p>
<label for="usernameinput">Username</label>
<input type="text" id="usernameinput" name="createUsername" placeholder="Username">
<p>
<label for="emailinput">Email</label>
<input type="email" id="emailinput" value="" placeholder="example#example.com" name="createEmail">
</p>
<p>
<label for="passinput">Password</label>
<input type="password" id="passinput" value="" placeholder="password" name="createPass">
</p>
<button id="submit" onclick="submitAcc()">SUBMIT TO CREATE ACCOUNT </button>
</fieldset>
</div>
<div id="hiddensignin">
<fieldset>
<legend>Sign In</legend>
<p>
<label for="usernamereauth">Username</label>
<input type="text" id="usernamereauth" value="">
<p>
<label for="emailreauth">Email</label>
<input type="email" id="emailreauth" value="">
</p>
<p>
<label for="passreauth">Password</label>
<input type="password" id="passreauth" value="">
</p>
<button id="signin" onclick="signInUser()">SUBMIT To Signin to console</button>
</fieldset>
</div>
<button id=mystat onclick="status()">CLICK me to GET Status</button>
<button id=mystat onclick="logout()">CLICK me to logout </button>
<div id="getthisblockoutofmygoddamnedway"> <!--Problematic code block that another member of my team put there -->
<a style = "color: white; "id="link" href="InfoPage.html">Click here for more information.</a>
<h6></h6>
<a style = "color: white; "id="link2" href="ChatLayout.html">Click Here To Chat</a>
<h6></h6>
<a style = "color: white; "id="link3" href="https://app.termly.io/document/privacy-policy/0ae020d8-ee05-4202-a0c7-d4ff19e8f661">Privacy Policy </a>
</div>
<script src="ne2.js" rel="script"></script>
</body>
<footer>
<p id="debugtest" class="debug">Haven't Been Signed In Yet</p>
<noscript>Man, sucks for you! We only support modern, functioning browsers. Maybe you should get JavaScript </noscript>
</footer>
</html>

firebaseui.js:formatted:9514 Uncaught TypeError: Cannot read property 'EmailAuthProvider' of undefined

i wanted to use the Firebase UI and i used it, It was working fine at the first time but broken
But i don't think this has the problem because its the code from Firebase UI themself
This is the code I have in index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://www.gstatic.com/firebasejs/5.0.4/firebase.js"></script>
<script>
var config = {
apiKey: "**************************",
authDomain: "chat-77ca3.firebaseapp.com",
databaseURL: "https://chat-77ca3.firebaseio.com",
projectId: "chat-77ca3",
storageBucket: "chat-77ca3.appspot.com",
messagingSenderId: "312413147357"
};
firebase.initializeApp(config);
</script>
<title>Chat</title>
<script defer="defer" src="https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js"></script>
<script defer="defer" src="https://www.gstatic.com/firebasejs/5.0.4/firebase-database.js"></script>
<script defer="" src="/__/firebase/init.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdn.firebase.com/libs/firebaseui/3.3.0/firebaseui.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/3.3.0/firebaseui.css" />
<script src="node_modules/firebaseui/dist/firebaseui.js"></script>
<script type="text/javascript">
var uiConfig = {
signInSuccessUrl: 'loggedin.html',
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID,
firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
]
}
var ui = new firebaseui.auth.AuthUI(firebase.auth());
ui.start('#firebaseui-auth-container', uiConfig);
</script>
</head>
<body>
<div id="firebaseui-auth-container"></div>
</body>
</html>
And this is the javascript in loggedin.html
HTML not included
< script type = "text/javascript" >
initApp = function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var uid = user.uid;
var phoneNumber = user.phoneNumber;
var providerData = user.providerData;
user.getIdToken().then(function(accessToken) {
document.getElementById('sign-in-status').textContent = 'Signed in';
document.getElementById('sign-in').textContent = 'Sign out';
document.getElementById('account-details').textContent = JSON.stringify({
displayName: displayName,
email: email,
emailVerified: emailVerified,
phoneNumber: phoneNumber,
photoURL: photoURL,
uid: uid,
accessToken: accessToken,
providerData: providerData
}, null, ' ');
});
} else {
document.getElementById('sign-in-status').textContent = 'Signed out';
document.getElementById('sign-in').textContent = 'Sign in';
document.getElementById('account-details').textContent = 'null';
}
}, function(error) {
console.log(error);
});
};
window.addEventListener('load', function() {
initApp()
});
</script>

Getting the ID when message is sent - Firebase & AngularFire

I have a messaging "app" and I need to get the ID when a message is created.
Here is all of the code below:
<html ng-app="sampleApp">
<body ng-controller="SampleCtrl">
<ul>
<li ng-repeat="message in messages">
<input ng-model="message.message" ng-change="messages.$save(message)" />
<input ng-model="message.by" ng-change="messages.$save(message)" />
<button ng-click="messages.$remove(message)">Delete Message</button>
</li>
</ul>
<form ng-submit="addMessage()">
<input ng-model="newMessageText" />
<input ng-model="newMessageBy" />
<button type="submit">Add Message</button>
</form>
<!-- Angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.6.6/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
<script>
var config = {
apiKey: "xxx",
authDomain: "xxx",
databaseURL: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx"
};
firebase.initializeApp(config);
var app = angular.module("sampleApp", ["firebase"]);
app.controller("SampleCtrl", function ($scope, $firebaseArray) {
var ref = firebase.database().ref().child("messages");
$scope.messages = $firebaseArray(ref);
$scope.addMessage = function () {
$scope.messages.$add({
message: $scope.newMessageText,
by: $scope.newMessageBy
});
};
});
</script>
</body>
</html>
When a message is sent, it creates a ID and the message content under it. So, I need to get the ID of the message sent, and write the ID to Firebase.
Here's what the database looks like:
{
"messages" : {
"-KrsHPUi7pIWTQ1qgO4q" : { // I NEED TO GET THIS
"message": "blah blah blah...",
"by": "john"
}
},
"ids" : {
"first": "-KrsHPUi7pIWTQ1qgO4q" // AND PUT IT HERE
}
here how you can get the id
$scope.messages.$add({
message: $scope.newMessageText,
by: $scope.newMessageBy
}).then(function(ref) {
var id = ref.key;
// do with the key what ever you want
})

Categories

Resources