accessing a node moudule from javascript file using jquery - javascript

i am building a web site using nodejs/javascipt/jquery/html/css and mysql.
lets say i have an html login page that has receives an input from the user (name && psw)
and i have a file:
login.js:
var node = reuqire('some module');
$(document).ready(function() {
var username = $('#name');
var password = $('#password');
$('#login_button').click(function(){ login(username.val(),password.val())});
});
without the require it works fine.(i also tried to move the require into the ready function)
for some reason it does not let me use another module.
any help?
thank you :)

Calling server-side functions in a client-side file like that is not possible. However, looking at your comment I suggest the NowJS library.
NowJS does not allow you to mix client-side/server-side JavaScript in one file (because that just does not make sense, and if it did it would be a high security risk). But it does allow you to define a function server-side (which will e.g. check credentials), which you can call client-side with no additional hassle. When that server-side function is done you can send a client-side function with the result (i.e. correct/wrong credentials). That way you can achieve what you want rather easily.
If you've read the basic tutorials, you could implement it like this (partly pseudocode since I don't know how you're checking login details etc.):
At the server-side:
everyone.now.checkLogin = function(username, password, callback) {
db.query("...", function(results) {
if(results.correct) {
callback(true);
} else {
callback(false);
}
});
};
At the client-side:
$("#login_button").click(function() {
var username = $("#username").val(),
password = $("#password").val();
now.checkLogin(username, password, function(correct) {
if(correct) {
$("#correct_message").show();
} else {
$("#wrong_message").show();
}
});
});

Related

Get variable from client-side JavaScript file in Express

I am trying to send a variable from my client-side JavaScript file to my server-side app.js file. I know that you can get a value from something like a form input field using methods such as the one below (using Express):
var express = require('express');
var app = express();
var path = require('path');
let cityResponse;
app.post('/city', function(req,res) {
cityResponse = {
user_name: req.body.userName
}
res.sendFile(path.join(__dirname, '/client/city/index.html'));
});
But I would like to get a value not directly from the HTML, but from the JavaScript file that the HTML is attached to.
As well as this, I am currently using Socket.io to send the data from the server to the client, and vice versa, using a window.onload to let the server know when the page is ready:
index.js
window.onload = function() {
socket.emit('cityPageReady');
console.log("city page ready");
};
socket.on('cityPageInfo', function(cityResponse) {
console.log('city page info received');
console.log(cityResponse);
console.log(cityResponse.user_name);
userName = cityResponse.user_name;
document.getElementById("name").innerHTML = userName;
});
app.js
var city = io.of('/city').on('connection', (socket) => {
console.log('A user has connected!');
socket.on('cityPageReady', function() {
socket.emit('cityPageInfo', cityResponse);
console.log('city page ready recieved');
});
});
This works, but many people have said that this is overkill, or as one person put it, "using a hammer to kill a bee". Ideally, I'd like to use the optimal method. I do know that template engines can achieve this, but I do not want to have to rewrite all my HTML just to be able to send a single variable to the server.
To reiterate, my questions are:
How would I get a variable from the client-side JavaScript file (not the HTML)?
What is the best way to send these variables back over to client-side?
Any help would be greatly appreciated.

Creating a user session - NODE js

I am new to node js & javascript in general. I have the below piece of code that will handle a login. I have a MYSQL database with a customer table. When the customer enters their username and password, it checks does it exist in the database. This part is working.
I now want to enhance this feature so that it will take the username and create some sort of a session variable, which can be used across the application. I am new to JS so I am not yet sure which inbuilt facilities already exist, or best practice around sessions.
I want to be able to use this session variable across the application, and for subsequent logout facility.
Can someone advise me on this, or point me in the right direction? Thanks.
case "/login":
var body = '';
console.log("user Login ");
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var obj = JSON.parse(body);
console.log(JSON.stringify(obj, null, 2));
var query = "SELECT * FROM Customer where name='"+obj.name+"'";
response.writeHead(200, {
'Access-Control-Allow-Origin': '*'
});
db.query(
query,
[],
function(err, rows) {
if (err) {
response.end('{"error": "1"}');
throw err;
}
if (rows!=null && rows.length>0) {
console.log(" user in database" );
theuserid = rows[0].customerID;
var obj = {
id: theuserid
}
response.end(JSON.stringify(obj));
}
else{
response.end('{"error": "1"}');
console.log(" user not in database");
}
}
);
});
}
There can be multiple ways of implementing a user session.
One, you could use a browser cookie, it comes with many pros and cons and you should read about it a bit to see how its managed. This would also depend on the server you are using (express, hapi, etc).
Two, you can set a JWT token on the backend, and include it in the header of the response, then you can either use your application state or the local storage of the browser to save that token on the UI. Any such follow up requests requiring authentication should contain this auth token as a header for verification.
For more clarity, you can look into related libraries (such as passport), which make this task a lot easier.
PS: If you choose cookies, please make sure the business is going to allow it or not as the end-users do not like being tracked always. :)

How the user authorization is done using Firebase in a webapp?

I've got following code for user authorization using Firebase but I'm not able to understand the code. Below the code I've mentioned the doubts I'm facing. Plase someone clarify them.
var ref = new Firebase("https://prj_name.firebaseio.com");
var loggedInUser = [];
$(document).ready(function() {
authData=ref.getAuth();
if(authData == null){
//TODO find an elegant way to manage authorization
// window.location = "../index.html";
}else{
ref.child("users").child(authData.uid).on("value", function(snapshot){
$( "span.user-name").html(snapshot.val().displayName);
loggedInUser.displayName = snapshot.val().displayName;
});
}
$("#cPassword").focusout(function() {
validatePassword($("#cPassword"), $("#password"));
});
$(document).on("click", ".clickable-row" ,function(){
window.document.location = $(this).data("href");
});
});
function validatePassword(password, cPassword) {
if (cPassword.val() != password.val()) {
cPassword.css('border-color', 'red');
password.css('border-color', 'red');
return false;
}
return true;
}
All the necessary libraries like firebase have been included and above code is working absolutely fine, the only concern is I'm not able to understand it.
My doubts are as follows :
What does the line authData=ref.getAuth(); do and what authData contains after it get execute?
In else block, what is value and snapshot. I didn't understand at all the line. ref.child("users").child(authData.uid).on("value", function(snapshot)
Can someone please clarify my doubts? Thanks.
Ok here goes:
Firstly you should update your firebase security rules first if you haven't already: Firebase security rules guide
ref.getAuth() returns a value that will either be null if you haven't been authorised yet or it will contain an object with some info about how the user was authorised (custom token, facebook id, email etc.)
This line: ref.child("users").child(authData.uid).on("value", function(snapshot). Here you're basically requesting some data from your users collection: '/users/{some unique id}'. When you request the data from firebase, as soon as the data is ready to be used, Firebase triggers the "value" callback and passes the data (snapshot) using this callback.
The firebase docs are very good, I would advise reading through the entire web guide. Firebase web guide
I hope I've been able to clear some things up for you!

JavaScript persist a search query through out the whole site

I'm currently fetching a query (e.g, http://localhost:49781/HTML/index.html?inputName=Marcus) from a html form using this following JavaScript:
function setSignedName() {
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
document.getElementById("signed_in_name").innerHTML += split[1];
} else {
document.getElementById("signed_in_name").innerHTML = "Not signed in";
}
running the script will get the result: Marcus.
I want this string to be persisted through out my site, so when the user navigates to another page the inputName will still be Marcus.
What is the best way of achieving this?
Edit: This approach is only for display/non-production use, I know using a server side language like PHP is the best approach.
I believe the best way is using localStorage. It works in all major browsers and it's easy to use:
function setSignedName() {
var userName = "";
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
userName += split[1];
} else {
userName = "Not signed in";
}
document.getElementById("signed_in_name").innerHTML = userName;
localStorage.setItem("userName", userName);
}
To access it:
var userName = localStorage.getItem("userName");
And this is it. Check for it in the Resources tab in Developer tools(F12) in your fav broswer.
You'll want to either repopulate it through GET parameters in your server side language, or if you want to hack it together, use a cookie and repopulate it with JavaScript on page load with "pushState".
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState()_method

Lotus notes automation from browser

I have been trying to automate Lotus Notes mail fillup from a browser interface.
After refering to Richard Schwartz's answer, i came up with this piece of code using the Lotus.NotesSession class.
function SendScriptMail() {
var mToMail = document.getElementById('txtMailId').value
var mSub = document.getElementById('txtSubject').value
var mMsg = document.getElementById('txtContent').value
var Password = "yyy"
alert("1");
var MailFileServer = "xxx.com"
var MailFile = "C:\Program Files\IBM\Lotus\Notes\mail\user.nsf"
alert("2")
var Session;
var Maildb;
var UI;
var NewMail;
var From = "user#xxx.com"
try {
alert("3")
// Create the Activex object for NotesSession
Session = new ActiveXObject("Lotus.NotesSession");
alert("4")
if (Session == null) {
throw ("NoSession");
} else {
Session.Initialize(Password);
// Get mail database
Maildb = Session.GetDatabase(MailFileServer, MailFile);
alert("5")
if (Maildb == null) {
throw ("NoMaildb");
} else {
NewMail = MailDB.CreateDocument();
if (MailDoc == null) {
throw ('NoMailDoc');
} else {
// Populate the fields
NewMail.AppendItemValue("Form", "Memo")
NewMail.AppendItemValue("SendTo", mToMail)
NewMail.AppendItemValue("From", From)
NewMail.AppendItemValue("Subject", mSub)
NewMail.AppendItemValue("Body", mMsg)
NewMail.Save(True, False)
NewMail.Send(False)
}
}
}
} catch (err) {
// feel free to improve error handling...
alert('Error while sending mail');
}
}
But now, alerts 1,2,3 are being trigerrd, and then the counter moves to the catch block. The lotus notes session is not being started.
In a powershell script that I was previously looking at there was a code regsvr32 "$NotesInstallDir\nlsxbe.dll" /s that was used before the Session = new ActiveXObject("Lotus.NotesSession");. Is there something similar in javascript too, if so how do i invoke that dll.
I think I've realised where I am going wrong. According to me, upto alert("5") things are good. But since Lotus.NotesSession doesn't have a CreateDocument() method, it is throwing the error. I am not sure how to create the document and populate the values though.
Since you've chosen to use the Notes.NotesUIWorkspace class, you are working with the Notes client front-end. It's running, and your users see what's happening on the screen. Are you aware that there's a set of back-end classes (rooted in Lotus.NotesSession) instead of Notes.NotesSession and Notes.NotesUIWorkspace) that work directly with Notes database data, without causing the Notes client to grab focus and display everything that you're doing?
Working with the front-end means that in some cases (depending on the version of Notes that you are working with) you're not going to be working directly with the field names that are standard in Notes messages as stored and as seen in the back-end. You're going to be working with names used as temporary inputs in the form that is used to view and edit the message. You can see these names by using Domino Designer to view the Memo form.
Instead of using 'SendTo', try using:
MailDoc.Fieldsettext('EnterSendTo', mToMail)
Regarding the Body field, there's no temporary field involved, however you haven't really explained the difficulty you are having. Do you not know how to display the interface that you want in the browser? Do you not know how to combine different inputs into a single FieldSetText call? Or are you just dissatisfied with the fact that FieldSetText can't do any fancy formatting? In the latter case, to get more formatting capability you may want to switch to using the back-end classes, which give you access to the NotesRichTextItem class, which has more formatting capabilities.

Categories