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

53 lines
1.6 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'
}
})
2023-04-23 17:16:53 +02:00
const userResult = await $fetch('https://discord.com/api/users/@me', {
headers: {
authorization: `Bearer ${tokenResponseData.access_token}`
}
})
const coll = db.collection('users')
const doc = {
discord: {
id: userResult.id,
username: userResult.username,
avatarHash: userResult.avatar || null
},
}
await coll.updateOne({ 'discord.id': userResult.id }, { $set: doc, $setOnInsert: { minecraft: { uuid: null, username: null }, team: null } }, { upsert: true })
2023-04-23 10:15:25 +02:00
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)
});