Polarcraft/web/server/utils/auth.js

51 lines
1.1 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,
2023-05-09 16:01:19 +02:00
statusMessage: 'JWT token is niet geldig',
2023-04-23 17:16:53 +02:00
})
}
const config = useRuntimeConfig()
let decodedToken;
try {
decodedToken = jwt.verify(token, config.jwtSecret)
} catch (err) {
console.log(err)
throw createError({
statusCode: 401,
2023-05-09 16:01:19 +02:00
statusMessage: 'JWT token is niet geldig',
2023-04-23 17:16:53 +02:00
})
}
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,
2023-05-09 16:01:19 +02:00
statusMessage: 'Error tijdens ophalen van gegevens'
2023-04-23 17:16:53 +02:00
})
}
}