auth0 Management Api NextJs not able to update metadata - javascript

Really struggling to get my head around authO management clients so I can update users information. I've created a Next.js API route for the backend but I'm not sure how to actually amend the user's data. I've followed the docs and got to the point below.
API route
The ID params I manually entered to test and my response is an empty JSON object.
The docs don't make it clear what I'm suppose to do in the update user area in.
var ManagementClient = require("auth0").ManagementClient;
export default async (req, res) => {
var auth0 = new ManagementClient({
domain: process.env.AUTH0_BASE_URL,
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
scope: "read:users update:users",
});
var params = { id: "**************************" };
var metadata = {
foo: "bar",
};
auth0.users.updateAppMetadata(params, metadata, function (err, user) {
if (err) {
// Handle error.
}
// Updated user.
console.log(user);
res.status(200).json({ user });
});
};
Error:
API resolved without sending a response for /api/authapi, this may result in stalled requests.
SanitizedError [APIError]: getaddrinfo ENOTFOUND http
(node:internal/process/task_queues:81:21) {
statusCode: 'ENOTFOUND',
requestInfo: { method: 'post', url: '***********' },
originalError: Error: getaddrinfo ENOTFOUND http
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http',
response: undefined
}
}

Related

JavaScript AWS Cognito Connection Problems "NetworkError"

I'm running into a strange problem with AWS Cognito. I'm able to create user accounts, however when I attempt to set the created user to a group it is
giving me a network timed out error.
Setup:
const AmazonCognitoIdentity = require('amazon-cognito-identity-js')
const AWS = require('aws-sdk')
const CognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({
region: 'us-east-1 ', // 100% sure this is the correct region
apiVersion: '2016-04-18'
})
const UserPoolId = config.cognito.userPoolId
const ClientId = config.cognito.clientId
const userPool = new AmazonCognitoIdentity.CognitoUserPool({ UserPoolId, ClientId })
Creating account:
userPool.signUp(email, password, [ emailAttribute ], null, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
CognitoIdentityServiceProvider.adminAddUserToGroup({
GroupName: 'TRIAL',
UserPoolId,
Username: email
}, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
res.redirect('/dashboard')
})
})
The account gets made correctly, however when attempting to add the new account to a group I get this error:
{ Error: connect ETIMEDOUT 104.239.207.44:443
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
message: 'connect ETIMEDOUT 104.239.207.44:443',
code: 'NetworkingError',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '104.239.207.44',
port: 443,
region: 'us-east-1 ',
hostname: 'cognito-idp.us-east-1',
retryable: true,
time: 2018-06-20T14:01:49.029Z }
I find this very strange as I just was able to create an account successfully.
Any ideas on why this is happening?
Thanks

Trouble making nodejs mysql connection

I am trying to make a simple connection between my nodejs server and my mysql db (using Microsoft SQL server manager studio v14), below is my code and the error message appearing in my console window.
here is my code:
var express = require('express');
var app = express();
var sql = require("mssql");
app.get('/', function (req, res) {
// config for your database
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Schools', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
The error I am getting looks like this:
Server is running..
tedious deprecated The default value for `options.encrypt` will change from `false` to `true`. Please pass `false` explicitly if you want to retain current behaviour. node_modules\mssql\lib\tedious.js:212:23
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.tedious.once.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:275:13)
at Connection.emit (events.js:182:13)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:14)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
code: 'ESOCKET',
originalError:
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\errors.js:12:12)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:30)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:174:19)
message: 'Failed to connect to localhost:1433 - Could not connect (sequence)',
code: 'ESOCKET' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1299:37)
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1242:12)
at C:\Users\smr09\Desktop\Code\ou\db_test\test.js:24:17
at _poolCreate.then.catch.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:178:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
I am rather new at this particularly with dealing with databases. Can someone explain what the error means?
Add this line to the config:
options: {
encrypt: false
}
It will finally look like:
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX' ,
options: {
encrypt: false
}
};
try to put encrypt: false in your config{}, it will work.
your error:
ConnectionError: Failed to connect to localhost:1433 - Could not
connect (sequence)
My problem was resolved by adding port
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX',
port: '',
};

SSL Error in nodejs request package

I'm trying to call freecodecamp api #url https://forum.freecodecamp.org/c/getting-a-developer-job.json?
I am doing some analysis on the data, but when I call this service using 'request' npm package I am getting ssl error as follows:
error { Error: write EPROTO 140735782093632:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1500:SSL alert number 40
140735782093632:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:659:
at _errnoException (util.js:1022:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:867:14) code: 'EPROTO', errno: 'EPROTO', syscall: 'write' }
Can somebody let me know what the issue is? A wget call pulls the data when provided with --ca-certificate option, also the webservice is giving data to postman without any certificate.
Here is my code:
import request from 'request';
import fs from 'fs';
const BASE_URL = 'forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1';
request.get(BASE_URL, {
port: 443,
agentOptions: {
ciphers: 'ALL',
ca: fs.readFileSync('./mycertfile.pem'),
secureProtocol: 'TLSv1_2_method'
},
strictSSL: false
})
.on('response', (response) => {
console.log('Response is ', response);
}).on('error', (err) => {
console.log('error', err);
});
I see no problems there except URI http:// is absent, in my environment i have node v10.5.0, and the slightly modified version of your script works well:
const request = require('request')
const BASE_URL = 'https://forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1'
request.get(BASE_URL, { json: true }, (err, res, body) => {
if (err) throw('error', err);
console.log('JSON object is => ', body);
})
outputs to console:
JSON object is => { users:
[ { id: 117390,
username: 'anthony2025',
....

No results from promise in Express Routing

I'm using NodeJS, Express and GoogleApis en Google-oauth-jwt to authenticate.
I'm having problems with getting data from my second promise function (getData).
I can succesfully retrieve a token, when I use res.json(myToken) in the getToken().then(function(myToken). However I'm having problems using this token in the getData(token) function.
When I'm finally able to retrieve data from the googleapis via the getData function,I'd like to save this data into a MongoDB, to reduce calls to the Google Analytics API.
These are the errors I get:
2018-01-11T09:46:55.063Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 token: XXXXXXXXXXXXXXX
2018-01-11T09:46:55.148Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 { Error:
Login Required at RequestError.Error (native) at new RequestError
(/var/task/node_modules/google-auth-library/lib/transporters.js:34:42)
at Request._callback
(/var/task/node_modules/google-auth-library/lib/transporters.js:96:27)
at Request.self.callback
(/var/task/node_modules/request/request.js:186:22) at emitTwo
(events.js:106:13) at Request.emit (events.js:191:7) at
Request.
(/var/task/node_modules/request/request.js:1163:10) at emitOne
(events.js:96:13) at Request.emit (events.js:188:7) at
IncomingMessage.
(/var/task/node_modules/request/request.js:1085:12) code: 401, errors:
[ { domain: 'global', reason: 'required', message: 'Login Required',
locationType: 'header', location: 'Authorization' } ] }
2018-01-11T09:46:55.153Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 (node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Login Required
This is my code:
var express = require('express');
var router = express.Router();
var googleAuth = require('google-oauth-jwt');
var google = require('googleapis');
var app = express();
/* get GA data*/
router.get('/kpis', function(req, res, next) {
// get token with googleapis library
function getToken() {
return new Promise(function(resolve,reject) {
googleAuth.authenticate({
email: 'serviceAcountemail#email.com',
key: "getting key",
scopes: ['https://www.googleapis.com/auth/analytics.readonly']
}, function (err, token) {
if (err){
reject(err)
} else
resolve(token)
});
});
}
function getData(token){
return new Promise(function(resolve,reject){
var analytics = google.analytics('v3');
var VIEW_ID = 'ga:profileid';
analytics.data.ga.get({
'auth': token,
'ids': VIEW_ID,
'metrics': 'ga:uniquePageviews',
'dimensions': 'ga:pagePath',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'sort': '-ga:uniquePageviews',
'max-results': 10,
}, function (err, response) {
if (err) {
console.log(err)
reject(err)
} else
console.log('Response:',response)
resolve(response)
});
});
}
getToken().then(function(myToken) {
// get the token, make a call to google analytics api with token included in auth
console.log('token:', myToken);
getData(myToken).then(function(results){
// show results on screen in json
res.json(gaResults);
});
});
});
/* end of get GA data*/
module.exports = router;
My question:

passport-facebook-token returns InternalOAuthError: Failed to fetch user profile when verifying the token

I have an iOS app in which I use Facebook API for logging in, and I get an access token in response. Now I want to use this token to authenticate user on my backend server.
I'm using passport-facebook-token strategy for Passport.js.
var FacebookTokenStrategy = require('passport-facebook-token');
module.exports = function(app) {
app.use(passport.initialize());
app.use(passport.session());
passport.use(new FacebookTokenStrategy({
clientID: '32424222424024',
clientSecret: '3292e42148264c2817523232446187',
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOne({ facebookId: profile.id }, function (err, user) {
console.log("facebook");
return done(err, user);
});
}
));
app.get('/auth/facebook',
passport.authenticate('facebook-token'),
function (req, res) {
res.send(req.user? 200 : 401);
}
);
};
But when I call http://localhost:3000/auth/facebook?access_token=my_token_here I get following error:
InternalOAuthError: Failed to fetch user profile
at C:\app\www\app\node_modules\passport-facebook-token\lib\index.js:152:32
at passBackControl (C:\app\www\app\node_modules\oauth\lib\oauth2.js:123:9)
at IncomingMessage. (C:\app\www\app\node_modules\oauth\lib\oauth2.js:143:7)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:474:9)
at process._tickCallback (node.js:388:17)
What steps in app configuration and/or authentication implementation am I'm missing?
First of all, check your ClientId and Client Secret, then check if you choose a correct app to test your connection to Facebook by Postman (or similar).
In my case, the problem was with generating token to another app

Categories

Resources