I have a chat application created using flutter dart and php mysql as backend and also node js for socket.io
So what i want is if i send a message via flutter dart, i want to encrypt it and send to node js via socket.io which will send it to the other client's flutter app and decrypt it there for the user to see and the node.js will also send it to my php script via json format and stores it in my database via post request. Also I will soon create a website where those messages will be decryted and displayed on the user browser and when i send message using the browser i also want to encrypt it and store in the database so that both flutter and web user can see the decrypted format.
const https = require("https");
const http = require("http");
const qs = require("querystring");
function send_to_db(msg) {
console.log(msg);
var postData = qs.stringify(msg);
var options = {
hostname: "*****.com",
port: 443,
path: "/src/chats/post.php",
method: "POST",
rejectUnauthorized: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": postData.length,
},
checkServerIdentity: function (host, cert) {
return undefined;
},
};
var buffer = "";
var req = https.request(options, (res) => {
res.on("data", function (chunk) {
buffer += chunk;
});
res.on("end", function () {
console.log(buffer);
});
});
req.on("error", (e) => {
console.error(e);
});
req.write(postData);
req.end();
return buffer;
}
Right now is am only encrypting and decrypting using php and am afraid of man in the middle attack since my data can be intercepted from flutter app to node.js before reaching my php side
Please what do I do to achieve this
Related
I got stuck when calling php api with form-data type in my React app. When I test with Postman, it works correctly but failed in react.
Please let me know if I'm doing wrong here.
In Postman, call api like this:
URl_API: xxxx/yyyy.php.
Config in Body tab in key/value: form-data
k: "some string"
id: "some string"
With axios, I had an error:
My code:
const formData = new FormData()
formData.append('k', 'some string')
formData.append('id', 'some string')
const response = await axios.post('xxxx/yyyy.php', formData, {
headers: {
'Access-Control-Allow-Origin': '*',
},
})
xxxx/yyyy.php net::ERR_HTTP2_PROTOCOL_ERROR
I had already tried with fetch but no luck - call api success with status 200 but the response.text() is empty.
With fetch api:
const result = await fetch('xxxx/yyyy.php', {
method: 'POST',
mode: 'no-cors',
body: formData,
cache: 'no-cache',
})
.then(async (res) => {
return res.text()
})
.then((text) => console.log('It is empty here', text))
It look like a CORS also, but you will be able to sort it out
a simple solution in development is to use a local api server, and finally when the app is deployed to the server which is on the same domain as the api, you should get the response, as demonstrated below by making the calls using dev tools.
in short: if a api calls work with postman but not through the browser, its mostly due to cors restrictions, then it could be the response type
Verifying cors issue by making calls throught dev tools
let onSubmit = async () => {
try {
const url = "https://www.your-domain***.com/getUrlApp.php";
const formData = new FormData();
formData.append("k", "kk");
formData.append("id", "dd");
const data = new URLSearchParams(formData);
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "no-cors", // no-cors, *cors, same-origin
body: data // body data type must match "Content-Type" header
});
//const res = response.json();
const buffer = await response.arrayBuffer();
const decoder = new TextDecoder("iso-8859-1");
const text = decoder.decode(buffer);
console.log("text", text);
return response;
} catch (error) {
console.log("error", error);
}
};
To verify the response
go https://www.your-domain***.com
open dev tools => console
past the function above and run it by typing onSubmit() in the console
you will see the response
Hope it helps you in some way
Im building my socket application with laravel broadcaasting. I made my server script and then added https like in this script: (The code may contain errors because it is written from memory)
var fs = require('fs');
var https = require('https');
var express = require('express');
var app = express();
var options = {
key: fs.readFileSync('./file.pem'),
cert: fs.readFileSync('./file.crt')
};
var serverPort = 3000;
var server = https.createServer(options, app);
var io = require('socket.io')(server);
require('socketio-auth')(io, {
authenticate: authenticate,
postAuthenticate: postAuthenticate,
disconnect: disconnect,
timeout: 1000
});
after that i added socketio-auth and modified it for just username and password authentication.
function authenticate(socket, data, callback) {
if (data.username != "username") {
return callback(new Error("User not found"));
}
return callback(null, user.password == "password");
}
}
My question is about credntials I'm sending via socket.
import VueSocketio from 'vue-socket.io';
Vue.use(VueSocketio, socketio('https://socketserver.com:1923', {secure: true}));
var vm = new Vue({
sockets:{
connect: function(){
console.log('socket connected')
this.$socket.emit('authentication', {username : "username", password: "password"});
},
},
})
Im actually using Vue with vue-socketio but its working with connection and with getting / sending information properly.
Problem I got is when Im going to console in google chrome im getting plain text socket emit authentication information like
(REQUEST PAYLOAD : {authentication: {username: "username", password : "password"}}).
Is that normal thing when Im using ssl? Something is wrong with my code?
Or I need to encrypt then decrypt this information myself?
I thought all Im sending via HTTPS is encrypted.
Looking for ur replay. Thanks!
Okey I made my own encryptor.
For client Im emiting encrypted information with data and the verify hash with socket.id.
And for server i decrypted and check hmac verification with socket.id.
I'm using Node.js (on AWS Lambda for alexa skill) to request my web server for a JSON file. But my server responds with a 'Javascript' not supported error html.
This is my code:
function httpsGet(myData, callback) {
// Update these options with the details of the web service you would like to call
var options = {
host: 'alexa0788.byethost24.com',
port: 80,
path: '/sample.php',
method: 'GET',
};
var req = http.request(options, res => {
res.setEncoding('utf8');
var returnData = "";
res.on('data', chunk => {
returnData = returnData + chunk;
});
res.on('end', () => {
console.log(returnData);
var pop = JSON.parse(returnData).firstName + JSON.parse(returnData).lastName;
callback(pop); // this will execute whatever function the caller defined, with one argument
});
});
req.end();
}
How can I make my server respond with the intended json and not force the client to support javascript? At the moment, I'm having a php file output the json. I tried calling a .json file too directly, instead of making a php file output json, but I see the same error.
I'm working on an AWS Lambda function in Node.js to call a PHP
URL
that will return a JSON encoded response so that Alexa (Amazon Dot, etc.) can reply to a user query. I've got all my intents set up properly and Alexa (online test) replies to the question, but the tag contains "Unchanged" (see code), indicating it isn't getting anything from the http.get() function in Node.js.
Here's the function to get the text that Alexa should speak:
function getData(mypath) {
var http = require('http');
var options = {
host: 'www.gypsysticks.com',
port: 80,
path: mypath
};
var mydata = "Unchanged";
http.get(options, function(res) {
res.on("response", function(chunk) {
mydata = chunk;
});
});
return mydata;
}
I'm building this "Skill" for Alexa for my band, Gypsy Sticks. Currently the url and path points to www.gypsysticks.com/echo/tonight.php which is supposed to return the location and time of the show for tonight. Right now I've just got it returning a JSON string with { "response" : "Test Success" }
I'm not familiar with Node.js, or the http.get() function.
i have my php point exposing these endpoints for example
[GET] /api/news --> [return] [ {id:1,title:'news1'},{id:1,title:'news1'} ];
[POST] /api/news?title=<string> --> [return] {id:NEW_ID,title:$title};
and my frontend webapp use angular 1 to get news.
//to get all news
$http.get('http://server.com/api/news').then(function(res){
$scope.news = res.data;
});
//to post a new news
$http.post('http://server.com/api/news',{title:'news3'}).then(function(res){
$scope.news.push(res.data);
});
this would work fine, except that i will have to pool every interval to get any new news, so i thought something like socket.io can help.
I'm tryying to achive.
user connect to io
io send all news once user connects by consuming my php api
when user post new, he send it to io server, and io forward the post request to my rest api and return the result to all connected users.
so my change to front end can be something like
var socket = io('http://localhost:3700');
socket.on('news', function (data) {
$timeout(()=>{$scope.news = data;});
});
socket.on('news_posted', function (data) {
$timeout(()=>{$scope.news.push(data);});
});
$scope.post = function(title){
socket.emit('post_news', { title: title });
}
now what i have no clue is how to make such simple server ?
var express = require("express");
var app = express();
var port = 3700;
var io = require('socket.io').listen(app.listen(port));
//setting CORS
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key,auth-client,auth-uid,auth-token');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
io.sockets.on('connection', function (socket) {
console.log('a user connected');
///BLOCK 1
///GET ALL POSTS FROM API AND EMIT news event BACK TO USER
///
socket.on('new_post', function(msg){
///BLOCK 2
///POST title TO API AND EMIT BACK news_posted WITH THE RESPONSE
});
});