I’ve pasted samples of the route that generates the initial authorization url and the callback route as well. However, let me be clear, the callback route is not being initiated at all. At the top of the middleware chain is a request logger. I am seeing the initial GET request to /auth on my API that generates the initial auth URL, but after that loads in the browser and requests user approval, I get the ‘something went wrong’ screen and there is no GET request to /oauthcb (the callback redirect URI) being logged (or any request period). When I was attempting to manually generate the signature rather than using the client I was at least successful in triggering a GET request to /oauthcb but now it appears after authentication on the twitter side that is no longer happening. I changed nothing about the logging/routes in between those two stages, so either something is wrong with my initial auth URL request that should trigger the callback, or something is breaking internally on the twitter side after the authentication BEFORE it makes the callback GET request.
Code snippets:
Logger (first thing that should see the callback and is not logging any callback GET request)
// request logger
app.use((req, res, next) => {
console.log(`request ${req.method} ${req.url}`);
next();
});
Initial step to request authentication:
//INIT Twitter Client
const client = new TwitterApi({
clientId: process.env.O2_TWITTER_ID,
clientSecret: process.env.O2_TWITTER_SECRET,
});
// authenticator url
app.get('/api/twitter/auth', async (req, res) => {
const authLink = await client.generateOAuth2AuthLink(
'https://www.mettabot.app/api/twitter/oauthcb',
{ scope: ['tweet.read', 'user.read', 'tweet.write', 'offline.access'] }
);
const { url: authUrl, codeVerifier, state } = authLink;
console.log('authlink: ', authLink);
twitCodeVerifier = codeVerifier;
twitState = state;
res.redirect(authUrl);
});
Callback route (never being requested):
// twitter callback url for code request
app.get('/api/twitter/oauthcb', async (req, res) => {
console.log('response from twitter auth request: ', {
body: req.body,
qparams: req.query,
});
try {
const { state, code } = req.query;
const codeVerifier = twitCodeVerifier;
const sessionState = twitState;
if (!codeVerifier || !state || !sessionState || !code) {
return res.status(400).send('App denied or session expired');
}
if (state !== sessionState) {
return res.status(400).send('Stored tokens did not match');
}
client
.loginWithOAuth2({
code,
codeVerifier,
redirectUri: 'https://www.mettabot.app',
})
.then(
async ({
client: loggedClient,
accessToken,
refreshToken,
expiresIn,
}) => {
const newMsg = getMsg();
console.log('message to be tweeted: ', newMsg);
const { data } = await loggedClient.v2.tweet(newMsg);
console.log('data return from tweet attempt: ', data);
}
)
.catch(() => res.status(403).send('Invalid verifier or access tokens!'));
} catch (err) {
console.log(err.message);
res.send(err);
}
});