Polarcraft/webv2/server/utils/user.ts

61 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-06-05 10:17:35 +02:00
import * as jwt from 'jsonwebtoken'
interface IDecodedToken {
discordId: string,
userId: string,
2023-06-05 10:17:35 +02:00
accessToken: string,
refreshToken: string
}
export const getAuth = (event: any) => {
2023-06-05 10:17:35 +02:00
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
2023-06-05 10:17:35 +02:00
} 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
}
2023-06-05 10:17:35 +02:00
try {
const user = await UserModel.findById(userId)
2023-06-05 10:17:35 +02:00
if (!user) {
throw createError({ statusCode: 400, statusMessage: 'No user was found' })
2023-06-05 10:17:35 +02:00
}
return user
} catch (e) {
console.error('Failed to get user by id', e)
2023-06-05 10:17:35 +02:00
throw createError({ statusCode: 500, statusMessage: 'Failed to get user' })
}
}
2023-06-06 13:49:27 +02:00
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()
}
}