Skip to content

Commit

Permalink
Merge pull request #132 from esamarathon/new-twitch-api
Browse files Browse the repository at this point in the history
Updated to new twitch API
  • Loading branch information
zephyyrr authored Apr 4, 2022
2 parents 4cff012 + b4d50f6 commit 5d5053d
Show file tree
Hide file tree
Showing 6 changed files with 184 additions and 147 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ yarn-error.log
**/dist/*.*
frontend/webpack/dist/13f9a2d4f5387c0d185acc223bc8c06b.png
backend/uploads/*
!backend/uploads/.gitkeep
!backend/uploads/.gitkeep
backend/dist/
8 changes: 4 additions & 4 deletions backend/src/api/teams.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ export async function inviteUser(req, res) {
} else {
let userResponse;
try {
userResponse = await twitchGet(`https://api.twitch.tv/kraken/users/${req.body.user}`);
userResponse = await twitchGet(`https://api.twitch.tv/helix/users?id=${req.body.user}`);
console.log('User response:', userResponse);
user = new models.User({
connections: {
twitch: {
name: userResponse.name,
name: userResponse.login,
displayName: userResponse.display_name,
id: userResponse._id,
logo: userResponse.logo
id: userResponse.id,
logo: userResponse.profile_image_url
}
}
});
Expand Down
49 changes: 27 additions & 22 deletions backend/src/api/twitch.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function handleLogin(req, res) {
if (req.cookies['esa-csrf'] && req.cookies['esa-csrf'] === csrf) {
res.clearCookie('esa-csrf');
logger.debug('Logging in...');
const tokenResponse = await httpPost('https://api.twitch.tv/kraken/oauth2/token', {
const tokenResponse = await httpPost('https://id.twitch.tv/oauth2/token', {
body: {
client_id: settings.twitch.clientID,
client_secret: settings.twitch.clientSecret,
Expand All @@ -33,21 +33,26 @@ export async function handleLogin(req, res) {
});
const token = tokenResponse.access_token;
if (!token) throw new Error('Access token could not be received');
const userResponse = await twitchGet('https://api.twitch.tv/kraken/user', null, token);
const userResponse = await twitchGet('https://api.twitch.tv/helix/users', null, token);
console.log('User response:', userResponse);
if (userResponse && userResponse._id) {
if(!userResponse || !userResponse.data || userResponse.data.length === 0) {
res.status(404).end(`User not found`);
return
}
const userData = userResponse.data[0];
if (userData && userData.id) {
// get user
let user = await models.User.findOne({ 'connections.twitch.id': userResponse._id }).exec();
let user = await models.User.findOne({ 'connections.twitch.id': userData.id }).exec();
if (!user) {
user = new models.User({
connections: {
twitch:
{
name: userResponse.name,
displayName: userResponse.display_name,
id: userResponse._id,
logo: userResponse.logo,
email: userResponse.email,
name: userData.login,
displayName: userData.display_name,
id: userData.id,
logo: userData.profile_image_url,
email: userData.email,
oauthToken: token,
refreshToken: tokenResponse.refresh_token,
expiresAt: Date.now() + tokenResponse.expires_in * 1000
Expand All @@ -57,15 +62,15 @@ export async function handleLogin(req, res) {
});
console.log('Created new user', user);
} else {
if (user.connections.twitch.name !== userResponse.name) {
user.connections.twitch.name = userResponse.name;
logger.info(`User ${user.connections.twitch.name} (id: ${userResponse._id}) changed their name to ${userResponse.name}`);
if (user.connections.twitch.name !== userData.login) {
user.connections.twitch.name = userData.login;
logger.info(`User ${user.connections.twitch.name} (id: ${userData.id}) changed their name to ${userData.login}`);
}
user.connections.twitch.displayName = userResponse.display_name;
user.connections.twitch.logo = userResponse.logo;
if (user.connections.twitch.email !== userResponse.email) {
user.connections.twitch.email = userResponse.email;
logger.info(`User ${user.connections.twitch.name} (id: ${userResponse._id}) changed their email to ${userResponse.email}`);
user.connections.twitch.displayName = userData.display_name;
user.connections.twitch.logo = userData.profile_image_url;
if (user.connections.twitch.email !== userData.email) {
user.connections.twitch.email = userData.email;
logger.info(`User ${user.connections.twitch.name} (id: ${userData.id}) changed their email to ${userData.email}`);
}
user.connections.twitch.oauthToken = token;
user.connections.twitch.refreshToken = tokenResponse.refresh_token;
Expand All @@ -74,7 +79,7 @@ export async function handleLogin(req, res) {
}

console.log('Default Admins:', settings.defaultAdmins);
if (settings.defaultAdmins.includes(userResponse._id) && user.roles.length === 0) {
if (settings.defaultAdmins.includes(userData.id) && user.roles.length === 0) {
const adminRole = await models.Role.findOne({ permissions: '*' }).exec();
if (adminRole) {
logger.info('Making user', user, 'an admin!');
Expand All @@ -89,15 +94,15 @@ export async function handleLogin(req, res) {

await user.save();

const jwt = generateToken(token, { twitchID: userResponse._id, name: user.name, id: user._id });
const jwt = generateToken(token, { twitchID: userData.id, name: user.name, id: user._id });
res.cookie('esa-jwt', jwt, settings.auth.cookieOptions);

console.log('Redirecting to', redirectUrl);
res.redirect(redirectUrl);
return;
} else {
res.redirect(`${settings.frontend.baseurl}${historySep}dashboard/profile?twitch_linked=0&error=Invalid%20data%20returned%20`);
}
res.redirect(redirectUrl);
return;
return
}
res.redirect(`${settings.frontend.baseurl}${historySep}dashboard/profile?twitch_linked=0&error=CSRF%20Token%20invalid`);
return;
Expand Down
18 changes: 6 additions & 12 deletions backend/src/twitchAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,21 @@ import { throttleAsync, httpReq } from './helpers';
export function twitchGet(url, headers, token, query) {
if (!headers) headers = {};
headers['Client-ID'] = settings.twitch.clientID;
if (token) headers.authorization = `OAuth ${token}`;
if (!headers.accept) headers.accept = 'application/vnd.twitchtv.v5+json';
logger.debug(`Getting ${url}`);
if (token) headers.authorization = `Bearer ${token}`;
if (!headers.accept) headers.accept = 'application/json';
if(token) logger.debug(`Getting ${url} with token`);
else logger.debug(`Getting ${url}`);
return httpReq(url, { headers, query });
}

export function twitchPost(url, headers, token, body) {
if (!headers) headers = {};
headers['Client-ID'] = settings.twitch.clientID;
if (token) headers.authorization = `OAuth ${token}`;
if (!headers.accept) headers.accept = 'application/vnd.twitchtv.v5+json';
if (token) headers.authorization = `Bearer ${token}`;
if (!headers.accept) headers.accept = 'application/json';
logger.debug(`Posting to ${url}`);
return httpReq(url, { headers, body });
}
const userIDByName = {};
export async function twitchGetIDByName(userName) {
if (userIDByName[userName]) return userIDByName[userName];
const userResponse = await twitchGet(`https://api.twitch.tv/kraken/users/?login=${userName}`);
userIDByName[userName] = userResponse.users[0]._id;
return userIDByName[userName];
}

export async function twitchGQL(query, variables) {
return twitchPost('https://api.twitch.tv/gql', null, null, { query, variables, extensions: {} });
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/components/dashboard/submissionedit.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ function findTeamName(teams) {
}

async function searchForName(search) {
const data = await makeTwitchRequest(`https://api.twitch.tv/kraken/search/channels?query=${encodeURIComponent(search)}`);
return data.channels;
const data = await makeTwitchRequest(`https://api.twitch.tv/helix/search/channels?query=${encodeURIComponent(search)}&first=100`);
return data.data;
}
async function searchForGame(search) {
const data = await makeTwitchRequest(`https://api.twitch.tv/kraken/search/games?query=${encodeURIComponent(search)}`);
return data.games;
const data = await makeTwitchRequest(`https://api.twitch.tv/helix/search/games?query=${encodeURIComponent(search)}&first=100`);
return data.data;
}

function getDisplayName(user) {
Expand Down
Loading

0 comments on commit 5d5053d

Please sign in to comment.