Polarcraft/web/server/api/auth/index.js

35 lines
1.0 KiB
JavaScript
Raw Normal View History

2023-04-23 10:15:25 +02:00
export default defineEventHandler(async (event) => {
const { code } = getQuery(event)
const config = useRuntimeConfig()
if (!code) sendRedirect(event, '/', 302)
try {
const tokenResponseData = await $fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams({
client_id: config.discordId,
client_secret: config.discordSecret,
code: code,
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:3000/api/auth',
scope: 'identify',
}).toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
const token = createToken(tokenResponseData.access_token, tokenResponseData.refresh_token, tokenResponseData.expires_in)
setCookie(event, 'jwt', token, { httpOnly: true, maxAge: tokenResponseData.expires_in * 1000 })
} catch (e) {
console.log(e)
throw createError({ statusCode: 500, statusMessage: 'Error creating login token'})
}
return sendRedirect(event, '/', 302)
});