hermes-web/lib/twitch.ts

79 lines
2.4 KiB
TypeScript
Raw Normal View History

import axios from 'axios'
import { db } from "@/lib/db"
export async function TwitchUpdateAuthorization(userId: string) {
try {
const connection = await db.twitchConnection.findFirst({
where: {
userId
}
})
if (!connection) {
return null
}
try {
const { expires_in }: { client_id:string, login:string, scopes:string[], user_id:string, expires_in:number } = (await axios.get("https://id.twitch.tv/oauth2/validate", {
headers: {
Authorization: 'OAuth ' + connection.accessToken
}
})).data;
if (expires_in > 3600) {
const data = await db.twitchConnection.findFirst({
where: {
userId
}
})
const dataFormatted = {
user_id: userId,
access_token: data?.accessToken,
refresh_token: data?.refreshToken,
broadcaster_id: connection.broadcasterId,
expires_in
}
return dataFormatted;
}
} catch (error) {
}
// Post to https://id.twitch.tv/oauth2/token
const token: { access_token:string, expires_in:number, refresh_token:string, token_type:string, scope:string[] } = (await axios.post("https://id.twitch.tv/oauth2/token", {
client_id: process.env.TWITCH_BOT_CLIENT_ID,
client_secret: process.env.TWITCH_BOT_CLIENT_SECRET,
grant_type: "refresh_token",
refresh_token: connection.refreshToken
})).data
// Fetch values from token.
const { access_token, expires_in, refresh_token, token_type } = token
if (!access_token || !refresh_token || token_type !== "bearer") {
return null
}
await db.twitchConnection.update({
where: {
userId
},
data: {
accessToken: access_token,
refreshToken: refresh_token
}
})
const data = {
user_id: userId,
access_token,
refresh_token,
broadcaster_id: connection.broadcasterId,
expires_in
}
return data
} catch (error) {
console.log("[ACCOUNT]", error);
return null
}
}