discord Oauth2 access token undefined - node.js

So i am trying to create a discord bot dashboard and I am including a Discord Oauth2 to get User information. My Discord Oauth2 works, however after authorising, it redirects me to the homepage but the URL has token=undefined . The console does log "It works!". How do I fix the undefined access token?
http://localhost:3000/?token=undefined
var path = require('path');
const express = require('express');
const fetch = require('node-fetch');
const app = express();
require('dotenv').config();
const btoa = require('btoa');
const { catchAsync } = require('./utils.js')
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect = encodeURIComponent('http://localhost:3000/callback');
...
app.get('/login', (req, res) => {
res.redirect(`https://discord.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${redirect}&response_type=code&scope=identify%20email%20guilds`);
});
app.get('/callback', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
const json = await response.json();
console.log("it works!")
res.redirect(`/?token=${json.access_token}`);
}));
app.listen(3000)

There seemed to be a problem with how the callback link was set up, So I changed it to look like this and it works.
app.get('/callback', catchAsync(async (req, res) => {
const data = {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: 'authorization_code',
redirect_uri: redirect,
code: req.query.code,
scope: ['identify', 'email', 'guilds'],
};
const response = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
const json = await response.json();
const fetchDiscordUserInfo = await fetch('http://discordapp.com/api/users/#me', {
headers: {
Authorization: `Bearer ${json.access_token}`,
}
});
const userInfo = await fetchDiscordUserInfo.json();
res.redirect('http://localhost:3000/dashboard')
console.log(userInfo);

Related

Twitch API returning "Redirect URI does not match registered URI"

I am having a weird issue where Twitch's API isn't recognizing that both, the redirect URI in my code and the URI I provided are the same.
The exact error is
Parameter redirect_uri does not match registered URI
On the Twitch API dashboard, I have two URI endpoints:
http://localhost:8888/auth/twitch/callback and
http://localhost:8888/auth/twitch/
I have both my Twitch AUTH API and my Express server code below.
TWITCH API
const express = require('express');
const axios = require('axios');
const config = require('../config.js');
const router = express.Router();
const authBaseURL = `https://id.twitch.tv/oauth2`;
const redirect_uri = `/auth/twitch/callback`; //${config.TWITCH_CLIENT_REDIR_HOST}
const authenticationAPI = axios.create({
baseURL: authBaseURL,
});
router.get('/', (req, res) => {
const qs = new URLSearchParams({
client_id: config.TWITCH_CLIENT_ID,
redirect_uri,
response_type: 'code',
scope: req.query.scope,
});
const redirectUrl = `${authBaseURL}/authorize?${qs}`;
res.redirect(redirectUrl);
});
router.get('/callback', async (req, res) => {
const { code, state } = req.query;
const qs = new URLSearchParams({
client_id: config.TWITCH_CLIENT_ID,
client_secret: config.TWITCH_CLIENT_SECRET,
code,
grant_type: 'authorization_code',
redirect_uri,
});
try {
const response = await authenticationAPI.post(`/token?${qs}`);
res.json({
expires_in: response.data.expires_in,
scope: response.data.scope,
token_type: response.data.token_type,
});
} catch (error) {
res.json({
message: error.message,
body: error.response.data,
// client_id: config.TWITCH_CLIENT_ID,
// client_secret: config.TWITCH_CLIENT_SECRET,
// client_redirect_host: config.TWITCH_CLIENT_REDIR_HOST,
});
}
});
module.exports = router;
// TEST URL - http://localhost:8888/auth/twitch?scope=chat:edit+chat:read+whispers:read
If you have a solution or any help you can provide, it is greatly appreciated!
Thank you in advance!

invaild_client while requesting the access token from discord

I want to create a login system with discord and I think I'm doing everything fine
but it's still not working.
This is my code:
require("dotenv").config();
const cookieSession = require("cookie-session");
const express = require("express");
const fetch = require("node-fetch");
const PORT = process.env.PORT;
const app = express();
const AUTH_URL = "https://discord.com/api/oauth2/authorize?client_id=928706322701119528&redirect_uri=http%3A%2F%2Flocalhost%3A4044%2Fapi%2Fauth%2Fcallback&response_type=code&scope=identify";
const params = new URLSearchParams({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
grant_type: "authorization_code",
redirect_uri: encodeURI("http://localhost:4044/api/auth"),
scope: "identify"
});
app.use(express.static(path.join(__dirname, "public")))
app.use(cookieSession({
name: "pprp",
keys: [
"abcde"
],
maxAge: 24 * 60 * 60 * 1000
}));
app.get("/", (req, res) => {
res.redirect(AUTH_URL);
});
app.get("/api/auth/callback", (req, res) => {
const code = req.query.code;
if(!code) return res.send("Invalid code");
params.append("code", encodeURI(code));
console.log("https://discord.com/api/oauth2/token?" + params.toString())
fetch("https://discord.com/api/oauth2/token?" + params.toString(), {
method: "post",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(response => response.json()).then(data => console.log(data)); // Here it's prints { error: 'invalid_client' }
});
app.listen(PORT, () => console.log(`Listening on ${PORT}`))
but in line 47 it's retuning invaild_client in the request and I don't know why
I tried to check if the client_id is undefined or the client_secret I tried to switch applications.

Fetching twilio api from node js is not working & throwing error

In this code i have added express endpoints to get twilio endpoints
const config = require("./config");
const express = require("express");
const bodyParser = require("body-parser");
const pino = require("express-pino-logger")();
const { videoToken } = require("./tokens");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
const sendTokenResponse = (token, res) => {
res.set("Content-Type", "application/json");
res.send(
JSON.stringify({
token: token.toJwt(),
})
);
};
app.post("/video/token", (req, res) => {
const identity = req.body.identity;
const room = req.body.room;
const token = videoToken(identity, room, config);
sendTokenResponse(token, res);
});
In this code i have added function to fetch twilio endpoints but i don't know why it's throwing error of JSON unexpected token at position 0 maybe it's twilio error
const handleSubmit = useCallback(async () => {
setConnecting(true);
const data = await fetch("/video/token", {
method: "POST",
body: JSON.stringify({
identity: username,
room: roomName,
}),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
}).then((res) => res.json());
Video.connect(data.token, {
name: roomName,
})
.then((room) => {
setConnecting(false);
setRoom(room);
})
.catch((err) => {
console.error(err);
setConnecting(false);
});
}, [roomName, username]);

Functions in Nodejs

I am new to Nodejs and am trying to figure out why I cannot pass the returned value of my function into my function when I call it. Here is my code:
const SpotifyWebApi = require('spotify-web-api-node');
const http = require("http");
const request = require('request');
const querystring = require('querystring');
const { post } = require('request');
const express = require('express');
const { response } = require('express');
const https = require('follow-redirects').https;
//sets express server vars
const app = express()
const port = 8080
app.get('/', (req, res) => {
res.send('Server Connected')
})
app.listen(port, () => {
console.log(`Now serving on ${port} at ${process.env.URI} `)
})
require('dotenv').config();
//authenticate to SpotifyAPI
var spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.SECRET_ID,
redirectUri: process.env.URI,
});
const scope = 'user-read-private user-read-email ';
const authUrl = 'https://accounts.spotify.com/api/token?grant_type=client_credentials';
//Headers needed to auth to SpotifyAPI for Bearer token
const tokenHeaders = {
'Authorization': process.env.ACCESSTOKEN,
'Content-Type': 'application/x-www-form-urlencoded',
};
//spotify Auth Payload
const options = {
'method': 'POST',
'url': authUrl,
'headers': tokenHeaders
};
function accessTokenAuth(bearerToken){
request(options, (error, response) => {
if (error) throw new Error(error);
const accessTokenBody = response.body;
// console.log(accessTokenBody)
// console.log(request)
const obj = JSON.parse(accessTokenBody);
const bearerToken = ("Bearer " + obj.access_token); //add this bearerAuth part to a function to make it repeatable. Times out in 3600???
// console.log(bearerToken);
return bearerToken;
});
}
//Add first playlists request using the bearer token
accessTokenAuth(bearerToken);
In the function "accessTokenAuth" I create a series of calls that essentially posts data from the above dictionaries into a function that then sends the data to the URL to receive a token back. My question is this, at the bottom of the function when I return "bearerToken", how come I cannot pass "bearerToken" into the function when I call it on line 67. Also, when I comment out calling the function and just run the program it prints out the "bearerToken" when I console.log it in the function. Why is this possible? Aren't you not able to access the function unless it is called?
Thank you!

invalid_request post to access Token

I have problem with post request authentification while trying to run the code I get error invalide request does anyone know how I could solve this problem, I get this error { error: 'invalid_request' }
const express = require('express');
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('./utils');
const router = express.Router();
const CLIENT_ID = 'CLIENT_ID ';
const CLIENT_SECRET = 'CLIENT_SECRET';
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const redirect = encodeURIComponent('http://localhost:50451/callback');
router.get('/login', (req, res) => {
res.redirect('https://flow.polar.com/oauth2/authorization?response_type=code&client_id=client_id');
});
router.get('/list', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
fetch('https://polarremote.com/v2/oauth2/token', {
method: 'POST',
data : {
'grant_type' : 'authorization_code',
'redirect_uri' : redirect,
'code' : code
},
headers : {
'Authorization':`Basic ${creds}`,
'Content-Type':'application/x-www-form-urlencoded',
'Accept':' application/json;charset=UTF-8'
}
})
.then(function(response) {
return response.json();
console.log(response.json());
}).then(function(body) {
console.log(body);
res.send('POST');
});
})

Resources