I am trying to create a user login application using Phonegap.
here is my code
function successCB(tx) {
var setName = $("#name").val();
var setID = $("#ID").val();
//alert('select * from USER where name='+setID+' and password='+setName+'');
tx.executeSql('select * from USER where name='+setID+' and password='+setName+'', [], querySuccess, errorCB);
}
When I uncomment the alert, it shows the data enter from the text fields, however I cant figure out what to do next,
I want to check the inputs from the database and if user id and password are correct the flow should go to another page like a proper login page.
What is the appropriate way to do that in
function querySuccess(tx, results)
You need to verify that some rows got selected. If the typed in username and password was correct the sql sentense will return a row with that user.
Either you make a global variable called DB where you connection is stored. Then you chould do something like this.
var db = "";
db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
// collect your values as you already do.. i just showed em for demontration purpose..
var setName = $("#name").val();
var setID = $("#ID").val();
// execute this code from a function of your choice.
db.transaction(function(con) {
con.executeSql('select * from USER where name='+setID+' and password='+setName+'', [], function (tx, results) {
var len = results.rows.length;
if (len==1) {alert("you logged in with some user");}
});
});
Or with what you posted.
function querySuccess(tx, results) {
var len = results.rows.length;
if (len==1) {alert("you logged in with some user");}
}
So what you need to do after all this is to make sure that you can detect if you are logged in or not. Its not of much use if you have to log in every time u change page or what your app contains. You could use the localstorage to detect that.
You could also make a global variable to hold the value of loggedin or not.
:-)
I hope my code helped you.
Related
I have been trying to make a simple Register/Login system in JS. I tried to get the username/password values through user inputs and turn them into variables using a register() function. After that, however, these variables no longer hold any value, and I need them to compare with the new login username/password to check if they match in order to login.
Here's what I tried.
The function below attributes the user's input to the respective variables successfully. The ID's are from a text input in a HTML file.
function register () {
var user1 = window.document.getElementById('username')
var pass1 = window.document.getElementById('password')
alert('User registered, user your credentials to login')
}
When I click the 'register' button in the html page, the function is called (onclick="register()"), and I am redirected to the login page.
Here's the code for the login session:
function login () {
let userL = window.document.getElementById('usernameL')
let passL = window.document.getElementById('passwordL')
if (userL === user1 && passL === pass1) {
alert(`${userL} successfully logged`)
}
else {
alert('Invalid credentials')
}
It doesn't work because in the code above, user1 and pass1 are "not defined", according to the console. How do I keep the values of these variables stored after getting them in the first function(register) in order to use it when the second function(login) is used?
You can use Session storage to store temporary data
sessionStorage.setItem('username',username);
sessionStorage.setItem('password',password);
To retreive the data in login page
var user1 = sessionStorage.getItem('username',username);
var pass1 = sessionStorage.getItem('password',password);
then clear
sessionStorage.clear();
Please refer the below code,
<script>
const allUsers = [];
function register() {
// assuming user1 && pass1 are input elements with ids username, password
var user1 = document.getElementById("username").value;
var pass1 = document.getElementById("password").value;
// TODO: always validate the data that is taken as input from the user
// create an object containing user details
const newUser = {
username: user1,
password: pass1,
};
// push the registered user in allUsers array
allUsers.push(newUser);
alert("User registered, user your credentials to login");
}
function login() {
// assuming user1 && pass1 are input elements with ids usernameL, passwordL
let userL = document.getElementById("usernameL").value;
let passL = document.getElementById("passwordL").value;
// TODO: always validate the data that is taken as input from the user
// loop through allUsers array to check whether we already have a user registered with the details given in login form
for(let user of allUsers) {
if(user.username === userL && user.password === passL) {
alert(`${userL} successfully logged`);
return; // exit the function here
}
}
// if user detail not found in allUsers array this alert will be executed
alert("Invalid credentials");
}
</script>
Store all users in array after successful registration
While login, loop through the registered users array to check whether the user has already registered or not and decide how to handle the logic.
As PM 77-1 mentioned in the comment, please be aware that getElementById(ID) returns us the element itself (the tag itself), if we want to access it text content we can use either getElementById(ID).textContent or getElementById(ID).innerText
i've been working on an app(Node.js with MongoDB using mongoose), and the server connects to 2 different databases, 1 generic containing username and password pairs for user authentication. Then, when the user signs in, I want to connect to a different database, named after the user's userId. I managed to create a module for sharing the generic UA database, but it's more difficult with the second one, since it doesn't open with the connection, but later on, when the user signs in. I guess i got inspired by the idea of react context kind of sharing.
So far i've got something like this
const mongoose = require("mongoose");
/*
UA = User Authentication
US = User Specific
DB = DataBase
*/
const UA_DB = mongoose.createConnection(/*...*/);
);
const User = UA_DB.model("User", require("../../data-schemas/user"));
let US_DB, Order, Item, Ingredient, Place;
console.log("opened UA database");
function sendUserId(newUserId) {
userId = newUserId;
US_DB = mongoose.createConnection(/*... ${newUserId} ...*/ );
Order = US_DB.model("Order", require("../../data-schemas/order"));
Item = US_DB.model("Item", require("../../data-schemas/item"));
Ingredient = US_DB.model(
"Ingredient",
require("../../data-schemas/ingredient")
);
Place = US_DB.model("Place", require("../../data-schemas/place"));
console.log("opened US database");
}
module.exports = {
UA_DB: {
User,
},
US_DB: {
Order,
Item,
Ingredient,
Place,
},
sendUserId,
};
Now, if I hadn't made it clear, the first, UA_DB works just fine, the user signs in just fine... When it comes to the US_DB i always get undefined as values(Cannot read property 'find' of undefined). I suspect the problem could be, that the exported value doesn't update with the value of the variables. Any ideas, how this could be solved?
Well, i figured it out. Instead of using precise values I use a function to return them, and to connect to the database.UserId is stored in a token, so after verification i check whether i am already connected to the right database (with the userId variable, which stores previous values) and then return curretn values of the models now my code looks something like this
const mongoose = require("mongoose");
/*
UA = User Authentication
US = User Specific
DB = DataBase
*/
const UA_DB = mongoose.createConnection(/* ... */
);
const User = UA_DB.model("User", require("../../data-schemas/user"));
let US_DB,
Order,
Item,
Ingredient,
Place = "some default value";
console.log("opened UA database");
let userId = "";
function getUS_DBModels(newUserId) {
if (newUserId !== userId) {
userId = newUserId;
US_DB = mongoose.createConnection(`...${userId}...`
);
Order = US_DB.model("Order", require("../../data-schemas/order"));
Item = US_DB.model("Item", require("../../data-schemas/item"));
console.log("opened a US_DB connection");
Ingredient = US_DB.model(
"Ingredient",
require("../../data-schemas/ingredient")
);
Place = US_DB.model("Place", require("../../data-schemas/place"));
}
return {
Order, Item, Ingredient, Place
}
}
module.exports = {
UA_DB: {
User,
},
getUS_DBModels,
};
For anyone wondering, in different modules you can access the values like this
const dbHandler = require("./path/to/the/module");
const { Item } = dbHandler.getUS_DBModels("UserId");
Good morning;
I've started studying javascript for passion, and I'm really liking it! but I have a question on how to store values in an array. I tried to store 2 email addresses (through regular expression) and display the value stored every time, but I can only store one and the second prompt doesn't even run, can you help me? Thank youuu
var myRE = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var prompt = prompt("Your email addess");
if (myRE.test(prompt)) {
alert("It's OK");
var myArray = [prompt];
alert(myArray[0]);
var prompt1 = prompt("another one");
if (myRE.test(prompt1)) {
alert("It's OK");
myArray.push(prompt1);
alert(myArray[1]);
} else {
alert("Put a fckng mail man");
};
} else {
alert("Put a mail man");
}
The javascript reference to the native browser function prompt is being overwritten by this line:
var prompt = prompt("Your email addess");
(now prompt is equal to the value returned and not the function that displays a window for the user to type in.)
Simply rename your variable to avoid this:
var anyOtherName = prompt("Your email address");
Now, next time you use prompt it will still be the function that displays a window.
I'm developing a app which uses IndexedDB extensively. What I'm trying to do is save data of employees table and company table. Each employee belongs to a company and in employee object I've Company's ID and the objects of both of the entity will look like this.
Company's object:
{"id":1,"name":"ABC"}
Employee's object:
{"id":100,"name":"E1","company_id":1}
I'm saving company's details using auto-incremented key (called it appid), so my final object of company's look like this:
{"id":1,"name":"ABC","appid":1}
Where the appid will get auto-incremented as I insert records of company one by one. Now while inserting employee's object I want to find the localid(appid) of the company and save it in employee's object to make employee's object look like:
{"id":100,"name":"E1","company_id":1,"company_app_id":1}
I'm able to get the localid of the company by calling a method while saving employee's details, like:
var transaction = db.transaction(['employees'], 'readwrite');
var objStore = transaction.objectStore('employees');
var company_id=employeeobject.company_id;
companyDB.getCompanyById(company_id,function(companyObject){
transaction = db.transaction(['employees'], 'readwrite');
objStore = transaction.objectStore('employees');
// If I comment above two lines it throws me exception.
var request=objStore.put(employeeobject);
request.onsuccess = function (e) {
// using it for next insertion.
};
});
Problem with the above code is every time when I want to insert employee's data in table I need to reopen the trascation in callback function because if I don't open the transaction again it throws TransactionInactiveError.
I've searched for specific error on SO and found that Transaction get inactive as soon as it's no more used in current scope.
Above code work perfectly fine when I've couple of employee's objects.
But When I'm trying to execute the same code with ~1K of data it takes
(normal execution time x ~10).
By normal execution time I mean without fetching company's localid and saving employee's details directly.
So my question is, what is the best way I can insert the employee's data including company's localid with least execution time? Or Am I doing something wrong ?
It depends on how you're implementing companyDB.getCompanyById().
As presented, it's an asynchronous black box (maybe it's doing a network request?) And as you've discovered, Indexed DB transactions are only active (1) directly after creation and (2) in callbacks from requests made in that transaction, until "control returns to the event loop". Without further details, your best bet would be to batch the work - do the getCompanyById() lookups for N employees, then write those N records.
But from the description at the top "...data of employees table and company table..." maybe this is all within a single Indexed DB database, in which case just use a single transaction for everything:
var tx = db.transaction(['companies', 'employees'], 'readwrite');
employee_records.forEach(function(record) {
var company_id = record.company_id;
var req = tx.objectStore('companies').get(company_id);
req.onsuccess = function() {
var company = req.result;
record.company_app_id = company.app_id;
tx.objectStore('employees').put(record);
};
});
(I'm mangling your actual data/logic here, this is just to illustrate)
Hmm, maybe something like this helps?
function addCompany(db, company, callback) {
var tx = db.transaction('companies', 'readwrite');
var store = tx.objectStore('companies');
var request = store.add(company);
request.onsuccess = callback;
}
function addEmployee(db, employee, callback) {
var tx = db.transaction('employees', 'readwrite');
var store = tx.objectStore('employees');
var request = store.add(employee);
request.onsuccess = callback;
}
function addCompanyThenEmployee(db, company, employee, callback) {
addCompany(db, company, onAddCompany);
function onAddCompany(event) {
var newAppId = event.target.result;
employee.company_app_id = newAppId;
addEmployee(db, employee, callback);
}
}
var company = {'id': 1, 'name': 'xyz'};
var employee = {'id': 1, 'name': 'xyz'};
var request = indexedDB.open(...);
request.onsuccess = function(event) {
var db = event.target.result;
addCompanyThenEmployee(db, company, employee, onAddCompanyThenEmployee.bind(null, company, employee));
};
function onAddCompanyThenEmployee(company, employee, event) {
console.log('Added company', company, 'and employee', employee);
};
I'm still struggling to understand how to access Meteor.users as a foreign key from another collection query. I understand that only the current user is published by default so I have a publication on the server as
Meteor.publish('itemOwner', function(userId) {
check(userId, String);
var user = Meteor.users.find({id: userId});
return user;
// return Meteor.users.find({id: userId}, {
// fields: {'profile': 1} });
});
I then have a Deps.autorun on the client..
Deps.autorun(function () {
var itemOwnerId = Session.get("itemOwnerID");
if (itemOwnerId) {
debugger
var ID = Session.get("itemOwnerID");
Meteor.subscribe('itemOwner', Session.get("itemOwnerID"));
}
});
I set the session ID on a modal form load, and display it in the template by calling the ownerProfile helper (or try to)
Template.showQuoteModalInner.helpers({
getQuote: function () {
// Get the quote ID from the session var
var quote = Session.get("quoteID");
if(quote) {
debugger;
var ID = quote.user._id;
Session.set("itemOwnerID", quote.user._id);
return quote;
}
},
ownerProfile: function() {
debugger;
var quote = Session.get("quoteID");
if(quote) {
var ID = quote.user._id;
var theUser = Meteor.users.find({_id: quote.user._id});
return theUser;
};
}
});
Now, I can trace the user ID at each stage and see it getting correctly passed to the autorun and the helpers. If I stop the program at the debugger in the ownerProfile helper and in the console put in Meteor.user.fetch({_id: "the id here"}).fetch() I get the correct user back.. but, in the handler itself the Meteor.users.find returns null??? What am I missing?
Two possibilities I noticed.
First, you are missing an underscore in the find in your publish function.
.find({id: userId}) should be .find({_id: userId}).
But this probably isn't the issue if you are seeing the user (other than the logged in user) in the console.
Second, if you are not seeing the user from your Template.showQuoteModalInner.ownerProfile helper, it is probably because you are returning a find() instead of a findOne().
find() returns a cursor whereas findOne() returns the record. Try findOne() if you want to display that single user's attributes.