"Failed to fetch" error message in Infura - ipfs

Steps
Using "ipfs-http-client" npm library
setting up auth with projectId, privateKey from infura
import { create } from 'ipfs-http-client'
const privateKey = '...'
const projectId = '...'
const auth =
'Basic ' + Buffer.from(projectId + ':' + privateKey).toString('base64')
const INFURA_URL = 'something.infura-ipfs.io'
const client = create({
host: INFURA_URL,
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
apiPath: '/ipfs/api/v0',
})
Calling ipfs client
const fileUrl = await client.add(image)
returns an error "Failed to fetch"

You can only use dedicated gateways to access IPFS content, not to upload content. Please follow this link for more info.
Your solution will be to replace the sub-domain with which is
something.infura-ipfs.io to
ipfs.infura.io and hopefully it should work.
For details about Dedicated gateways, please follow this link.
Cheers.

Related

message": "Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500." in dialogflow fulfillment

I am trying to send email using dialogflow intents from my gmail. But it throws the same error every time and I am unable to understand the issue behind this. The same thing stand alone from my code is able to send emaail to various email addresses. So i guess the code works just fine . Please have a look at my code .
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const nodemailer = require("nodemailer");
const admin = require("firebase-admin");
const axios = require("axios");
admin.initializeApp({
credential:admin.credential.applicationDefault(),
databaseUrl:'ws://***************/'
});
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
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 welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function emailSend(){
const email= agent.parameters.email;
const name= agent.parameters.name;
const subject= agent.parameters.subject;
const message = agent.parameters.message;
}
const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '*****#gmail.com',
pass: '***********'
}
});
var mailOptions = {
from: 'Mamuni',
to: 'email' ,
subject: 'subject' ,
text: 'message'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
let intentMap = new Map();
intentMap.set('emailSend',emailSend);
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
agent.handleRequest(intentMap);
});
The error probably is indicative that your code is not reachable or probably not being served via a HTTPS endpoint. I suggest the following:
Is the code available over a publicly accessible endpoint?
If the above is yes, is it being served over a secure channel i.e. HTTPS?

connection in channels.js returns undefined?

I'm trying to establish a real-time socket connection to my client
side via feathers channels. It works without any sort of
authentication. But if i add the following login action scoket is
throwing a weak map key error.
app.on('login', (authResult, { connection }) => {
console.log(connection) // returns undefined
....
})
This is the error I'm receiving
Unhandled Rejection at: Promise Promise { TypeError:
Invalid value used as weak map key
at WeakMap.set ()
app.on('login', (authResult, { connection }) => {
console.log("============>>", connection)
if (authResult && connection) {
app.channel('anonymous').leave(connection);
if (authResult.user && authResult.user['chanelName']) {
let channelName = authResult.user['chanelName'].toString();
channelName = channelName.substr(0, 5)
app.channel(`channel/${channelName}`).join(connection);
} else
app.channel('authenticated').join(connection)
}
});
The connection object is undefined, i think that causes the problem.
Anu suggestions?
Please provide the client side script.
According to fethers documentation connection can be undefined if there is no real-time connection, e.g. when logging in via REST.
You should authenticate your client.
Sample script
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const io = require('socket.io-client');
const auth = require('#feathersjs/authentication-client');
const socket = io('http://localhost:3031');
const app = feathers();
// Setup the transport (Rest, Socket, etc.) here
app.configure(socketio(socket));
const options = {
header: 'Authorization', // the default authorization header for REST
prefix: '', // if set will add a prefix to the header value. for example if prefix was 'JWT' then the header would be 'Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOi...'
path: '/authentication', // the server-side authentication service path
jwtStrategy: 'jwt', // the name of the JWT authentication strategy
entity: 'user', // the entity you are authenticating (ie. a users)
service: 'users', // the service to look up the entity
cookie: 'feathers-jwt', // the name of the cookie to parse the JWT from when cookies are enabled server side
storageKey: 'feathers-jwt', // the key to store the accessToken in localstorage or AsyncStorage on React Native
storage: undefined // Passing a WebStorage-compatible object to enable automatic storage on the client.
}
app.configure(auth(options))
app.authenticate({
strategy: 'jwt',
accessToken: '<JWT TOKEN>'
}).then(() => {
console.log("Auth successfull")
const deviceService = app.service('myService');
deviceService.on('created', message => console.log('Created a message', message));
}).catch(e => {
console.error('Authentication error', e);
// Show login page
});
Hope this will help you.

Sending Data from React to MySQL

I am creating a publishing application that needs to use communication between React and MySQL database to send information back and forth. Using Express as my JS server. The server code looks as follows:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const cors = require('cors');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'ArticleDatabase',
port: 3300,
socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
});
// Initialize the app
const app = express();
app.use(cors());
appl.post('/articletest', function(req, res) {
var art = req.body;
var query = connection.query("INSERT INTO articles SET ?", art,
function(err, res) {
})
})
// https://expressjs.com/en/guide/routing.html
app.get('/comments', function (req, res) {
// connection.connect();
connection.query('SELECT * FROM articles', function (error, results,
fields) {
if (error) throw error;
else {
return res.json({
data: results
})
};
});
// connection.end();
});
// Start the server
app.listen(3300, () => {
console.log('Listening on port 3300');
});
And my React class looks as follows:
class Profile extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
author: '',
text: ''
}
}
handleSubmit() {
// On submit of the form, send a POST request with the data to the
// server.
fetch('http://localhost:3300/articletest', {
body: JSON.stringify(this.state),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(function (response) {
console.log(response);
if (response.status === 200) {
alert('Saved');
} else {
alert('Issues saving');
}
});
}
render() {
return (
<div>
<form onSubmit={() => this.handleSubmit()}>
<input type = "text" placeholder="title" onChange={e =>
this.setState({ title: e.target.value} )} />
<input type="text" placeholder="author" onChange={e =>
this.setState({ author: e.target.value} )} />
<textarea type="text" placeholder="text" onChange={e =>
this.setState({ text: e.target.value} )} />
<input type="Submit" />
</form>
</div>
);
}
}
So fairly standard stuff that I found in online tutorials. I can search my database and display fetched info no problem, but not the other way around. When I try to take input from the <form> tag nothing is inserted into my database but instead I get this error:
[Error] Fetch API cannot load
http://localhost:3000/static/js/0.chunk.js due to access control
checks.
Error: The error you provided does not contain a stack trace.
Unhandled Promise Rejection: TypeError: cancelled
I understand that this has something to do with access control but since I am already using cors and can successfully retrieve data from the database, I am not sure what I am doing wrong. Any suggestions will be greatly appreciated. Thank you in advance.
You'll need to isolate the problem by first verifying that your service point is CORS Enabled. In order to focus solely on CORS functionality, I would remove the MySQL code temporarily.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', function(req, res){
var root = {};
root.status = 'success';
root.method = 'index';
var json = JSON.stringify(root);
res.send(json);
});
app.post('/cors', function(req, res) {
var root = {};
root.status = 'success';
root.method = 'cors';
var json = JSON.stringify(root);
res.send(json);
})
// Start the server
app.listen(3300, () => {
console.log('Listening on port 3300');
});
One you have server listening on port 3300, run the following PREFLIGHT command at the terminal.
curl -v \
-H "Origin: https://example.com" \
-H "Access-Control-Request-Headers: X-Custom-Header" \
-H "Acess-Control-Request-Method: POST" \
-X OPTIONS \
http://localhost:3300
If the preflight request is successful, the response should include Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers
Now run the POST method.
curl -v \
-H "Origin: https://example.com" \
-H "X-Custom-Header: value" \
-X POST \
http://localhost:3300/cors
If the post request is successful, the response should include
Access-Control-Allow-Origin
If everything looks good, your server is okay. You then need to try the post method from your iOS app.
NOTE. I would also be suspicious of using cors on localhost. I would map 127.0.0.1 to a domain and then have the app use that domain instead. If you are on Linux or Mac, you modify /etc/hosts. For Windows it's c:\windows\system32\drivers\etc\hosts
Try explicitly whitelisting the server that is making the request:
const whitelist = ['http://localhost:3000']; // React app
const corsInstance = cors({
origin: (origin, callback) => {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
});
application.use(corsInstance);
https://expressjs.com/en/resources/middleware/cors.html#configuring-cors-w-dynamic-origin
You need to add event.preventDefault() at the end of your handleSubmit method (check this example https://stackblitz.com/edit/react-forms).
You have to do it for the reason for preventing form default behavior on submit: it tries to synchronously send data to the url it loaded from (since there is no action attribute on it).
For those who may have run into a similar problem, I was able to fix it by dumping express server altogether. I simply used the .php file on the Apache server to insert data into database. Hope it helps somebody.

Connecting to HTTPS web services API with node.js v4.2.6?

I'm looking at connecting to an https web api, I've obtained my token, and my username by receiving an email about it, and there isn't really any sample code to connect to the webservice using node; however there are examples for Java and C#, and based on those this is what I came up with...
/* WEB API: https://www.careeronestop.org/Developers/WebAPI/technical-information.aspx?frd=true */
// UserID: ...
// Token Key: ...==
// Your agreement will expire three years from today on 12/8/2019 and all Web API services will be discontinued,
// unless you renew.
var https = require('https');
var username = '...';
var tokenKey = "...==";
var options = {
host: 'api.careeronestop.org',
port: 443,
path: '/v1/jobsearch/' + username + '/Computer%20Programmer/15904/200/2',
method: 'GET',
headers: {
'Content-Type' : 'application/json',
'Authorization' : '' + new Buffer(tokenKey.toString('base64'))
}
};
var req = https.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
Unfortunately however, it returns a 401 Unauthorized, so is there anything that needs added to this to get it working? Some headers maybe?
I used this form to submit a request and then looked in the Chrome debugger network tab to see exactly what request was sent.
The authorization header is supposed to look like this:
Authorization: Bearer 901287340912874309123784
You also want this:
Accept: application/json
So, assuming tokenKey is already a string since it appears to have been sent to you in an email, you can change your code to this:
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + tokenKey
}

How to authenticate a java web app with KeyRock?

We are trying to create a user authentication in our web app ( that we are developing in Java Spring MVC). For our authentication we want to use the token and user info acquired from the users fiware.lab account on global instance of keyrock.
Since Keyrock is based on OAuth2 protocol, what is the best approach to use keyrock from our web app?
Is there a java library that we could use for this purpose?
Is there a way to integrate spring security or apache oltu?
Every example would be more than welecome.
We only have the implementation of node.js but we need a java version of this:
var express = require('express');
var OAuth2 = require('./oauth2').OAuth2;
var config = require('./config');
// Express configuration
var app = express();
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: "skjghskdjfhbqigohqdiouk"
}));
app.configure(function () {
"use strict";
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
//app.use(express.logger());
app.use(express.static(__dirname + '/public'));
});
// Config data from config.js file
var client_id = config.client_id;
var client_secret = config.client_secret;
var idmURL = config.idmURL;
var response_type = config.response_type;
var callbackURL = config.callbackURL;
// Creates oauth library object with the config data
var oa = new OAuth2(client_id,
client_secret,
idmURL,
'/oauth2/authorize',
'/oauth2/token',
callbackURL);
// Handles requests to the main page
app.get('/', function(req, res){
// If auth_token is not stored in a session cookie it sends a button to redirect to IDM authentication portal
if(!req.session.access_token) {
res.send("Oauth2 IDM Demo.<br><br><button onclick='window.location.href=\"/auth\"'>Log in with FI-WARE Account</button>");
// If auth_token is stored in a session cookie it sends a button to get user info
} else {
res.send("Successfully authenticated. <br><br> Your oauth access_token: " +req.session.access_token + "<br><br><button onclick='window.location.href=\"/user_info\"'>Get my user info</button>");
}
});
// Handles requests from IDM with the access code
app.get('/login', function(req, res){
// Using the access code goes again to the IDM to obtain the access_token
oa.getOAuthAccessToken(req.query.code, function (e, results){
// Stores the access_token in a session cookie
req.session.access_token = results.access_token;
res.redirect('/');
});
});
// Redirection to IDM authentication portal
app.get('/auth', function(req, res){
var path = oa.getAuthorizeUrl(response_type);
res.redirect(path);
});
// Ask IDM for user info
app.get('/user_info', function(req, res){
var url = config.idmURL + '/user/';
// Using the access token asks the IDM for the user info
oa.get(url, req.session.access_token, function (e, response) {
var user = JSON.parse(response);
res.send("Welcome " + user.displayName + "<br> Your email address is " + user.email + "<br><br><button onclick='window.location.href=\"/logout\"'>Log out</button>");
});
});
// Handles logout requests to remove access_token from the session cookie
app.get('/logout', function(req, res){
req.session.access_token = undefined;
res.redirect('/');
});
console.log('Server listen in port 80. Connect to localhost');
app.listen(80);
Edit 1
Here is my set up:
and the end result error I get when I call the token:
Fiware devguide explains how this oauth2 flow works against KeyRock.
There also, you can find linked several oauth2 implementations like scribe-data, where you can find several examples on how to use oauth2 authentication against some of the most extended social networks.