I am trying to open url using using this package. It works locally, but if I try to use the same thing on my deployed app, it is not working, it just skip that part, or it looks like that because it returns a message, but it is not opening url. Is there something that should be configured on server for this?
For example, I am trying to do this
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
});
try {
opn(authorizeUrl, { wait: true }).then(cp => {
console.log('cp', cp)
const server = http
.createServer(async (req, res) => {
try {
if (req.url.indexOf('/callback') > -1) {
const qs = new url.URL(req.url, `${process.env.SERVER_API_URL}`)
.searchParams;
res.end(
'Authentication successful! Please return to the console.'
);
server.destroy();
const { tokens } = await oauth2Client.getToken(qs.get('code'));
oauth2Client.credentials = tokens;
resolve(oAuth2Client);
}
} catch (e) {
reject(e);
}
})
});
return res.send({ msg: 'okay' })
and it works locally, but on deployed app it just returns 'ok'. If I use callback or something else to return message, it just block and causes timeout.
Related
I'm developing a webapp authentication system using Firebase. When I login and use the webapp from my computer everything works fine but when I use it on mobile appcheck does not work anymore and it gives me the following error in the console:
https://content-firebaseappcheck.googleapis.com/v1/projects/nameoftheproject/apps/1:784721317237:web:5db5892bc06253ab6b173c:exchangeRecaptchaEnterpriseToken?key=myKey
Failed to load resource: the server responded with a status of 403 ()
This is the code I'm using to create initialise appCheck in my webapp:
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaEnterpriseProvider(config[process.env.REACT_APP_ENV]['recaptcha-key']),
isTokenAutoRefreshEnabled: true
});
export const getAppCheckToken = async () => {
let appCheckTokenResponse;
try {
appCheckTokenResponse = await getToken(appCheck, false);
} catch(err) {
console.log(err);
}
return appCheckTokenResponse.token;
}
So a typical use case for that function is this:
//This is the code from one of my functions, it's just an example to show you how I use appcheck tokens
if (querySnapshot.docs.length === 0) {
headerAPI.headers['X-Firebase-AppCheck'] = await getAppCheckToken();
await axios.post(signupAPI, {
email: email,
username: displayName
}, headerAPI);
await sendEmailVerification(auth.currentUser, {
url: config[process.env.REACT_APP_ENV]['url-used-to-send-mail-auth-signup'],
handleCodeInApp: true
})
props.cookieAlert('Info', 'Cookies', 'Informations here...');
} else {
window.location.href = '/dashboard/home';
}
Now, I can't understand why it doesn't work on mobile...I hope my code is clear enough to let you understand my troubles, thank you in advance.
I have a route like http://localhost:3000/admin/video/edit/5 and the controller looks like this
albumEdit: async (req, res) => {
const editInfoId = req.params.id;
await Movie.findOne({ where: { id: editInfoId } }).then((movie) => {
if (movie) {
res.render('admin/movies/edit', { title: 'Edit Movie On Page One', movie });
}
});
},
for the testing purpose when I type the wrong id after edit/ then the process is freezing after some time I am getting 500 errors.
how to prevent this if someone tries to break my app with the wrong id in the URL? I want something like if anyone tries to do this application redirect to an error page.
I am new in node js express js I need some info.
Your route will freeze if movie is falsy or if fineOne results in an error because for both of these cases you don't send any response.
after some time I am getting 500 errors.
If you run your node server behind a web server then this 500 is due to a timeout because your router does not send a response.
how to prevent this if someone tries to break my app with the wrong id in the URL? I want something like if anyone tries to do this application redirect to an error page.
As with any programming language or code, make sure you handle all control flows and possible exceptions.
Besides that, if you use await you in most of the cases don't want to use .then.
albumEdit: async (req, res) => {
const editInfoId = req.params.id;
try {
let movie = await Movie.findOne({
where: {
id: editInfoId
}
})
if (movie) {
res.render('admin/movies/edit', {
title: 'Edit Movie On Page One',
movie
});
} else {
// either the if is not necessary or you have to also handle the else cases
// send some error response
res.send('error')
}
} catch (err) {
// send some error response
res.send('error')
}
}
For completeness, this is how where you would need to do changes in your code, but as said above don't mix await and then:
albumEdit: async (req, res) => {
const editInfoId = req.params.id;
try {
await Movie.findOne({
where: {
id: editInfoId
}
}).then((movie) => {
if (movie) {
res.render('admin/movies/edit', {
title: 'Edit Movie On Page One',
movie
});
} else {
// either the if is not necessary or you have to also handle the else cases
// send some error response
res.send('error')
}
});
} catch (err) {
// send some error response
res.send('error')
}
}
i am using graph api javascript example from here https://learn.microsoft.com/en-us/graph/api/user-list-joinedteams?view=graph-rest-beta&tabs=javascript
and my code is like:
async function(req, res) {
if (!req.isAuthenticated()) {
// Redirect unauthenticated requests to home page
res.redirect('/')
} else {
let params = {
active: { calendar: true }
};
// Get the access token
var accessToken;
try {
accessToken = await tokens.getAccessToken(req);
console.log("access token is:", accessToken)
} catch (err) {
req.flash('error_msg', {
message: 'Could not get access token. Try signing out and signing in again.',
debug: JSON.stringify(err)
});
}
if (accessToken && accessToken.length > 0) {
try {
console.log("vik testing stuff12 for teams")
const user = await graph.getTeams(accessToken)
console.log("graph me:::", user)
} catch (err) {
req.flash('error_msg', {
message: 'Could not fetch events',
debug: JSON.stringify(err)
});
}
} else {
req.flash('error_msg', 'Could not get an access token');
}
res.render('calendar', params);
}
}
getTeams is
getTeams: async function(accessToken) {
const client = getAuthenticatedClient(accessToken);
const events = await client
.api('/me/joinedTeams')
.version('beta')
.get();
return events;
}
this prints no results and no error. if I replace 'me/joinedTeams' to just 'me' then it returns logged in user details.
You can got a response successfully, so it seems no error with your code as you said if you call https://graph.microsoft.com/v1.0/me you can get user information.
And I tried to call this API using my account(my account hasn't joined any Teams), and got response like below, so if you got the same response as mine, perhaps you need to check if you have joined any Teams:
On the other hand, following the document, this API needs several permissions. So please obtain your access token when debug and use JWT tool to decrypt it to check if the access token have enough scope.
And I used the same request and got Teams information after adding my account to a team.
I am trying to build a Whatsapp chatbot using Node.JS and am running into a bit of trouble in receiving the Whatsapp message from Twilio. On checking the debugger, I get a Bad Gateway error, ie. Error 11200: HTTP Retrieval Failure. The message is getting sent, and ngrok shows the post request, however, dialogflow does not receive the request. On terminal, the error is showing UnhandledPromiseRejectionWarning: Error: 3 INVALID ARGUMENT: Input text not set. I'm not sure if it's because the message is not in JSON format. Please help!
This is the app.post function:
app.post('/api/whatsapp_query', async (req, res) =>{
message = req.body;
chatbot.textQuery(message.body, message.parameters).then(result => {
twilio.sendMessage(message.from, message.to, result.fulfillmentText).then(result => {
console.log(result);
}).catch(error => {
console.error("Error is: ", error);
});
return response.status(200).send("Success");
})
});
And this is the sendMessage function I've imported:
const config = require('./config/keys');
const twilioAccountID = config.twilioAccountID;
const twilioAuthToken = config.twilioAuthToken;
const myPhoneNumber = config.myPhoneNumber;
const client = require('twilio')(twilioAccountID,twilioAuthToken);
module.exports = {
sendMessage: async function(to, from, body) {
return new Promise((resolve, reject) => {
client.messages.create({
to,
from,
body
}).then(message => {
resolve(message.sid);
}).catch(error => {
reject(error);
});
});
}
}
And this is the textQuery function I've imported:
textQuery: async function(text, parameters = {}) {
let self = module.exports;
const request = {
session: sessionPath,
queryInput: {
text: {
text: text,
languageCode: config.dialogFlowSessionLanguageCode
},
},
queryParams: {
payload: {
date: parameters
}
}
};
let responses = await sessionClient.detectIntent(request);
responses = await self.handleAction(responses)
return responses[0].queryResult;
},
Twilio developer evangelist here.
The issue is that you are not passing the correct message body from the incoming WhatsApp message to your textQuery function.
First, you should make sure that you are treating the incoming webhook from Twilio as application/x-www-form-urlencoded. If you are using body-parser, ensure you have urlencoded parsing turned on.
app.use(bodyParser.urlencoded());
Secondly, the parameters that Twilio sends start with a capital letter. So your code currently gets message = req.body and then uses message.body. But it should be message.Body.
Those two points should sort you out.
One final thing though. The Twilio Node.js library will return a Promise if you do not pass a callback function. So you don't need to create a Promise here:
module.exports = {
sendMessage: async function(to, from, body) {
return new Promise((resolve, reject) => {
client.messages.create({
to,
from,
body
}).then(message => {
resolve(message.sid);
}).catch(error => {
reject(error);
});
});
}
}
You can just return the result of the call to client.messages.create
module.exports = {
sendMessage: async function(to, from, body) {
return client.messages.create({ to, from, body });
}
}
Hope this helps.
I am logging in/signing up users client side but I would like to check if their logged in from the server upon a page landing get request.
Is this possible?
You should have something server side which checks if a user is authenticated, this is the secure way as you can't trust verification client side as client side code can be altered by the user.
You can create a Cloud Code function to check if the user is logged In.
Some simple example:
Parse.Cloud.define('isLoggedIn', async (req) => {
const { user } = req;
if (!user) {
return { isLogged: false };
}
const sessionToken = user.getSessionToken();
try {
const result = await Parse.Cloud.httpRequest({
url: `${Parse.serverURL}/sessions/me`,
headers: {
"X-Parse-Application-Id": Parse.applicationId,
"X-Parse-JavaScript-API-Key": Parse.javaScriptKey,
"X-Parse-Session-Token": sessionToken,
}
});
return { isLogged: true }
} catch (e) {
return { isLogged: false }
}
});
Then you can use this cloud code function like this:
const isLoggedInFunc = async () => {
const { isLoggedIn } = await Parse.Cloud.run("isLoggedIn");
if (isLoggedIn) {
// if logged in do what you want
} else {
// if not logged in do what you want
// for example redirect user to login page or something ...
}
}
Hope this will help :)