Polarcraft/web/server/utils/auth.js

51 lines
1.0 KiB
JavaScript

import jwt from 'jsonwebtoken'
const config = useRuntimeConfig()
export const createToken = (accessToken, refreshToken, maxAge, discordId) => {
return jwt.sign({ accessToken, refreshToken, discordId }, 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',
})
}
try {
const coll = db.collection("users")
const user = await coll.findOne({ 'discord.id': decodedToken.discordId })
user.accessToken = decodedToken.accessToken
return user;
} catch (err) {
console.log(err)
throw createError({
statusCode: 500,
statusMessage: 'Error getting user'
})
}
}