btnsubmit.addEventListener('click', e => {
const task = txttask.value;
const description = txtdescription.value;
const date = txtdate.value;
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
console.log(firebaseUser.email)
firebase.database().ref('uid/' + firebaseUser.uid + '/reminders/' + date).set({
task: task,
description: description,
date: date,
});
alert('Data Has Been Recorded');
}
});
document.getElementById("input_form").reset();
so when I hit the submit button I get the alert but the data is not saved.
another example
if (firebaseUser) {
console.log(firebaseUser);
return window.location.href = 'index.html';
} else {
if (email == '' && pass == '') {
alert('Please Enter The Email and The Password!')
} else if (pass == '') {
alert('Please Enter The Password!')
} else if (email == '') {
alert('Please Enter The Email')
}
else {
if (firebaseUser) {
console.log(firebaseUser);
return window.location.href = 'index.html';
} else {
alert('Something went wrong')
}
}
console.log("not loged in");
}
});
Here the website shows the alert that something went wrong and when I clear it I'm logged in. I added extra if to again check if the user exists just in the case. but it still does that, so I'm confused as to what am I doing wrong in both scenarios.
Related
After a user sign in successfully, I want to use the User UID to verify the user has selected the right school, I have been able to achieve this task, but the problem is, I have to click the login button twice before an action takes effect.
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
//After signing in, use the user auth id to check if the user exist in the selected school
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
}
It is very unusual to have an onAuthStateChanged listener in a click handler like that. More likely you want something like:
...
} else {
toggleSignIn();
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
By the way: if you can look up the school for the user with a query, is there any specific reason why you don't simply prepopulate that value for them in the form?
Your code has a flaw. onAuthStateChanged listener is attached every time the button is clicked. This could add multiple listeners and the same code triggered multiple times after each repeated click. onAuthStateChanged listener should be attached only once when the document is loaded. Your code should be something like:
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
}
}
document.onload = function () {
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
I assume toggleSignIn() function is used to sign in and will change the firebase AuthState on successful sign in.
I want to validate my data with jQuery or Javascript and send them to the server but why aren't they validated?
$(document).ready(function() {
var name = $('#signup-name').val();
var email = $('#signup-email').val();
var password = $('#signup-password').val();
var email_regex = new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
var pass_regex = new RegExp(/^(?=.[0-9])(?=.[!##$%^&])[a-zA-Z0-9!##$%^&]{7,15}$/);
$('#signup-form').on('submit', function(e) {
e.preventDefault();
if (validate()) {
$.ajax({
type: 'post',
url: 'signup',
data: {
email: email,
password: password,
name: name
},
});
} else {
return false;
};
});
function validate() {
// name cheak here
if (name.length == "") {
$('.nameerror').html("Name field required !");
return false;
} else if (name.length = < 3) {
$('.nameerror').html("Name Should be greater than 3");
return false;
};
// email cheak here
if (email.length == "") {
$('.emailerror').html("Email field required !");
return false;
} else if (!email_regex.test(email)) {
$('.emailerror').html("Please enter correct email.");
return false;
};
// password cheak here
if (password.length == "") {
$('.passerror').html("password field required !");
return false;
} else if (!pass_regex.test(password)) {#
('.passerror').html("Minimum eight characters, at least one letter and one number:");
return false;
};
};
});
There are two major issues, you were just not passing the arguments to the validate function. I have updated your code with arguments passed to the function.
Furthermore, you never returned true for any function as a result nothing would be returned. Also your if statements are split and will contradict.
I have corrected these issues, hopefully this should work!
$(document).ready(function() {
$('#signup-form').on('submit', function(e) {
var name = $('#signup-name').val();
var email = $('#signup-email').val();
var password = $('#signup-password').val();
e.preventDefault();
if (validate(name, email, password)) {
$.ajax({
type: 'post',
url: 'signup',
data: {
email: email,
password: password,
name: name
},
});
} else {
return false;
};
});
});
function validate(name, email, password) {
var email_regex = new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
var pass_regex = new RegExp(/^(?=.[0-9])(?=.[!##$%^&])[a-zA-Z0-9!##$%^&]{7,15}$/);
// name cheak here
if (name.length == 0) {
$('.nameerror').html("Name field required !");
return false;
} else if (name.length <= 3) {
$('.nameerror').html("Name Should be greater than 3");
return false;
} else if (email.length == 0) { //Check Email
$('.emailerror').html("Email field required !");
return false;
} else if (!email_regex.test(email)) {
$('.emailerror').html("Please enter correct email.");
return false;
} else if (password.length == 0) { // password cheak here
$('.passerror').html("password field required !");
return false;
} else if (!pass_regex.test(password)) {
('.passerror').html("Minimum eight characters, at least one letter and one number:");
return false;
} else {
return true;
}
};
I believe the issue is that, although the validate function does indeed have access to the variables name etc, these are just set once when the document is first ready, and never updated. The values of the variables should be set inside the event handler for the submit event, before validate is called.
I'm working on a chat app with meteor that uses accounts-ui and accounts-twitter. I want to be able to ban people if they misuse the website but I'm not sure how to do this or if it is even possible. Is there a way to do this? Here is the code I use to run the chat app part of it:
ui.js:
// render all of our messages in the ui
Template.chatBox.helpers({
"messages": function() {
return chatCollection.find();
}
});
// get the value for handlerbar helper user
Template.chatMessage.helpers({
"user": function() {
if(this.userId == 'me') {
return this.userId;
} else if(this.userId) {
getUsername(this.userId);
return Session.get('user-' + this.userId);
} else {
return 'anonymous-' + this.subscriptionId;
}
}
});
// when Send Chat clicked at the message to the collection
Template.chatBox.events({
"click #send": function() {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
var message = $('#chat-message').val();
// check to see if the message has any characters in it
if (message.length < 1) {
alert("You must enter a message to post.");
return;
}
if (message.length > 200) {
alert("Your message is too long... they can't read that fast!");
return;
}
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//Validation
var bot =Check_bots();
if(bot==false)
{
//add the message to the stream
chatStream.emit('chat', message);
}
else
{
alert("Slow down! No need to post that fast.");
return false;
}
},
"keypress #chat-message": function(e) {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
if (e.which == 13) {
//Validation
var bot =Check_bots();
if(bot==false)
{
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
console.log("you pressed enter");
e.preventDefault();
//repeat function from #send click event here
var message = $('#chat-message').val();
// check to see if the message has any characters in it
if (message.length < 1) {
alert("You must enter a message to post.");
return;
}
if (message.length > 200) {
alert("Your message is too long... they can't read that fast!");
return;
}
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
else
{
alert("Slow down! No need to post that fast.");
return false;
}
}
}
});
chatStream.on('chat', function(message) {
chatCollection.insert({
userId: this.userId,
subscriptionId: this.subscriptionId,
message: message
});
});
var lastintime=0;
var defference=0;
var msg_count=0;
function Check_bots()
{
var seconds = new Date().getTime() / 1000;
seconds=parseInt(seconds);
if(lastintime < seconds)
{
defference = seconds -lastintime;
lastintime=seconds;
if(defference<=5 && msg_count>=3)
{
return true;
}
else
{
return false;
}
}
}
users.js:
Accounts.ui.config({
passwordSignupFields: "USERNAME_ONLY"
});
getUsername = function(id) {
Meteor.subscribe('user-info', id);
Deps.autorun(function() {
var user = Meteor.users.findOne(id);
if(user) {
Session.set('user-' + id, user.username);
}
});
}
Does anybody know a way to do this?
You could use Accounts.validateLoginAttempt
Server side code
Accounts.validateLoginAttempt(function(info) {
var user = info.user;
if(user.isBanned) throw new Meteor.Error(403, 'You are banned');
});
With the above code: If you added isBanned: true to any user in your MongoDB database, that user would not be able to sign in.
$(document).ready(function(){
logger();
});
function logger()
{
if(localStorage.getItem("status") === null)
{
$("#test").html("Not logged in.");
$("#buttonlogin").click(function(){
var ul = $("#userlogin").val();
var pl = $("#passlogin").val();
$.post("includes/logger.php", {type : "login", user : ul, pass : pl}, function(dlogin){
if(dlogin == 1)
{
$("#outlogin").html("Please enter a username.");
$("#userlogin").focus();
}
else if(dlogin == 2)
{
$("#outlogin").html("Please enter password.");
$("#passlogin").focus();
}
else if(dlogin == 3)
{
$("#outlogin").html("This username doesn't exist.");
$("#userlogin").focus();
}
else if(dlogin == 4)
{
$("#outlogin").html("This username and password don't match.");
$("#userlogin").focus();
}
else
{
localStorage.setItem("status", dlogin);
logger();
}
});
});
$("#buttonregister").click(function(){
var ur = $("#userregister").val();
var pr = $("#passregister").val();
var cpr = $("#confirmpassregister").val();
$.post("includes/logger.php", {type : "register", user : ur, pass : pr, cpass : cpr}, function(dregister){
if(dregister == 1)
{
$("#outregister").html("Please enter a username.");
$("#userregister").focus();
}
else if(dregister == 2)
{
$("#outregister").html("Please enter a password.");
$("#passregister").focus();
}
else if(deregister == 3)
{
$("#outregister").html("Please enter a confirm password.");
$("#cpassregister").focus();
}
else if(dregister == 4)
{
$("#outregister").html("Password and confirm password do not match.");
$("#passregister").focus();
}
else if(dregister == 5)
{
$("#outregister").html("This username is already taken.");
$("#userregister").focus();
}
else
{
localStorage.setItem("status", dregister);
logger();
}
});
});
}
else
{
$("#test").html("You are logged in.");
$("#buttonlogout").click(function(){
localStorage.removeItem("status");
logger();
});
}
}
The above code is meant to check whether or not a localStorage variable is in existence or not. If it is then only allow the log out button to be pressed. If is doesn't then let the two forms to work. Once it is done with either it is supposed to recheck if the variable is set and then do as I said above. However it ignores it when a user logs in and allows the forms to run. If you refresh however it works fine. I cannot for the life of me figure out why this is happening, and it is beginning to piss me off. Any help would be appreciated.
On your else statement, try adding:
$('#buttonlogin').unbind('click');
$('#buttonregister').unbind('click');
If I understand your problem correctly, what's happening is those events are registered when you first run $("#buttonlogin").click(function()....
It doesn't matter that you call logger() again and the if statement is false the second time around. If you want to disable these callbacks you have to do it explicitly.
I have a sign-up form which prompts for the first name, last name, username, password and e-mail address. I'm using two separate $.get() methods to check if the username and e-mail address are not existing.
This is my function:
function validateSignUp() {
var firstName = $("#first-name").val();
var lastName = $("#last-name").val();
var username = $("#username").val();
var password = $("#pass").val();
var email = $("#email").val();
var passwordVerifier = $("#retype-pass").val();
var emailVerifier = $("#retype-email").val();
errorMessage = "";
var isUsernameValid = validateUsername(username);
var isError = false;
// validate first name field
if (firstName == "" || lastName == "") {
isError = true;
$("#error-message").html("All fields are required");
}
// validate password
if (validatePassword(password) == false) {
isError = true;
$("#check-password").html("Password is invalid");
}
else {
$("#check-password").html("");
}
// validate password verifier
if (passwordVerifier == password) {
if (validatePassword(passwordVerifier) == false) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters");
}
else {
if (password != passwordVerifier) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters ");
}
else {
$("#recheck-password").html("");
}
}
}
else {
isError = true;
$("#recheck-password").html("Passwords didn't match");
}
// validate username field
if (isUsernameValid == false) {
isError = true;
$("#check-username").html("Alphanumeric characters only");
} // if
else if (isUsernameValid == true) {
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
} // else
// validate e-mail address field
if (validateEmail(email) == false) {
isError = true;
$("#check-email").html("Sorry, the e-mail you typed is invalid");
} // if
else if (validateEmail(email) == true) {
$.get("/account/checkavailabilitybyemail", { email: email },
function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
}
else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
});
}
if (isError == true) {
return false;
}
return true;
}
When other fields are blank and the username and/or e-mail address is existing, the form is not submitted. And the callback functions of the get methods are called as well. But when I'm going to submit my form with no empty fields, it is automatically submitted without checking the username and/or e-mail by $.get(). Is there anything wrong with my function or I'm not yet discovering something. Thanks.
You need to use a full ajax() call and set the async property to false. This makes your request synchronous, i.e. it forces the browser to wait until doing anything else. Try this:
$.ajax({
url: "/account/checkavailabilitybyemail",
data: { email: email },
async: false,
success: function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
} else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
})
});
if (isError == true) {
return false;
}
I suggest you leverage Jquery validate with two remote rules. It's quite easy to implement and a very mature plugin. This way you can focus on other aspects of your UX and not have to re implement this validation logic should you need to validate another form in your project.
Inside your main function, you cannot directly wait for the $.get() to return. But you can move the form submission to the success callback of the AJAX call (assuming form to contain a reference to the actual form element):
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
form.submit();
//--------------------------^
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
Note however, that then the form submission depends on the AJAX to return. Most useful would be a timeout (with window.setTimeout()) and a server-side validation, if the JS doesn't respond or the user has JS disabled.