Polarcraft/webv2/server/utils/user.ts
Xeovalyte f9c13e5ada
All checks were successful
Build and Deploy / Deploy Web (push) Successful in 1m3s
Build and Deploy / Deploy Discord Bot (push) Successful in 43s
feat: Added team leave
2023-06-06 18:22:36 +02:00

61 lines
1.4 KiB
TypeScript

import * as jwt from 'jsonwebtoken'
interface IDecodedToken {
discordId: string,
userId: string,
accessToken: string,
refreshToken: string
}
export const getAuth = (event: any) => {
const token = getCookie(event, 'jwt') || null
if (!token) {
throw createError({ statusCode: 401, statusMessage: 'JWT token is invalid' })
}
try {
return jwt.verify(token, config.jwtSecret) as IDecodedToken
} catch (e) {
console.error('Failed to verify JWT token', e)
throw createError({
statusCode: 401,
statusMessage: 'JWT token is invalid'
})
}
}
export const getUser = async (userId: string, event: any) => {
if (userId === '@me') {
const auth = getAuth(event)
userId = auth.userId
}
try {
const user = await UserModel.findById(userId).populate('team')
if (!user) {
throw createError({ statusCode: 400, statusMessage: 'No user was found' })
}
return user
} catch (e) {
console.error('Failed to get user by id', e)
throw createError({ statusCode: 500, statusMessage: 'Failed to get user' })
}
}
export const applyUsername = async (user: IUser) => {
if (user.usernameType === 'discord' || user.$isEmpty('minecraft') || !user.minecraft) {
user.username = user.discord.username
await user.save()
} else {
user.username = user.minecraft.username
await user.save()
}
}