Polarcraft/webv2/server/utils/user.ts
Xeovalyte 3eb4453d71
All checks were successful
Build and Deploy / Deploy Web (push) Successful in 1m5s
Build and Deploy / Deploy Discord Bot (push) Successful in 44s
feat: Added minecraft linking system, closes #29
2023-06-05 22:41:48 +02:00

49 lines
1.0 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)
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' })
}
}