I've been trying to add simple email / password signup/login for Firebase to the Polymer Starter Kit app. It comes stock with a Google auth sign in via a single button but there doesn't seem to be any instructions on how to set-up email/password register/login instead.
Here is the specific part of the code from the project's todo-auth.html file I've been struggling with:
<firebase-auth id="authenticate"
user="{{user}}"
location="{{location}}"
ref="{{refauth}}"
provider="">
</firebase-auth>
<paper-dialog modal
opened="[[!user]]"
entry-animation="scale-up-animation"
exit-animation="fade-out-animation">
<h2>Please sign in</h2>
<div>
<!-- Inputs I added to accept user credentials -->
<paper-input id="loginEmailInput"
no-label-float
label="Email"
on-keydown="">
</paper-input>
<paper-input id="loginPasswordInput"
no-label-float
label="Password"
on-keydown="">
</paper-input>
<paper-button on-tap="logIn">Login</paper-button>
<!-- Original Google sign-in code -->
<!-- <div class="google-sign-in"
tabindex="0"
on-tap="signIn">
<span class="google-sign-in-icon"></span>
<span class="google-sign-in-label">Google</span>
</div> -->
</div>
</paper-dialog>
I removed google from the provider property of the <firebase-auth> element and added a couple of input fields but don't really know where to go from there.
Here is the Polymer script part of todo-auth.html
<script>
Polymer({
is: 'todo-auth',
properties: {
user: {
notify: true
}
},
logIn: function() {
this.$.authenticate.login();
},
signOut: function() {
this.$.authenticate.logout();
this.user = null;
}
});
</script>
I've tried to find examples or guide tutorials on how to implement this but everything I've found has used the google based auth as login. Likewise, all other questions I've found here on SO have focused on google login.
I'd be grateful for any directions or pointers or tutorials on how to set it up. Thanks all in advance!
UPDATE
I managed to implement a new page with a form using the demo from the Google Web Components github repo.
I have a my-firebase.html file that imports everything I can think of to make it work. Imports look like this:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../../bower_components/polymerfire/firebase-app.html">
<link rel="import" href="../../bower_components/polymerfire/polymerfire.html">
I have also added the following for firebase-app and firebase-auth:
<firebase-app auth-domain="my-polymer-app.firebaseapp.com"
database-url="https://my-polymer-app.firebaseio.com/"
api-key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
</firebase-app>
<firebase-auth id="firebaseLogin" user="{{user}}" status-known="{{statusKnown}}" location="my-polymer-app.firebaseapp.com" provider="{{provider}}" on-error="errorHandler" on-user-created="userSuccessHandler" on-password-changed="us erSuccessHandler" on-password-reset="userSuccessHandler" on-user-removed="userSuccessHandler"></firebase-auth>
I am now getting the following error when I try to login(I have already set up a user in my Firebase App to test):
my-firebase.html:122 Uncaught TypeError: this.$.firebaseLogin.login is not a function
Which refers to this part of the code take from the Google Web Components repo.
login: function() {
var params;
try {
params = JSON.parse(this.params);
} catch (e) {
params = null;
}
if (this.provider == 'password') {
params = params || {};
params.email = this.email;
params.password = this.password;
}
this.$.firebaseLogin.login(params);
}
There are also red boxes around every instance of firebaseLogin on the page. No other errors are showing up so not sure what this means exactly. Again, I'd be grateful if anyone could point out what I'm missing here.
Use signInWithEmailAndPassword function instead of login function,
this.$.firebaseLogin.signInWithEmailAndPassword(username, password);
Related
I'm new to angular so please be kind. I have been struggling to figure out how to connect the google signin callback button to my angular component. I'm trying to receive the OAuth token on the client-side in order to send to my back-end but I am unable to get a hold of the response inside my angular component. The obstacle I'm encountering is the inability to have the google button call my angular component function.
Based on the latest google signin api in order to add a google OAuth button via html you need to do the following. I attempted to do this via their javascript library but wasn't successful.
<html>
<body>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script>
function handleCredentialResponse(e) {
//e.credential contains the JWT token
}
</script>
<div id="g_id_onload"
data-client_id="YOUR_CLIENT_ID"
data-callback="handleCredentialResponse">
</div>
<div class="g_id_signin" data-type="standard"></div>
</body>
</html>
I wanted to encapsulate this into a component and get that function called in my component.ts file. So I did the following with onGoogleSignin being a component function.
<script src="https://accounts.google.com/gsi/client"></script>
<div id="g_id_onload"
[attr.data-client_id]="google_login_id"
[attr.data-callback]="onGoogleSignIn">
</div>
<div class="g_id_signin"
[attr.data-text]="buttonTxt"
[attr.data-theme]="theme"
></div>
The project compiles and runs but when I run it I get the following issue in the console
[GSI_LOGGER]: The value of 'callback' is not a function. Configuration ignored.
The properties bind no problem but it's the function that doesn't work. So the only hack I have come up with is to put the following in the index.html file
<script>
function onGoogleSignIn(e) {
console.log(e);
window.authRef.zone.run(() => { window.authRef.googleSigninFunction(e); });
}
</script>
Modifying the component.html to not bind to the component function like below:
<div id="g_id_onload"
[attr.data-client_id]="google_login_id"
data-callback="onGoogleSignIn">
</div>
And then put the following into the constructor of my component:
constructor(
private ngZone: NgZone) {
window['authRef'] = { component: this, zone: this.ngZone,
googleSigninFunction: (e:any) => this.onGoogleSignin(e), };
}
All of this works but it requires to have a dependency on my component to be outside of my component which is not good practice. I know this is simply because I lack some basic understanding of angular.
Any help would be greatly appreciated
UPDATE:
I did add code on OnInit to inject the code into the DOM programmatically so that it will exist when google needs to bind to it. This allows me to not have to manually add the code into index.html but I'm sure there is a more elegant way to do this.
I'm trying to implement firebase on a Kirby website (a CMS run on PHP) so visitors can mark subpages to show up as links on the landing page.
To do this, I've constructed a form where a user adds their name when on the subpage to highlight it. The form doesn't submit when the button is clicked, but instead uses JS to add a document to Firebase (where it can be approved or deleted).
I'd like to prevent abuse and am interested in adding Recaptcha as a step when the visitor "submits" the page.
A simplified version of my code looks like this.
HTML:
<form id="add-item" action="?" method="POST">
<label for="f-name">Submitted by:</label>
<input type="text" id="f-name" name="f-name" placeholder="your name">
<button type="submit">Submit</button>
</form>
JS:
document.querySelector("#add").addEventListener("click", function(e){
const fName = document.querySelector('#f-name').value;
tableRef.get().then(function(querySnapshot) {
var uid = Date.now().toString(36) + Math.random().toString(36).substr(2);
if(fName === true){
tableRef.doc('item-'+uid).set({
contributor: fName,
})
}
});
e.preventDefault();
return false;
})
I've found answers to enable Recaptcha with Firebase that use Firebase hosting, or as a method for sign in:
Using recaptcha with Firebase
How to use it with Angular or React:
Google/Firebase reCaptcha not working with angular
Firebase: Invisible reCaptcha does not work in React JS
I am wondering how this can be done using just HTML (no app framework), or with PHP, and without a login?
I am very amateur web developer, so really appreciate any insights on this! I apologize in advance if this is an obvious question. Thank you!
here’s the code how you can add recaptcha but I’ll suggest you to use Php in the backend to verify the status :
First add this in head tag
<script src='https://www.google.com/recaptcha/api.js'></script>
Then add the site key and block for error message
<div class="g-recaptcha" id="rcaptcha" data-sitekey="site key"></div>
<span id="captchaStatus" style="color:red" /></span>
Then add script tag :
<script>
function checkCaptcha(form)
{
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captchaStatus').innerHTML="Captcha code is empty";
return false;
}
else
{
document.getElementById('captchaStatus').innerHTML="Captcha completed";
return true;
}
}
</script>
My goal for the project portion is to be able to have a functioning login and register page using TypeScript.
Currently my code works without a database, but I wanted to use Firebase to register user's usernames and passwords, so they can login with ease.
The only tutorial I have found only use Firebase with Angular or React, and I was wondering if there was a way to use Firebase storage without it?
The IDE I am using is Intellij.
if needed here is my registering page code:
.ts code:
class RegisterTs{
username: string;
password: string;
password2:string;
constructor(username: string, password: string, password2:string ) {
this.username = username;
this.password = password;
this.password2 = password2;
let registerBtn = document.getElementById("enterR")
registerBtn.addEventListener("click", (e: Event) => {
return RegisterTs.validateInput(this.password,this.password2)
});
let forgotBtn= document.getElementById("forgotPass")
forgotBtn.addEventListener("click",(e:Event) =>RegisterTs.forgotPasswordR());
}
private static validateInput(password: string, password2:string) {
if(password==password2){
return alert("success")
}
else{
return alert("Password inputs do not match")
}
}
private static forgotPasswordR() {
return alert("tough luck lmao")
}
}
window.onload= function() {
let iUser =(document.getElementById("re") as HTMLInputElement).value;
let iPass =(document.getElementById("rp") as HTMLInputElement).value;
let iPass2 =(document.getElementById("rrp") as HTMLInputElement).value;
let regTs = new RegisterTs(iUser,iPass,iPass2);
}
.html code
<HTML>
<HEAD>
<TITLE>Capstone Typescript Login</TITLE>
</HEAD>
<BODY>
<header>
<h2>Billy Bronco's Grading Calculator</h2>
</header>
<div id="container">
<div id="tabs">
<p id="rt" class="tabs" >Register</p>
<link rel="stylesheet" href="Login.css">
<div id="clear"></div>
</div>
<div id="cont">
<div id="register" class="comm">
<h3>Register</h3>
<input id="re" type="email" placeholder="Email" required/>
<input id="rp" type="password" placeholder="Password" required/>
<input id="rrp" type="password" placeholder="Re write Password" required/>
<input type="button" class="button" id="enterR" value="Register">
<input type="button" class="button" id="forgotPass" value="Forgot Password?">
<a href="login_view.html" > Already have an account? CLICK HERE </a>
</div>
</div>
</div>
<script src="RegisterTs.js"></script>
</BODY>
</HTML>
Thank You!
You should use Firebase Authentication. you shouldn't use firebase storage as its designed to store larger files than strings like files such as a word document or a video file etc.
Firebase comes with authentication system of its own which allows you to authenticate a user without needing to match password and username individually, like you are doing, that is considered worst practice as it exposes the actual password and username. That is why storing the password/username inside Firebase Realtime Database or Firestore is also a bad idea.
There is no requirement to use React or angular to use Firebase Auth. you can simple do all the js steps said in the tutorial and you will have yourself a working authentication platform. Since you know typescript, using and reading normal javascript shouldn't be a problem.
Follow this guide from Firebase here to understand how to add a user authentication system using email and password. You will not need most of the code you have written above.
I'm running a nuxtjs application in production and it's causing some VueJS functionality to break, particular with DOM events. However, development mode works just fine as it should flawlessly, though it is slower than production mode due to the code not being minified and compiled and all that.
#click events do not fire their functionality
.prevent does not prevent anything
Here's my source of an example section that does not work.
The #click event calls that change the view do not do anything.
Upon hitting enter to fire v-on:keydown.enter="login" it does not get prevented and the form gets submitted as a GET request to the same page ( the URL shows the GET ?variables )
After looking at the HTML code in the browser to see if there's any logged warnings or errors, there's nothing and nothing on the server side logs.
Plus, the <button> tags that have the #click to fire the login or signup methods do not have any events on them, basically not doing anything; just HTML.
On my production server after running nuxt build by executing npm run build, there are no errors or warnings.
<template>
<div class='card'>
<div class='tabs 2-col'>
<span :class="{active : view != 'signup'}" #click="view = 'login'">
Login
</span>
<span :class="{active : view == 'signup'}" #click="view = 'signup'">
Sign Up
</span>
</div>
<div class='card-body'>
<form v-show="view == 'login'" v-on:keydown.enter="login" novalidate>
<!-- my other html -->
<button #click.prevent="login">Login</button>
</form>
<form v-show="view == 'signup'" v-on:keydown.enter="signup" novalidate>
<!-- my other html -->
<button #click.prevent="signup">Sign Up</button>
</form>
</div>
</div>
</template>
<script>
export default {
data : function(){
return { view : 'login'};
},
methods : {
login: function(){
// my functionality
},
signup:function(){
// my functionality
},
}
}
</script>
Thank you for any help! I've been banging my head for hours.
data proprerty should be a function that return the object. try to do this:
data: function () {
return {
view: 'login',
}
}
I want to implement Google login in my site like is done in
Stack Exchange, Stack Overflow and more.
Meaning that when the user choose Login using Google authentication, the site redirects to a page where he can choose which Google account to use and without opening a new window/tab and redirect to the site
Can you help me with links/documentation how to do it
Very important not to open new tab/window.
I'm using this: https://developers.google.com/identity/sign-in/web/build-button
You can see that when you click on the button a new window is open, I wand to prevent this.
Thanks in advance
You could try to switch to the JavaScript client authentication and pass the ux_mode option to the signIn() function options.
ux_mode: "redirect"
Documentation here:
https://developers.google.com/identity/sign-in/web/reference#googleauthsigninoptions
Then you can get the user profile like so:
let googleUser = window.gapi.auth2.getAuthInstance().currentUser.get();
if (googleUser) {
let profile = googleUser.getBasicProfile();
if (profile) {
this.state.google.firstname = profile.getGivenName();
this.state.google.lastname = profile.getFamilyName();
this.state.google.email = profile.getEmail();
}
}
This is all documented here and there:
https://developers.google.com/identity/sign-in/web/people
Just add data-ux_mode="redirect" to the sign-in div from the Google's example (or to the .render call if you're rendering the login-button programmatically)
<div class="g-signin2" data-onsuccess="onSignIn" data-ux_mode="redirect"></div>
GAPI is now being discontinued, and Google is transitioning to Google Identity Services (GIS). The new method is similar to that which was suggested by #AlexfromJitbit, with some small modifications:
<html>
<body>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="YOUR_CLIENT_ID"
data-ux_mode="redirect"
data-login_uri="https://www.example.com/your_login_endpoint">
</div>
<div class="g_id_signin" data-type="standard"></div>
</body>
</html>
This code is pulled from the new GIS example, and is recommended for all new applications as the old API will be retired as of 31 March 2023.