Polarcraft/web/server/utils/auth.js
2023-05-11 19:46:18 +02:00

64 lines
1.5 KiB
JavaScript

import { ObjectId } from 'mongodb'
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 is niet geldig',
})
}
const config = useRuntimeConfig()
let decodedToken;
try {
decodedToken = jwt.verify(token, config.jwtSecret)
} catch (err) {
console.log(err)
throw createError({
statusCode: 401,
statusMessage: 'JWT token is niet geldig',
})
}
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 tijdens ophalen van gegevens'
})
}
}
export const applyUsername = async (user) => {
const teamsColl = db.collection('teams')
const team = await teamsColl.findOne({ _id: new ObjectId(user.team.id) })
const discordUsername = user.team ? user.username + ' [' + team.name + ']' : user.discord.username
await $fetch(config.discordHost + '/user/changenickname', {
method: 'POST',
body: { nickname: discordUsername, discordId: user.discord.id }
})
}