I am working on generating unique email links for my users, trying to generate a code bye concatenating the user email and the Date timestamp.
The code generated looks like this
bUBzLnBvazE0NjM2ODc3MDg0MTA=3D
while in the mongodb it doesn't have 3D in it, bUBzLnBvazE0NjM2ODc3MDg0MTA=, and that's why URLs don't work.
I am using cryptoJS to encode string into base64.
const BASE_SERVER_URL = "http://localhost:3000/";
const INVITE_URL = BASE_SERVER_URL+"login/";
let uniqueCode = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(pmGroupUser.email+Date.now()));
let emailText = "Hello " + pmGroupUser.first_name + " click the following url to register your self ";
emailText += INVITE_URL;
emailText += uniqueCode;
Meteor.call('sendEmail',"to", "from","Subject", emailText, (err, res) => {
if(!err) {
Invites.insert({
code: uniqueCode
});
}
});
Related
I need to upload a file on the Postgres database using the nodeJs server. On frontend (vueJs) I have <input ref="file_upload" type="file" multiple="true" #change="changeFile" > element where I pick files. After I select the wanted file I convert it to a base64 string with the following code:
var file_input = this.$refs.file_upload
var base64String
function changeFile() {
for(let i = 0; i < file_input.files.length; i++) {
var reader = new FileReader();
reader.onloadend = () => {
base64String = reader.result
.replace('data:', '')
.replace(/^.+,/, '');
console.log(base64String)
console.log("SIZE: " + base64String.length)
}
reader.readAsDataURL(file_input.files[i]);
}
}
file_input.addEventListener('change', changeFile);
After I convert it to a base64 string, on button click I create post request with this code:
btnSubmit.addEventListener("click", () => {
let dat_title = file_input.files[0].name;
let url_files = "http://localhost:3000/blobFile/" + dat_title + "/" + base64String
console.log("URL:\n" + url_files)
fetch(url_files, {
method: "POST"
})
.then(response => {
response.json().then(parsedJson => {
console.log(parsedJson);
})
})
})
And that's where problems start. If the size of the base64 string is less than 16kB, it will normally do a post request and will be inserted into the database table (column is bytea type, so before insert I decode base64 string). But, if the size of the base64 string is more than 16kB, it shows an error that says how it failed to fetch. So I figured out that the URL is too big to fetch and I need to split it into chunks. And my question is how can I do that. How can I split that base64 string into chunks and receive those chunks on the nodeJs server? I've tried millions of solutions but nothing worked. If you know how to tackle this problem please write it down. Under is nodeJs server configuration:
app.js
require('dotenv').config();
var express = require('express');
var cors = require('cors');
var app = express();
const pool = require('./dbConnect');
const port = 3000;
app.use(cors());
app.post("/blobFile/:title/:url(*)", pool.postBlobFile)
app.listen(port, () => {
var host = "localhost";
console.log(`Server listening on port http://%s:%s`, host, port);
})
dbConnect.js
const postBlobFile = (req, res) => {
const dat_title = req.params.title
var base64String = req.params.url
console.log("TITLE: " + dat_title)
console.log("STRING: " + base64String)
console.log("STRING_SIZE: " + base64String.length)
pool.query(`insert into test_blob (dat_naziv, dat_blob)
values ('${dat_title}', decode('${base64String}', 'base64'))`,
(err, results) => {
if (err) console.log(err);
else{
res.json(results.rows)
}
})
}
module.exports = {
pool,
postBlobFile,
}
THANK'S IN ADVANCE
POST is for a reason. you are using GET, POST is just sitting useless in your code
There are 2 Problems which I am seeing
I don't know what you are trying to do. but do note that there is a URL length limit. and you are trying to exploit it and that's why you are getting this error. I don't understand why you are using POST if you won't just want to use bas64 in the URL
It is a best practice that you don't use Postgres for blob or byte type of things. just a suggestion. use something like s3 or spaces.
btnSubmit.addEventListener("click", () => {
let dat_title = file_input.files[0].name;
let url_files = "http://localhost:3000/blobFile/"
console.log("URL:\n" + url_files)
fetch(url_files, {
method: "POST",
'data | body': {'**Your data over here**'}
})
.then(response => {
response.json().then(parsedJson => {
console.log(parsedJson);
})
})
})
I'm Using node js to create a jwt in my backend server.
I'm using a library to sign/verify a JWT and it work fine. once one jwt.io i paste the token that i got when i sign in and i can see my data in the payload.
So the problem is that I'm trying to generate the signature from header and the payload that i got back in jwt.io
here is what i tryed to do but it did'nt work and i'm confuse a bit.
the algorith used to sign is the default one HS256.
const crypto = require("crypto");
// encode base64 the header
let jsonHeader = JSON.stringify({
alg: "HS256",
typ: "JWT",
});
let bs64header = Buffer.from(jsonHeader).toString("base64").split("=")[0];
console.log("bs64header :>>\n ", bs64header); //look the same as the token i got
// encode vase64 the payload
let jsonPayload = JSON.stringify({
id: "5eb20004ac94962628c68b91",
iat: 1589125343,
exp: 1589989343,
jti: "37743739b1476caa18ca899c7bc934e1aba63ba1",
});
let bs64payload = Buffer.from(jsonPayload).toString("base64").split("=")[0];
console.log("bs64Payload :>> \n", bs64payload); //look the same as the token i got
// TRY to generate the signature from the Base64Header and Base64Payload
// with the secret code that i used to sign the JWT
let secret = "0d528cb666023eee0d44e725fe9dfb751263d2f68f07998ae7388ff43b1b504f";
let signature = bs64header + "." + bs64payload;
let hashed = crypto
.createHash("sha256", secret)
.update(signature)
.digest("hex");
console.log("hashed :>> \n", hashed);
let bs64signature = Buffer.from(hashed).toString("base64").split("=")[0];
console.log("bs64signature>>", bs64signature); //This is where i got stuck.
// let jwt = bs64header + "." + bs64payload + "." + bs64signature;
// console.log("jwt>>", jwt);
I have modified your code a lot to make it less repetitive and easier to read. I am not entirely sure if this will work, so please comment if there are any errors.
I have tested it in runkit and have also checked what the output should be using jwt.io. The output appears to be the same, so I am pretty certain that this works.
Changes
Created a function to base64 encode objects and strings.
Created a function to make base64 strings use the URL safe character set.
Changed crypto.createHash() to crypto.createHmac(), so that a secret key can actually be used.
// base64 encode the data
function bs64encode(data) {
if (typeof data === "object") {
data = JSON.stringify(data);
}
return bs64escape(Buffer.from(data).toString("base64"));
}
// modify the base64 string to be URL safe
function bs64escape(string) {
return string.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
// base64 encode the header
let bs64header = bs64encode({
alg: "HS256",
typ: "JWT"
});
console.log("bs64header :>>\n ", bs64header);
// base64 encode the payload
let bs64payload = bs64encode({
id: "5eb20004ac94962628c68b91",
iat: 1589125343,
exp: 1589989343,
jti: "37743739b1476caa18ca899c7bc934e1aba63ba1"
});
console.log("bs64payload :>> \n", bs64payload);
// generate the signature from the header and payload
let secret = "0d528cb666023eee0d44e725fe9dfb751263d2f68f07998ae7388ff43b1b504f";
let signature = bs64header + "." + bs64payload;
let bs64signature = bs64escape(crypto
.createHmac("sha256", secret)
.update(signature)
.digest("base64"));
console.log("bs64signature>>", bs64signature);
let jwt = bs64header + "." + bs64payload + "." + bs64signature;
console.log("jwt>>", jwt);
I am trying to follow the firebase tutorial to retrieve data and display in Google assistant.But I am not able to retrieve multiple data from database in Dialogflow fulfillment.I want to ask user to enter register id with that field, remaining fields of student details were fetched.
I tried firebase documentation. My database connection was successful,But I am not able to retrieve data and also I want to ask user to enter the student Id i.e Register number. Suppose if i enter 191611238 [RegId] It will retrieve FirstName,EmailId and year fields.
* This is my Dialogflow fulfillment code *
const functions = require('firebase-functions');
const { WebhookClient} = require('dialogflow-fulfillment');
// initialise DB connection
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'ws://******.firebaseio.com/'
});
process.env.DEBUG = 'dialogflow:debug';
exports.dialogflowFirebaseFulfillment =
functions.https.onRequest((request, response) => {
const agent = new WebhookClient({
request,
response
});
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function getRegId(agent) {
const RegId = agent.parameters.RegId;
agent.add(`Thank you...`);
return
admin.database().ref('Table/').orderByChild('/RegId').equalTo("$RegId").once("value").then((snapshot) => {
var Email = snapshot.child("EmailId").val();
agent.add(`The student Mail is ` + Email);
var Regno = snapshot.child("RegId").val();
agent.add(`The student Register no is ` + Regno);
var name = snapshot.child("FirstName").val();
agent.add(`The student name is ` + name);
var year = snapshot.child("CourseName").val();
agent.add(`The student currently studying ` + year);
var Gradu = snapshot.child("GraduationTypeName").val();
agent.add(`The student Department is ` + Gradu);
});
}
// Run the proper function handler based on the matched Dialogflow
intent name
let intentMap = new Map();
intentMap.set('GetthedetailsofRegisternumber', getRegId);
agent.handleRequest(intentMap);
});
I want to get the details of student.but Iam getting Null i.e
The student Mail is null
The student Register no is null etc
I got error in Firebase console as
dialogflowFirebaseFulfillment
FIREBASE WARNING: Using an unspecified index. Consider adding ".indexOn": "RegId" at /Table to your security rules for better performance
Please provide me how to ask the user to enter RegId based on that I want to retrieve all fields.
function handleGetthedetailsofRegisternumber(agent){
const RegId = agent.parameters.RegId;
var ref = admin.database().ref().child("Table/");
var query = ref.orderByChild("RegId").equalTo(RegId.toString());
query.once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key);
// name field
console.log("FirstName: " + child.val().FirstName);
console.log("Mobile: " + child.val().MobileNumber);
console.log("Email: " + child.val().EmailId);
var name = snapshot.child("FirstName").val();
agent.add(`The student name is ` + name);
});
});
I would like to be able to convert the JSON string sent from the server into a JavaScript object on a HMTL page. The raw JSON string data is being displayed, but I would rather display it as a JavaScript object instead.
case '/get_list':
if (req.method == 'POST') {
console.log("POST");
var body = '';
req.on('data', function(data) {
body += data;
console.log("Partial body: " + body);
});
req.on('end', async function() {
console.log("Body: " + body);
var json = JSON.parse(body)
console.log("name is " + json.name) // get name
const {
Client
} = require('pg');
const connectionString = 'postgresql://postgres:password#localhost/app';
const client = new Client({
connectionString: connectionString,
});
await client.connect(); // create a database connection
console.log("user input is " + json.name1);
//Returns the result from the database in a JSON string onto the HTML page
const res3 = await client.query('SELECT name, studentno, proname FROM applications WHERE name =$1 LIMIT 1', [json.name1]);
await client.end();
// json = res2.rows;
json = res3.rows;
var obj = JSON.parse(res3.rows);
var json_str_new = JSON.stringify(json); //working
console.log(obj);
console.log(json_str_new);
res.end(json_str_new);
});
}
break;
Actual results
{"name":"jake","studentno":10001212,"proname":"asdasdas"}
Expected/required results
{
name: 'jake',
studentno: 10001212,
proname: 'asdasdas'
}
If you're planning on using the JSON for anything, as in traversing and reading the data from that, then JSON.parse() is exactly what you need. Pretty-printing is something only useful for humans, so unless you're exclusively using the output for human consumption, the result you have should be fine.
However, if you are going to just show the data, then I would recommend just formatting the output into some HTML/CSS display.
But assuming you are planning on using the data for something, as mentioned before and by others, JSON.parse() is all you need to generate a JS object.
im using textlocal.in api for sending bulk sms, when i type message in regional language it shows error
{"errors":[{"code":204,"message":"Invalid message content"}],"status":"failure"}
is there any way of sending regional language please help me?
var http = require('http');
var urlencode = require('urlencode');
var msg = 'ಅನುವಾದಿಸಿ';
var toNumber = '9731750371';
var username = 'dinesh#cantern.in';
var hash = '171f2176f6a24f1d219028011d5bff7b9eac1a3ff91873de62af429a736da26'; // The hash key could be found under Help->All Documentation->Your hash key. Alternatively you can use your Textlocal password in plain text.
var sender = 'txtlcl';
var data = 'username=' + username + '&hash=' + hash + '&sender=' + sender + '&numbers=' + toNumber + '&message=' + msg;
var options = {
host: 'api.textlocal.in', path: '/send?' + data
};
callback = function (response) {
var str = '';//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}//console.log('hello js'))
http.request(options, callback).end();
First install
npm install i18n-nodejs --save
download the locale language json file and use this code
var config = {
"lang": "ar",
"langFile": "./../../locale.json"//relative path to index.js file
}
var i18n = require('i18n-nodejs')(config.lang, config.langFile);
where "ar" refers to Arabic language
and set character-set to UTF-8 like this
response.header("Content-Type", "html/text; charset=utf-8");