Skip to content

Commit

Permalink
chore: jwt creation on sign in (#214)
Browse files Browse the repository at this point in the history
  • Loading branch information
hmbanan666 authored Aug 22, 2024
1 parent 302c404 commit 4aeef6a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 9 deletions.
53 changes: 45 additions & 8 deletions apps/website/src/server/api/auth/twitch.get.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import jwt from 'jsonwebtoken'
import type { WebsiteProfile } from '@chat-game/types'
import type { TwitchAccessTokenResponse, WebsiteProfile } from '@chat-game/types'
import { getTokenInfo } from '@twurple/auth'

export default defineEventHandler((event) => {
export default defineEventHandler(async (event) => {
const { public: publicEnv, jwtSecretKey } = useRuntimeConfig()
const query = getQuery(event)

Expand All @@ -13,17 +14,36 @@ export default defineEventHandler((event) => {
}

const code = query.code.toString()
const twitchResponse = await obtainTwitchAccessToken(code)
if (!twitchResponse?.access_token) {
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized',
})
}

log(JSON.stringify(query), code)
const tokenInfo = await getTokenInfo(twitchResponse.access_token)
if (!tokenInfo.userId || !tokenInfo.userName) {
throw createError({
statusCode: 400,
statusMessage: 'Wrong userId or userName',
})
}

const repository = new DBRepository()

const profileInDB = await repository.findOrCreateProfile({
userId: tokenInfo.userId,
userName: tokenInfo.userName,
})

const profile: WebsiteProfile = {
id: '123',
twitchToken: '2134',
twitchId: '1245',
userName: 'tester',
id: profileInDB.id,
twitchId: tokenInfo.userId,
userName: tokenInfo.userName,
}

const token = jwt.sign({ profile }, jwtSecretKey, { expiresIn: '48h' })
const token = jwt.sign({ profile }, jwtSecretKey, { expiresIn: '7d' })

setCookie(event, publicEnv.cookieKey, token, {
path: '/',
Expand All @@ -32,3 +52,20 @@ export default defineEventHandler((event) => {

return sendRedirect(event, '/')
})

async function obtainTwitchAccessToken(code: string) {
const { public: publicEnv, twitchSecretId } = useRuntimeConfig()

try {
const response = await fetch(
`https://id.twitch.tv/oauth2/token?client_id=${publicEnv.twitchClientId}&client_secret=${twitchSecretId}&code=${code}&grant_type=authorization_code&redirect_uri=${publicEnv.signInRedirectUrl}`,
{
method: 'POST',
}
)
return (await response.json()) as TwitchAccessTokenResponse
} catch (err) {
console.error('obtainTwitchAccessToken', err)
return null
}
}
1 change: 0 additions & 1 deletion libs/types/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,6 @@ export interface TwitchAccessToken {

export interface WebsiteProfile {
id: string
twitchToken: string
twitchId: string
userName: string
}

0 comments on commit 4aeef6a

Please sign in to comment.