Polarcraft/web/server/utils/auth.js

51 lines
1.0 KiB
JavaScript
Raw Normal View History

2023-04-23 10:15:25 +02:00
import jwt from 'jsonwebtoken'
const config = useRuntimeConfig()
2023-04-25 15:51:20 +02:00
export const createToken = (accessToken, refreshToken, maxAge, discordId) => {
return jwt.sign({ accessToken, refreshToken, discordId }, config.jwtSecret, {
2023-04-23 10:15:25 +02:00
expiresIn: maxAge,
})
}
2023-04-25 15:51:20 +02:00
2023-04-23 17:16:53 +02:00
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")
2023-04-25 15:51:20 +02:00
const user = await coll.findOne({ 'discord.id': decodedToken.discordId })
2023-04-23 17:16:53 +02:00
2023-05-09 15:23:31 +02:00
user.accessToken = decodedToken.accessToken
2023-04-23 17:16:53 +02:00
return user;
} catch (err) {
console.log(err)
throw createError({
statusCode: 500,
statusMessage: 'Error getting user'
})
}
}