so i wrote this code and I am getting no errors in the console
the only error i get from the fauna server is An error occurred while logging in.
also i will change the secret key after this is awnsered for security reasons.
const client = new faunadb.Client({
secret: "fnAE7vAmHdAA1I7LvovMRWnGVVM2_sit_IrKDgnN"
});
async function signUp() {
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
try {
const result = await client.query(
q.Create(
q.Collection("users"),
{
data: {
email,
password
}
}
)
);
alert("Sign up successful! You can now log in.");
} catch (error) {
console.error(error);
alert("An error occurred while signing up.");
}
}
async function login() {
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
try {
const result = await client.query(
q.Get(
q.Match(
q.Index("users_by_email"),
email
)
)
);
if (result.password === password) {
alert("Login successful!");
} else {
alert("Incorrect email or password.");
}
} catch (error) {
console.error(error);
alert("An error occurred while logging in.");
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/faunadb"></script>
<script></script>
</head>
<body>
<h1>Sign Up</h1>
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" required>
<br><br>
<button type="button" onclick="signUp()">Sign Up</button>
</form>
<h1>Login</h1>
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" required>
<br><br>
<button type="button" onclick="login()">Login</button>
</form>
</body>
</html>
I've tried looking for errors in thr java script and tried playing around
with the fauna database itself
IMPORTANT
note about credentials in Fauna: using Fauna's built in Credentials support means you don't store the actual password, only the hashed password. This is also what enables Fauna's built in Login function, which returns a new user Token. Your current application provides all users with permissions to read every user, including every user's password, and that is very, very bad.
Your errors
I see that you are trying to access the password field by doing result.password. Notice that when you created the document, password is under the data field.
if (result.data.password === password) {
alert("Login successful!");
} else {
alert("Incorrect email or password.");
}
A better way
You should follow along with the User Authentication Tutorial.
It is my recommendation that you turn signup and login into UDFs and use a public key that has two permissions (and only two permissions):
call Function("signup")
call Function("login")
Then your application can use the public key to access these functions. The login function then gives you a separate Token, which you use to make a new Fauna Client. That Token should have whatever privileges a user should have (but no more).
Fauna Community Resources
Forums: https://forums.fauna.com/
Discord: https://discord.gg/2qXynEjn
Related
i'm working on my very first app : a login/register form with JS/node Js/ Mysql.
I'm trying to connect my form to my database (to collect my users' data into my db) but my code is not working. I didn't use "handleChange" or "onSubmit" functions because i don't use ReactJS framework. Do you guy think it's necessary?
this is my code :
HTML code:
<div class="msg-alerte">message</div>
<form method="post" action="http://localhost:8000/">
<div class="formulaire">
<h1 class="entete">inscription</h1>
<input type="name" placeholder="nom" name="nom" id="nom" autocomplete="off" required>
<input type="email" placeholder="email" name="email" id="email" autocomplete="off" required>
<input type="password" placeholder="mot de passe" name="password" id="password" autocomplete="off" required>
<button class="btn-valider">s'inscrire</button>
Vous avez déjà un compte? Se connecter
</div>
</form>
JS (frontend) :
const username = document.getElementById('name')|| null;
const email = document.getElementById('email');
const password = document.getElementById('password');
const submitBtn = document.querySelector('.btn-valider');
if(username === 0){
}
else{
submitBtn.addEventListener('click', ()=>{
//register-user??
fetch('/', {
method: "post",
headers: new Headers({'Content-Type':'application/json'}),
body: JSON.stringify({
user_name: username,
email: email,
password: password
})
})
console.log(username);
console.log(email);
console.log(password)
.then(res =>res.json())
})
}
js server :
app.post("/",(req,resp)=>{
//insertion d'une donnée
const data={user_name:req.body.user_name,email:req.body.email, password:req.body.password};
let sql="INSERT INTO users (user_name, email, password) VALUES (?,?, ?);";
pool.query(sql,[data],(err,fields)=>{
if(err)console.log("Echec d'enregistrement à BD");
else{
console.log("Enregistrement effectuee");
resp.redirect("/");
}
});
});
THANK YOU FOR YOUR HELP!!!
It looks like the main issue you will want to resolve before you can move forward is with your fetch call in your frontend code. You need to use the then() method on fetch so you can properly parse and read the response. Currently, you are calling .then(res =>res.json()) on a console.log(). This is not valid.
I have made a modification to your event listener function that you can try
submitBtn.addEventListener('click', () => {
fetch('/', {
method: "post",
headers: new Headers({'Content-Type':'application/json'}),
body: JSON.stringify({
user_name: username,
email: email,
password: password
})
})
.then((res) => res.json())
.then((data) => {
// now we can read the response and decide what to do next
console.log(data);
});
})
I'm also seeing some possible syntactical issues in your node js code. Specifically with the request data assignment and the string interpolation on your query string. You could try something like this:
app.post("/", (req, resp) => {
//insertion d'une donnée
const data =[req.body.user_name, req.body.email, req.body.password];
let sql="INSERT INTO users (user_name, email, password) VALUES ($1, $2, $3)";
pool.query(sql, data, (err, fields) => {
if (err) console.log("Echec d'enregistrement à BD");
else {
console.log("Enregistrement effectuee");
resp.redirect("/");
}
});
});
Please comment if you need any further clarification.
I'm creating a dashboard using vanilla HTML, CSS and JS, with Firebase as my backend. In my signup.html page, I have a form that allows users to input their name along with their email address and password. Upon signup, users are redirected to dashboard.html with their personalized content. Inside the dashboard, it has a spot where it displays their name.
The problem is it is not always getting the name from the form, and if it doesn't get the user's name from the signup form then it just doesn't have their name as I don't have a "add name" function in the dashboard. I suspect this is because of the way I use the onAuthStateChanged() inside signup.html.
The following is my signup page JS code:
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
window.location.replace('dashboard.html')
} else {
return
}
});
document.querySelector('#signup_btn').addEventListener("click", (e) => {
e.preventDefault();
var user_email = document.getElementById('user_email').value;
var user_pass = document.getElementById('user_pass').value;
var user_name = document.getElementById('user_name').value;
// Sign Up
firebase.auth().createUserWithEmailAndPassword(user_email, user_pass)
// Success
.then((userCredentials) => {
userCredentials.user.updateProfile({
displayName: user_name
})
})
// Errors
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
})
If it helps, here is the form from my signup.html page:
<form>
<h1>Sign Up</h1>
<!-- <h2>Log into your account using your email address</h2> -->
<label for="user_name">Name</label>
<input type="text" name="name" id="user_name">
<label for="user_email">Email Address</label>
<input type="text" name="email" id="user_email">
<label for="user_pass">Password</label>
<input type="password" name="Password" id="user_pass">
<button type="submit" id="signup_btn">Sign Up</button>
<p>Already have an account? Log In</p>
</form>
It seems like your onAuthStateChanged listener is being triggered before the write to the database has completed. This is the expected behavior for the API, but not what you want here.
Since you do want to use the onAuthStateChanged listener to navigate on page reload, the best I can think off is to turn off the listener when the user clicks the sign up button:
// 👇 store the unsubscribe function in a variable
var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
if (user) {
window.location.replace('dashboard.html')
} else {
return
}
});
document.querySelector('#signup_btn').addEventListener("click", (e) => {
e.preventDefault();
unsubscribe(); // 👈 turn off auth state listener
var user_email = document.getElementById('user_email').value;
var user_pass = document.getElementById('user_pass').value;
var user_name = document.getElementById('user_name').value;
// Sign Up
firebase.auth().createUserWithEmailAndPassword(user_email, user_pass)
// Success
.then((userCredentials) => {
return userCredentials.user.updateProfile({ // 👈 add a return
displayName: user_name
})
})
.then(() => {
window.location.replace('dashboard.html') // 👈 explicitly navigate here
})
As mentioned in the documentation,
onAuthStateChanged adds an observer for changes to the user's sign-in state.
When the user is logged in, it redirects your user to /dashboard before the updateProfile is resolved resulting in termination of that request.
I don't think you'll need an auth state listener on login page so try refactoring the code like this:
window.onload = function () {
if (firebase.auth().currentUser) window.location.replace("dashboard.html")
// Else stay on this page
// button click events here
}
If I have some HTML code:
<div>
<input type="text" name="user" placeholder="User Name" />
<input type="password" name="password" placeholder="Password" />
<button type="button">Login</button>
</div>
and when I click on the login button, it goes to the /api/users/ function in my nodejs file. How do I pass the strings stored in the username and password in the HTML code? Using sqlite3.
app.get('/api/users/', function (req, res) {
let sql = 'SELECT * FROM users;';
db.all(sql, [], (err, rows) => {
var result = {};
result["users"] = [];
if (err) {
result["error"] = err.message;
}else {
rows.forEach((row) => {
result["users"].push(row);
});
}
res.json(result);
});
});
I want to execute some type of function, where if the username and password does not exist, than add it to the table "users" and redirect to another HTML file.
You should use a html form. See here. You're HTML is just sending an empty get request to your API, a form will send the data as well.
I am implementing a logic of forgot password using AWS Cognito. I am so far successful in changing the password using Prompts as given in the documentation. Here is the code
var username = document.getElementById('reset-pass').value;
var data = {
UserPoolId: _config.cognito.userPoolId,
ClientId: _config.cognito.clientId
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
// setup cognitoUser first
var cognitoUser = new AmazonCognitoIdentity.CognitoUser({
Username: username,
Pool: userPool
});
cognitoUser.forgotPassword({
onSuccess: function (result) {
console.log('call result: ' + result);
},
onFailure: function(err) {
alert(err);
},
inputVerificationCode() {
var verificationCode = prompt('Please input verification code ' ,'');
var newPassword = prompt('Enter new password ' ,'');
cognitoUser.confirmPassword(verificationCode, newPassword, this);
}
});
My question is instead of using prompts, how can I confirm the user on next page. Example On the first page a user enter the email and mail is sent using the forgotPassword(). Now user is redirected to a new page. There i wanted to enter the code as well as the new password and call the cognitoUser.confirmPassword method.
What i tried is to create a delay interval and after entering the details it would trigger clear interval on button press.
function resetPassword() {
var username = document.getElementById('reset-pass').value;
var data = {
UserPoolId: _config.cognito.userPoolId,
ClientId: _config.cognito.clientId
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
// setup cognitoUser first
var cognitoUser = new AmazonCognitoIdentity.CognitoUser({
Username: username,
Pool: userPool
});
// call forgotPassword on cognitoUser
cognitoUser.forgotPassword({
onSuccess: function (result) {
alert("Mail Sent")
},
onFailure: function (err) {
console.log(err)
},
inputVerificationCode()
{
window.myVar = setInterval(function(){
console.log('check');
}, 10000);
var verificationCode = document.getElementById('code').value;
var newPassword = document.getElementById('fpass').value;
cognitoUser.confirmPassword(verificationCode, newPassword, this);
}
});
}
The HTML Part Of the code-
<div class="change">
<form>
<label>Enter Email ID</label>
<input type="email" id="reset-pass" required />
<br />
<div class="">Next</div>
</form>
</div>
div class="change-confirm">
<form>
<label>Enter Code</label>
<input type="number" id="code" required />
<br />
<label>Enter New Password</label>
<input type="password" id="fpass" required />
<br />
<div class=""> Reset</div>
</form>
</div>
But the above code never executed. Instead it stops execution after some time.
So my question is is there any way to delay the function call of cognitoUser.confirmPassword method? I do not want to use prompts instead get the email and code in a text field after mail is sent.
A little late to the party, but it can help someone else.
You can pass the congitoUser you have created to the state, and then use cognitoUser.confirmPassword(...) by retrieving the cognitoUser object from the state.
You should consider using the aws-amplify-react which provides a withAuthenticator higher-order component that provides a login flow with forgot password, mfa, etc. And it's maintained by a team of devs who work for AWS.
https://aws-amplify.github.io/docs/js/react#add-auth
I've been struggling to get Firebase Auth to work for my website. I'm using a local server to run the HTML code.
Firebase is signing up users successfully (they show up in my Firebase console), but it's not signing them in.
I am using this code to check if user is signed in. It always shows "User is not signed in."
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log(user);
console.log('User is signed in');
} else {
console.log(user);
console.log('User is not signed in');
}
});
I've gone through the documentation and watched the Firecast videos as well as some other tutorials.
My HTML code:
<div class="login w3-display-middle">
<form class="login-container">
<p><input type="text" placeholder="Email" id="email"></p>
<p><input type="password" placeholder="Password" id="password"></p>
<p><button class="w3-blue" id="signin" style="width:100%">LOG IN </button></p>
<p><button class="w3-blue" id="signup" style="width:100%">SIGN UP </button></p>
<p><button class="w3-red" id="signout" style="width:100%">SIGN OUT </button></p>
</form>
</div>
Javascript (included right below the HTML code, before the body tag is closed:
<script src="https://www.gstatic.com/firebasejs/4.5.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: <I have included my apiKey>,
authDomain: <I have included my authDomain>,
databaseURL: <Included my database URL>,
projectId: <Used my project ID>,
storageBucket: <Used this as well>,
messagingSenderId: <And this too>
};
firebase.initializeApp(config);
</script>
<script>
const txtEmail = document.getElementById("email");
const txtPassword = document.getElementById("password");
signin.addEventListener('click', e => {
//Get email and password
const email = txtEmail.value;
const pass = txtPassword.value;
console.log(txtEmail.value);//Shows correct value
console.log(txtPassword.value);//Shows correct value
const promise = firebase.auth().signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
signup.addEventListener('click', e => {
//Get email and password
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
auth.createUserWithEmailAndPassword(email,pass)
.catch(function(error){
console.log(error.code);
console.log(error.message);
});
});
signout.addEventListener('click',e=> {
firebase.auth().signOut().then(function() {
// Sign-out successful.
})
.catch(function(error) {
console.log(error.code);
console.log(error.message);
});
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log(user);
console.log('User is signed in');
} else {
console.log(user);
console.log('User is not signed in');
}
});
</script>
Really need help figuring this one out. I've spent like 4 hours on it now. Also, when I initially signup the user, it also signs them in (shows up in the Firebase console!). It's just so weird.