How to check If a twitch streamer is live? - javascript

I was trying to check if a twitch streamer is live or not but when I tried it gave me a error.
here is my code:
async function isStreamerLive(username) {
const theUrl = `https://api.twitch.tv/helix/streams?user_login=${username}`
const headers = {
"Client-Id": 'ID', //hidden
"Authorization": 'TOKEN', //hidden
};
const response = await fetch(theUrl, headers);
const data = await response.json();
console.log(data)
return data?.data?.find(s => s.user_login === username.toLocaleLowerCase())
}
let username = 'kaicenat'
isStreamerLive(username)
Output:
{
error: 'Unauthorized',
status: 401,
message: 'OAuth token is missing'
}
Why is it saying OAuth token is missing?
I am also providing client id and token when I tried code.

Related

Invalid signature error when trying to refresh a token

I have this weird error every time I try to refresh a token after the session token expired
{ success: false, message: 'invalid signature' }
This is the function where I try to refresh my token:
async function updateToken(currentToken, refreshToken) {
const response = await fetch(`${basePath}/auth/token`, {
method: 'GET',
headers: getTokenAndRefreshAuthHeaders(currentToken, refreshToken)
});
const token = await response.json();
await saveTokenInLocalStorage(token);
return token;
}
This is the /token endpoint:
router.get('/token', async (req, res) => {
try {
const token = await TokenController.getTokenFromRequest(req);
const refreshToken = await TokenController.getRefreshTokenFromRequest(req);
await TokenController.verifyRefreshToken(refreshToken);
const decoded = jwt.decode(token);
res.json({
token: TokenController.generateToken(decoded.email, decoded.type, decoded.id)
});
} catch (error) {
ErrorController.errorCallback(error, res);
}
});
and this is my getTokenFromRequest function:
static getTokenFromRequest(req) {
let token = req.body.token || req.headers['x-access-token'] || req.headers['authorization'] || req.params.token;
return TokenController.getNormalizedToken(token);
}
I'm not sure what I'm doing wrong, some console.log() that I placed in those 3 places suggest that the culprit is the getTokenFromRequest but I'm not quite sure

Discord oauth2 /users/#me/guilds error 401

It is supposed to get all the guilds a user is joined in. It gets the bearer auth right, but it always errors with code 401. When using a external API (https://reqbin.com/) with auth to test the discord API it also gives the same error 401.
This is the code:
let discordCode = window.location.href
let code = discordCode.split("?code=")
if(code && code.length > 0){
discordCode = code[code.length-1]
}
console.log(discordCode)
fetch("https://discord.com/api/users/#me/guilds",{method: 'GET',headers: {
"Authorization": `Bearer ${discordCode}`,
}}).then(function(response) {
response.json().then((result) => {
console.log(result)
})
})
/*fetch(`/discordProxy/${discordCode}`).then(function(response) {
response.json().then((result) => {
console.log(result)
})
})*/
$("#connect_top_button").click(function(){
window.location.href = "https://discord.com/api/oauth2/authorize?client_id=955915443405729844&redirect_uri=http%3A%2F%2F130.162.37.209%2Fservers&response_type=code&scope=identify%20guilds"
})
The oauth2 scopes I gave to the app are: identify, email, guilds
Edit: Actually, it seems that all the auth tokens from the oauth2 don't work. Weird
You must get discord token and use it in authorization:
"Authorization": `Bearer ${await getTokenDiscord()}`
here is my example of getting the discord token:
async getTokenDiscord() {
const params = new URLSearchParams()
params.append('client_id', CLIENT_ID)
params.append('client_secret', CLIENT_SECRET)
params.append('grant_type', 'authorization_code')
params.append('code', YOUR_DISCORD_CODE)
params.append('redirect_uri', REDIRECT_URL)
params.append('scope', 'identify')
const resp = await fetch('https://discord.com/api/oauth2/token', {
method: 'post',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json'
}
})
return await resp.json()
}
It's not the best example of how to do this, but it's the way it works for me

is there anyway i can refresh spotify token in react?

I create a function that I can log in to my Spotify and get the access token and I create a function to refresh my token but it does not work properly when I pass it to the request function with Axios and it returns 400 or 404.
what should I do ?
here is my code :
const AUTH_URL =
" https://accounts.spotify.com/authorize?client_id=MY_ID&response_type=token&redirect_uri=http://localhost:3000/&scope=user-read-playback-state";
let Login = () => {
const spotifyHandle = (params) => {
const afterHashtag = params.substring(1);
const param = afterHashtag.split("&");
const paramsSplit = param.reduce((Para, currentPara) => {
const [key, value] = currentPara.split("=");
Para[key] = value;
return Para;
}, {});
return paramsSplit;
};
useEffect(() => {
if (window.location.hash) {
const { access_token, expires_in } = spotifyHandle(window.location.hash);
localStorage.clear();
localStorage.setItem("accessToken", access_token);
localStorage.setItem("expiresIn", expires_in);
}
});
return (
<div>
<a href={AUTH_URL}>
<button>Login</button>
</a>
</div>
);
};
here the refresh function:
let refresh = async () => {
const clientId = "id";
const clientSecret = "secret";
const headers = {
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: clientId,
password: clientSecret,
},
};
const data = {
grant_type: "client_credentials",
};
try {
const response = await axios.post(
"https://accounts.spotify.com/api/token",
qs.stringify(data),
headers
);
console.log(response.data.access_token);
return response.data.access_token;
} catch (error) {
console.log(error);
}
};
The Spotify API follows the OAuth 2.0 specs and it requires (as presented at this Spotify's documentation section):
grant_type to be equal to authorization_code
code to be equal to the authorization code returned from the initial request to the Account /authorize endpoint
redirect_uri This parameter is used for validation only (there is no actual redirection). The value of this parameter must exactly match the value of redirect_uri supplied when requesting the authorization code.
And a Authorization is also required at the request header, as stated at the docs:
Base 64 encoded string that contains the client ID and client secret key. The field must have the format: Authorization: Basic *<base64 encoded client_id:client_secret>*

Session cookie from node-fetch is invalid?

I am writing a javascript program (for a github action) right now but ran into a problem.
I was trying to log into www.overleaf.com and access the page https://www.overleaf.com/project after generating a session cookie by sending a POST request to https://www.overleaf.com/login with my credentials and the csrf token.
The response contained the requested token in the set-cookie header as expected, however, when I tried to access https://www.overleaf.com/project via GET, I get redirected back to https://www.overleaf.com/login
When copying a session cookie saved in my browser, the request works just fine as expected.
I tried doing the same thing in the command line with cURL and it worked there.
I am fairly certain my authentication request is accepted by Overleaf's server, because I have tried intentionally incorrectly sending the password or the csrf token and in both cases, the response does not give me a new session cookie but sends the old one.
If anyone has any clue what is going wrong, I'd be very thankful for your input.
This is what worked in the terminal, which I'm trying to replicate in javascript with node-fetch:
curl -v --header "Content-Type: application/json" --cookie "GCLB=someothercookie;overleaf_session2=firstsessioncookie" --data '{"_csrf":"the_csrf_token", "email": "MYEMAIL", "password":"MYPASSWORD"}' https://www.overleaf.com/login
to get the cookie and csrf token and
curl -v https://www.overleaf.com/project --cookie "overleaf_session2=returnedsessioncookie; GCLB=someothercookie" as the request that returns the html page of my projects.
This is my javascript code, I have double, triple, quadruple checked it but I think I'm missing something.
const fetch = require("node-fetch");
const parser = require("node-html-parser");
const scparser = require("set-cookie-parser");
async function run() {
const email = process.env.EMAIL;
const password = process.env.PASSWORD;
var cookies = await login(email, password);
console.log(await all_projects(cookies));
}
async function login(email, password) {
const login_get = await fetch("https://www.overleaf.com/login");
const get_cookies = login_get.headers.raw()["set-cookie"];
const parsed_get_cookies = scparser.parse(get_cookies, {
decodeValues: false
});
const overleaf_session2_get = parsed_get_cookies.find(
(element) => element.name == "overleaf_session2"
).value;
const gclb = parsed_get_cookies.find(
(element) => element.name == "GCLB"
).value;
console.log("overleaf_session2_get:", overleaf_session2_get, "gclb:", gclb);
const get_responsetext = await login_get.text();
const _csrf = parser
.parse(get_responsetext)
.querySelector("input[name=_csrf]")
.getAttribute("value");
login_json = { _csrf: _csrf, email: email, password: password };
console.log(login_json);
const login_post = await fetch("https://www.overleaf.com/login", {
method: "post",
body: JSON.stringify(login_json),
headers: {
"Content-Type": "application/json",
"Cookie": "GCLB=" + gclb + ";overleaf_session2=" + overleaf_session2_get
}
});
const post_cookies = login_post.headers.raw()["set-cookie"];
const parsed_post_cookies = scparser.parse(post_cookies, {
decodeValues: false
});
const overleaf_session2_post = parsed_post_cookies.find(
(element) => element.name == "overleaf_session2"
).value;
console.log(
"successful:",
overleaf_session2_get != overleaf_session2_post ? "true" : "false"
);
console.log(await fetch("https://www.overleaf.com/project", {
headers: {
"Cookie": "overleaf_session2=" + overleaf_session2_post
}
}))
return "overleaf_session2=" + overleaf_session2_post;
}
async function all_projects(cookies) {
const res = await fetch("https://www.overleaf.com/project", {
headers: {
Cookie: cookies
}
});
return res;
}
run();
Yes your authentication request is probably valid however this is likely to be a security issue which browsers do not allow you to do such thing and freely access another website's cookie.
Browsers do not allow you to access other domain's cookies, If they did then web would be an unsafe place because for example Stackoverflow could access my Facebook account cookie and extract my personal information.
I fixed my issue by not using node-fetch and switching to https.
Here is what worked:
async function login(email, password) {
//GET login page
const get = await get_login();
//get necessary info from response
const csrf = parser
.parse(get.html)
.querySelector(`meta[name="ol-csrfToken"]`)
.getAttribute("content");
const session1 = scparser
.parse(get.headers["set-cookie"], { decodeValues: false })
.find((cookie) => cookie.name == "overleaf_session2").value;
const gclb = scparser
.parse(get.headers["set-cookie"], { decodeValues: false })
.find((cookie) => cookie.name == "GCLB").value;
//POST login data
const post = await post_login(csrf, email, password, session1, gclb);
//get necessary data from response
const session2 = scparser
.parse(post["set-cookie"], { decodeValues: false })
.find((cookie) => cookie.name == "overleaf_session2").value;
//GET new csrf token from project page
const projects = await get_projects(session2, gclb);
const csrf2 = parser
.parse(projects.html)
.querySelector(`meta[name="ol-csrfToken"]`)
.getAttribute("content");
//return data
return {
session: session2,
gclb: gclb,
csrf: csrf2,
projects: projects.html
};
}
async function get_login() {
const url = "https://www.overleaf.com/login";
return new Promise((resolve) => {
https.get(url, (res) => {
var data;
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
resolve({ html: data, headers: res.headers });
});
});
});
}
async function get_projects(session2, gclb) {
const url = "https://www.overleaf.com/project";
return new Promise((resolve) => {
https.get(
url,
{ headers: { Cookie: `GCLB=${gclb};overleaf_session2=${session2}` } },
(res) => {
var data;
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
resolve({ html: data, headers: res.headers });
});
}
);
});
}
async function post_login(_csrf, email, password, session1, gclb) {
const url = "https://www.overleaf.com/login";
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Cookie: `GCLB=${gclb};overleaf_session2=${session1}`
}
};
const postData = {
_csrf: _csrf,
email: email,
password: password
};
return new Promise((resolve) => {
var req = https.request(url, options, (res) => {
resolve(res.headers);
});
req.on("error", (e) => {
console.error(e);
});
req.write(JSON.stringify(postData));
req.end();
});
}

Why does my Auth0 API call give a 403 error when trying to delete a user?

I'm trying to integrate Auth0.com, and I've written a function that should unlink an identity and then delete it.
The unlinking works, but I keep getting a 403 error when trying to delete the unlinked identity.
The Auth0 API docs (https://auth0.com/docs/api/management/v2#!/Users/delete_users_by_id) say a 403 error is due to either rate limits, insufficient scopes, or user not matching the bearer token.
I think I added the correct scopes to the auth0 client, I'm very sure I'm not hitting rate limits, so it must be the mismatching bearer token.
But I don't understand how that could be?
Can you take a look at what I have and tell me what's gone wrong?
P.S. In case it matters, I'm using auth0-spa.js not the standard auth0.js. More info here.
This is the code I'm working with:
function(properties, context) {
// Load any data
const domain = context.keys.auth0_domain;
const client_id = context.keys.auth0_client_id;
const connection = properties.connection;
const auth0_user_id = properties.auth0_user_id;
//Do the operation
const auth0 = new Auth0Client({
domain: domain,
client_id: client_id,
audience: `https://${domain}/api/v2/`,
scope: "openid email profile read:current_user update:current_user_identities delete:users delete:current_user",
});
const auth0_user_obj = {
id: auth0_user_id
};
const getUserProfile = async (userId) => {
const token = await auth0.getTokenSilently();
const response = await fetch(
`https://${domain}/api/v2/users/${userId}`, {
headers: {
Authorization: `Bearer ${token}`,
},
}
);
return await response.json();
};
const getSecondaryIdentity = async () => {
const auth0user = await getUserProfile(auth0_user_id);
const secondary_identity = auth0user.identities.find(i => i.connection === connection);
return secondary_identity;
}
const unlinkDeleteAccount = async () => {
const secondaryIdentityObj = await getSecondaryIdentity();
const {
provider,
user_id
} = secondaryIdentityObj;
const accessToken = await auth0.getTokenSilently();
const {
sub
} = await auth0.getUser();
await fetch(
`https://${domain}/api/v2/users/${sub}/identities/${provider}/${user_id}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const secondUserId = provider + '|' + user_id;
await fetch(
`https://${domain}/api/v2/users/${secondUserId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
};
unlinkDeleteAccount();
}

Categories

Resources