35 lines
1.0 KiB
JavaScript
35 lines
1.0 KiB
JavaScript
|
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)
|
||
|
});
|