Polarcraft/web/server/utils/auth.js

59 lines
1.2 KiB
JavaScript

import jwt from 'jsonwebtoken'
const config = useRuntimeConfig()
export const createToken = (accessToken, refreshToken, maxAge) => {
return jwt.sign({ accessToken, refreshToken }, config.jwtSecret, {
expiresIn: maxAge,
})
}
export const getAuth = async (event) => {
const token = getCookie(event, 'jwt') || null
if (!token) {
throw createError({
statusCode: 401,
statusMessage: 'JWT token invalid',
})
}
const config = useRuntimeConfig()
let decodedToken;
try {
decodedToken = jwt.verify(token, config.jwtSecret)
} catch (err) {
console.log(err)
throw createError({
statusCode: 401,
statusMessage: 'JWT token invalid',
})
}
let userResult;
try {
userResult = await $fetch('https://discord.com/api/users/@me', {
headers: {
authorization: `Bearer ${decodedToken.accessToken}`
}
})
} catch (e) {
console.log(e)
}
try {
const coll = db.collection("users")
const user = await coll.findOne({ 'discord.id': userResult.id })
return user;
} catch (err) {
console.log(err)
throw createError({
statusCode: 500,
statusMessage: 'Error getting user'
})
}
}