Accessing sqlite databases on remote machine with static adress (Electron / Nodejs / fs) - node.js

I am trying to access an sqlite file on a local area network machine located in "sqlite" folder, on windows file explorer I access it using the IP address "192.168.5.15/sqlite/db.sqlite", however when the electron aplication tries to access it, the path is converted to the local machine path "c:/application ....../192.168 ....".
please how can I just point the file directly using the static IP adress without converting it to local machine path?
here is the code:
// login_app.js
var route = require('../../libs/router.js'); //my lib
var dbPath = "192.168.5.15/sqlite/db.sqlite" // here is the path i want to keep it static
function login() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if(email == "" || password == ""){
alert("Please Enter Your email & Password ...");
return;
} else{
var sql = require('sql.js'); //Import sqLite
var fs = require("fs"); //Import Files driver
var SHA256 = require("crypto-js/sha256"); //Crypting Library
try {
var filebuffer = fs.readFileSync(dbPath); //here is the problem it converts the file to local machine path c:/..../192....
if (filebuffer != null) {
var db = new SQL.Database(filebuffer);
} else {
var db = new SQL.Database();
console.log("No Database");
}
// Prepare an sql statement
var stmt = db.prepare("SELECT * FROM users WHERE email=:emailid");
// Bind values to the parameters and fetch the results of the query
var result = stmt.getAsObject({':emailid' : email});
if(result.password == null) alert('Account not existing, please contact Your Administrator ...');
else{
if(SHA256(password) == result.password) {
route.data.relocate('dashboard');
}
else alert('Wrong Login credentials, please try again ...');
}
} catch (e) {
console.log(e);
}
}
}

as suggested by GregHNZ var dbPath = "//192.168.5.15/sqlite/db.sqlite" worked, so just used double slash.
Thanks GregHNZ

Related

Use Text-to-speech Azure service on public SPA (no authentication)

I have a public SPA website (written in Svelte), with no user authentication.
I'd like to use the Azure Text-to-speech service (as either REST Api or with the azure-cognitive-services npm package).
I now need to provide the api key to use the service... But I understand it is a bad practice to store that key in the client code.
What would be the way to use that service then? Do I really need a backend service? Do I need to wrap my text-to-speech code in something like an Azure Function?
Thanks
If you look at the Source Code of the microsoft-cognitiveservices-speech-sdk NPM package it is clear the only way to auth to the service is by using some form of token/id which you will have to store at client side.
Instead of that you can use an azure function which will take text and convert to text .
My index,js file in azure function .
var t = require('./test');
var fs = require('fs');
module.exports = async function (context, req) {
const name = (req.query.name || (req.body && req.body.name));
t(name);
context.res = {
body:""
}
}
The main processing will be in the file test.js
function test (text) {
var sdk = require("microsoft-cognitiveservices-speech-sdk");
var readline = require("readline");
// This will be the name of the file created later
var audioFile = "YourAudioFile.wav";
const speechConfig = sdk.SpeechConfig.fromSubscription(process.env.SPEECH_KEY, process.env.SPEECH_REGION);
const audioConfig = sdk.AudioConfig.fromAudioFileOutput(audioFile);
speechConfig.speechSynthesisVoiceName = "en-US-JennyNeural";
var synthesizer = new sdk.SpeechSynthesizer(speechConfig, audioConfig);
synthesizer.speakTextAsync(text,
function (result) {
if (result.reason === sdk.ResultReason.SynthesizingAudioCompleted) {
console.log("synthesis finished.");
} else {
console.error("Speech synthesis canceled, " + result.errorDetails +
"\nDid you set the speech resource key and region values?");
}
synthesizer.close();
synthesizer = null;
},
function (err) {
console.trace("err - " + err);
synthesizer.close();
synthesizer = null;
});
}
module.exports = test ;
Majority of code from above is from the MSDOC
At the end all you have to do is return the file created by the synthesizer.

How to configure the user_token of Damn Vulnerable Web Application within CSRF field while Script based authentication using ZAP?

I had been following the documentation of Script Based Authentication for Damn Vulnerable Web Application using ZAP. I have navigated to http://localhost/dvwa/login.php through Manual Explore which opens up the DVWA application on my localhost as follows:
and adds the URL to the Default Context.
I've also created the dvwa script with the following configuration:
and modified the dvwa script:
Now when I try Configure Context Authentication, dvwa script does gets loaded but the CSRF field doesn't shows up.
Additionally, POST Data doesn't even shows up but Extra POST Data is shown.
Am I missing something in the steps? Can someone help me out?
The modified script within the documentation of Script Based Authentication section for Damn Vulnerable Web Application using ZAP
seems incomplete.
The complete script is available at Setting up ZAP to Test Damn Vulnerable Web App (DVWA) which is as follows:
function authenticate(helper, paramsValues, credentials) {
var loginUrl = paramsValues.get("Login URL");
var csrfTokenName = paramsValues.get("CSRF Field");
var csrfTokenValue = extractInputFieldValue(getPageContent(helper, loginUrl), csrfTokenName);
var postData = paramsValues.get("POST Data");
postData = postData.replace('{%username%}', encodeURIComponent(credentials.getParam("Username")));
postData = postData.replace('{%password%}', encodeURIComponent(credentials.getParam("Password")));
postData = postData.replace('{%' + csrfTokenName + '%}', encodeURIComponent(csrfTokenValue));
var msg = sendAndReceive(helper, loginUrl, postData);
return msg;
}
function getRequiredParamsNames() {
return [ "Login URL", "CSRF Field", "POST Data" ];
}
function getOptionalParamsNames() {
return [];
}
function getCredentialsParamsNames() {
return [ "Username", "Password" ];
}
function getPageContent(helper, url) {
var msg = sendAndReceive(helper, url);
return msg.getResponseBody().toString();
}
function sendAndReceive(helper, url, postData) {
var msg = helper.prepareMessage();
var method = "GET";
if (postData) {
method = "POST";
msg.setRequestBody(postData);
}
var requestUri = new org.apache.commons.httpclient.URI(url, true);
var requestHeader = new org.parosproxy.paros.network.HttpRequestHeader(method, requestUri, "HTTP/1.0");
msg.setRequestHeader(requestHeader);
helper.sendAndReceive(msg);
return msg;
}
function extractInputFieldValue(page, fieldName) {
// Rhino:
var src = new net.htmlparser.jericho.Source(page);
// Nashorn:
// var Source = Java.type("net.htmlparser.jericho.Source");
// var src = new Source(page);
var it = src.getAllElements('input').iterator();
while (it.hasNext()) {
var element = it.next();
if (element.getAttributeValue('name') == fieldName) {
return element.getAttributeValue('value');
}
}
return '';
}
Using this script, CSRF Field and POST Data field shows up just perfect.

azure database and google spreadsheet connection error "Failed to establish a database connection. Check connection string, username and password."

I tried many ways to fix this error :
"Failed to establish a database connection. Check connection string, username and password."
Code :
function AcessaVendas () {
var URL = 'jdbc:sqlserver://servername:49159'
var USER = 'visitant'
var PASS = '*******'
var conn = Jdbc.getConnection(URL, USER, PASS);
var stmt = conn.createStatement();
stmt.setMaxRows(10000);
var start = new Date();
var rs = stmt.executeQuery( myquery());
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Dados");
ss.getRange('a2:h1000').clearContent();
var cell = ss.getRange('a2');
var row = 0;
while (rs.next()) {
for (var col = 0; col < 11; col++) {
cell.offset(row, col).setValue(rs.getString(col + 1));
}
row++;
}
rs.close();
stmt.close();
conn.close();
var end = new Date();
Logger.log('Time elapsed: ' + (end.getTime() - start.getTime()));
}
First i have tried changing the azure servername for the server ip, then i tried adding the database name like,
db = "databasename"
URL = 'jdbc:mysql://servername:49159'+'/'+ db;
I also thought that maybe the database user that i have created in the sql server management studio could be the problem, because he has db_datareader role but i tried using the user with db_owner role and it also didn't work.
I also tried to put every Google App Server IPs whitelist range in the firewall of the azure server(one at once, or do i have to put ervery ip range at once?).
Could someone give me a help?

Bluemix Nodejs FileTransferStep, documentation

I am a newbie to bluemix. I downloaded the client libraries. But I don't see API docs for Javascript. Where do I find that? How do I go about calling several of javascript functions which is neither in the nodejs client libs nor I could find it online?
about the Workload service call you have to edit your package.json file
to add a dependency on the iws-light module using an https link, as follows
"dependencies": {
"iws-light": "https://start.wa.ibmserviceengage.com/bluemix/iws-light.tgz"
}
then you have to open your shell, go to the root of your app and run:
npm install
after this you can require the Workload Scheduler service in your application:
var ws = require("iws-light");
and create a connection to Bluemix:
//retrieve service URL from Bluemix VCAP_SERVICES...
var wsConn;
if(process.env.VCAP_SERVICES) {
wsConn = ws.createConnection();
} else {
//...or set it on your own(if you're working in local)
var url = "your workload scheduler url";
wsConn = ws.createConnection(url);
}
//retrieve cloud agent
var agentName;
wsConn.getCloudAgent(function(data) {
agentName = data;
});
//set your timezone
wsConn.setTimezone({timezone: "Europe/Rome"}, function(err, data){
if(err){
console.log(err);
}
});
now you're ready to use the lib and create a process
and add to it a FileTransferStep:
//create a process
var process = new ws.WAProcess("ProcessName", "This process transfer a file every day from local to remote server");
//supported operations are ws.steps.FileTransferStep.OperationDownload or ws.steps.FileTransferStep.OperationUpload
var operation = ws.steps.FileTransferStep.OperationUpload;
//create FileTransferStep
var ftStep = new ws.steps.FileTransferStep(agentName, operation);
//supported protocols are AUTO, FTP, FTPS, SSH, WINDOWS;
ftStep.setProtocol(ws.steps.FileTransferStep.ProtocolAuto);
//set local file
var local = {
path: "local file path",
user: "local username",
password: "local password"
};
ftStep.setLocalFile(local.path, local.user, local.password);
//set remote file
var remote = {
path: "remote file path",
user: "remote username",
password: "remote password",
server: "remote server"
};
ftStep.setRemoteFile(remote.server, remote.path, remote.user, remote.password);
//the binary mode flag: true if it uses FTP binary mode
var binaryMode = true;
the passive mode flag: true if it uses FTP passive mode
var passiveMode = true;
//set timeout
var timeout = 5;
ftStep.setMode(binaryMode, passiveMode , timeout);
//add FileTransferStep to the process
process.addStep(ftStep);
//create a trigger
var trigger = new ws.TriggerFactory.everyDayAt(1, 7, 30);
//add Trigger to the process
process.addTrigger(trigger);
process.tasklibraryid = "your task library id";
//create and enable process
wsConn.createAndEnableProcess(process, function(err, data){
if(err){
console.log(error);
} else{
console.log("process created and enabled");
}
});
The code above creates a process using a file transfer step from node.js code, however I'm not sure if this is what you actually need.
If you can explain the scenario you are trying to implement, I can be more precise about which is the best way to implement this scenario using Workload Scheduler service.
Regards,
Gabriele

How to get and display the email using the Facebook provider in ASP.NET Identity and MVC 5

UPDATE: PLEASE SEE THIS POST: https://stackoverflow.com/a/20379623/687549
Been reading I think almost all questions on SO about external providers and how to get extra info/data/metadata/claims/orwhateveryouwannacallit in particular the email address which many use as the username on modern websites.
So the problem that I was facing was that I wanted to retrieve the email from the Facebook provider with as little code as possible. I thought to myself; the new ASP.NET Identity framework must have this buil-in and can do this with probably just a couple of lines of code. I searched and all I could find was these imensely large chunks of code and I thought to myself: there has got to be another more simpler way. And here it is, as an answer in this questionthread.
I managed to get this working with both Facebook and Google but what I'm concerned about is wheather or not I'm doing this right without any consequenses somewhere else in the code.
For instance: Do you really only need to specify the Scopes.Add("email") for it all to work or why haven't I been able to find more info about this on the interweb?
UPDATE: PLEASE SEE THIS POST: https://stackoverflow.com/a/20379623/687549
Startup.Auth.cs:
var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
AppId = "myAppId",
AppSecret = "myAppSecret"
};
facebookAuthenticationOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookAuthenticationOptions);
AccountController (default mvc 5 template app stuff)
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// These next three lines is how I get the email from the stuff that gets returned from the Facebook external provider
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
var email = emailClaim.Value;
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindAsync(loginInfo.Login);
if (user != null)
{
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
else
{
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
// Populate the viewmodel with the email
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = email });
}
}
I have the same problem. You need to edit and add this code to ExternalLoginCallback in the AccountController
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// added the following lines
if (loginInfo.Login.LoginProvider == "Facebook")
{
var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
var access_token = identity.FindFirstValue("FacebookAccessToken");
var fb = new FacebookClient(access_token);
dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
loginInfo.Email = myInfo.email;
}
Note the code dynamic myInfo = fb.Get("/me?fields=email"); this will work for facebook app with version 2.4, but for old version you can write this
dynamic myInfo = fb.Get("email");

Resources