2023-06-05 10:17:35 +02:00
|
|
|
import * as jwt from 'jsonwebtoken'
|
|
|
|
|
|
|
|
interface IDecodedToken {
|
|
|
|
discordId: string,
|
2023-06-05 22:41:48 +02:00
|
|
|
userId: string,
|
2023-06-05 10:17:35 +02:00
|
|
|
accessToken: string,
|
|
|
|
refreshToken: string
|
|
|
|
}
|
|
|
|
|
2023-06-05 22:41:48 +02:00
|
|
|
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 {
|
2023-06-05 22:41:48 +02:00
|
|
|
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'
|
|
|
|
})
|
|
|
|
}
|
2023-06-05 22:41:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2023-06-05 22:41:48 +02:00
|
|
|
const user = await UserModel.findById(userId)
|
2023-06-05 10:17:35 +02:00
|
|
|
|
|
|
|
if (!user) {
|
2023-06-05 22:41:48 +02:00
|
|
|
throw createError({ statusCode: 400, statusMessage: 'No user was found' })
|
2023-06-05 10:17:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return user
|
|
|
|
} catch (e) {
|
2023-06-05 22:41:48 +02:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|