How to handle server side error during authentication in react-native - node.js

So I was making an app and in that app I have say login with facebook
For login, I am using expo-web-browser
Here is my relevant code,
loginWithFacebook = async () => {
const redirectUrl = await Linking.getInitialURL()
const authUrl = config.backendUrl + '/auth/facebook'
Linking.addEventListener('url', this.handleRedirect)
try {
const authResult = await WebBrowser.openAuthSessionAsync(authUrl, redirectUrl)
console.log(authResult)
Linking.removeEventListener('url', this.handleRedirect)
} catch (err) {
console.warn('ERROR:', err)
}
}
While this works, my problem is on error handling, I am using passport Js on the backend (NodeJS). On successful authentication, I am re-directing to my deep link url
return res.redirect(myapplink://)
and currently, on error (say there is an sql connection error), I am throwing a 500 internal error
return res.status(error.status).send(error.message)
Since typically auth related events are done using href and not using ajaxy request, How would you typically handle the error in this situation? I think the answer for the app and web should be identical but if not can you please suggest the way I can handle error in the app and web.

Related

Node / React Authentication API callback STUMPER

I've been developing for a year and change and this maybe a novice question but I've tried EVERYTHING (~150 hours worth of tries, YIKES) I will post my React Frontend and my Nodejs backend to hopefully get some clarity.
Key notes:
-I am using Auth0 authentication to build an api with a nodeJs server
-Auth0 says to use an https:// call which my localhost:3000 is not. However, everything about AUTH0 works except the API call invoked when a user logs in to redirect them and display their information on their profile. I have only found one solution to this which is a reverse proxy https:// server to make calls (I can stop here if this is the issue lol unless another easier method is out there). Also why would AUTH0 require production https servers to test???
-I have the correct CORS enabled on AUTH0's site and 99% sure NodeJs (I can get a console.log response from my API) and have tried many ways on the front end and backend
to solve.
Help would greatly, greatly, be appreciated.
Code:
function URLChecker() {
// setTimeout(function(){
// console.log("Executed immediately");
if (location.pathname.indexOf('/profile/') === 0) {
//setToken(true);
return true;
}
}
function tokenChanger() {
setToken(true);
console.log("Your token is presented as...", token)
}
useEffect(()=> {
//console.log("url checker is:" + URLChecker());
if(URLChecker() == true){
tokenChanger();
console.log(location)
if (token) {
console.log("token exists");
axios.defaults.headers.get['Access-Control-Allow-Origin'] = 'http://localhost:3000';
axios.get('http://localhost:8080/profile')
.then(res => {
//console.log(res);
console.log(res.data);
}).catch(error => {
console.log(error);
console.log("API for user FAILED")
})
}
app.get('/profile', requiresAuth(), (req, res, next ) => {
console.log(req.oidc.user);
res.header("Access-Control-Allow-Origin", "*");
res.redirect(http://localhost:3000/profile/${((req.oidc.user.nickname))})
});
(res(req.oidc.user) returns a localhost:8080/profile page that is blank with the JSON of the user's information displayed. My next step is to obviously make my frontend call a different API instead of /profile to hit an authentication required api that will return user data, however no matter what I've tried I always get stuck with the same error message. I am so close and don't know whether to stick with AUTH0 to solve this error or going with Google authentication which I hear is nice.
Thank you,
imgur link to error message on my frontend

GraphqQL Cannot set headers after they are sent to the client

I have tried looking at other articles on SO related to this question, but I am unable to resolve this issue.
I have a graphql api and in my component on the UI side, I am calling it as such
useEffect(()=>{
const leaders = graphQLClient.request(GetLeadersQuery)
if(leaders && leaders.leaders) {
let leadersList = JSON.parse(leaders.leaders)
setLeaders(leadersList)
}
}, [leaders])
On the server side, this looks like this
leaders: (_parent, args, _context) => {
return (JSON.stringify({
name:"Jane Dooe"
}))
This is the query that I am using
query {
leaders
}
Now everytime, my client side code is hit, I see the following error in my terminal.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
My use case is very simple and yet , I am unable to see why I am encountering this error.
Update
On my client side, I tried doing the following, just to make sure that I am resolving the promises, but I am still getting the same result.
useEffect(()=>{
async function getLeaders(){
const leaders = await graphQLClient.request(GetLeadersQuery)
console.log({ leaders })
if (leaders && leaders.leaders) {
let leadersList = JSON.parse(leaders.leaders)
setLeaders(leadersList)
}
}
getLeaders()
}, [])
On the server side I am using
NextJS
apollo-server-micro
On the client side I am using
React
graphql-request
Can you please help ?
Thanks

Botkit Slackbot responds with 401 error every time

I'm trying to create a very simple Slack bot using botkit and Google App Engine, but for some reason I keep getting 401 errors any time I message the bot. The weird thing is that the Slack Event Subscription URL (the one ending in /api/messages) validates correctly, and I get a 200 response in GAE logs and validation within Slack.
But whenever I actually message the bot it always gets a 401 error with no message explaining the error at all. I've tried various combinations of the code below, and have now stripped it down to the bare minimum as found here. Aside from dependencies and a code to decrypt credentials (which I've verified is working as expected), this is my full code at the moment:
botInit();
async function botInit () {
const credentialsRaw = await getCredentials();
const credentials = JSON.parse(credentialsRaw);
const adapter = new SlackAdapter(credentials);
const controller = new Botkit({
adapter: adapter
});
controller.on('message', async(bot, message) => {
await bot.reply(message, 'I heard a message!');
});
}
I have also tried this for the messaging function:
controller.ready(() => {
controller.hears(['hello', 'hi'], ['message', 'direct_message'],
async (bot, message) => {
await bot.reply(message, 'Meow. :smile_cat:')
})
})
and this for setting up the controller:
const controller = new Botkit({
webhook_uri: '/api/messages',
adapter: adapter
});
And everything gives back the same exact 401 error, despite all of them working with the Event Subscription URL verification on Slack.
I had same issue but figured out the problem.
I had been using Client Secret as clientSigningSecret
But I should use Signing Secret !

How to get external api data using inline editor in dialogflow

I've got a Dialogflow agent for which I'm using the Inline Editor (powered by Cloud Functions for Firebase). When I try to get external api data by using request-promise-native I keep getting Ignoring exception from a finished function in my firebase console.
function video(agent) {
agent.add(`You are now being handled by the productivity intent`);
const url = "https://reqres.in/api/users?page=2";
return request.get(url)
.then(jsonBody => {
var body = JSON.parse(jsonBody);
agent.add(body.data[0].first_name)
return Promise.resolve(agent);
});
}
Your code looks correct. The exception in this case might be that you're not using a paid account, so network access outside Google is blocked. You can probably see the exact exception by adding a catch block:
function video(agent) {
agent.add(`You are now being handled by the productivity intent`);
const url = "https://reqres.in/api/users?page=2";
return request.get(url)
.then(jsonBody => {
var body = JSON.parse(jsonBody);
agent.add(body.data[0].first_name)
return Promise.resolve(agent);
})
.catch(err => {
console.error('Problem making network call', err);
agent.add('Unable to get result');
return Promise.resolve(agent);
});
}
(If you do this, you may want to update your question with the exact error from the logs.)
Inline Editor uses Firebase. If you do not have a paid account with Firebase, you will not be able to access external APIs.

Github api - how to make authenticated requests?

I am using Nodejs to write a simple web app that needs to read content from readme files using the GH api.
Everything works, but I am can't sort how to create requests as an authenticated user.
Sorry bit of a noob here :-) but is it not enough to add my client and secret key or an access_token as a parameter to my url? I have tried both and both seem to time out after 60 requests instead the 5000 the docs say.
I have looked at this site Github Rate Limits but I think I have done what it says.
Do I need to add a token on my server? Like how public and private ssh keys work? - Sorry, just trying to get an understanding of this.
This worked for me recently for getting a list of issues from Github. Nothing else set up on server or similar.
I used a token created with https://github.com/settings/tokens/new
const chalk = require("chalk");
const sa = require("superagent");
const { getProperty } = require("../context");
async function getIssues(org) {
try {
const url = `https://api.github.com/orgs/${org}/issues?state=open`;
const apiToken = await getProperty("github.token");
const res = await sa
.get(url)
.set("Authorization", `token ${apiToken}`)
.send();
res.body.forEach(issue => {
console.log(issue.title);
});
} catch (err) {
console.error(err);
}
}
module.exports = getIssues;

Resources