feat: Added get user by id, closes #18
All checks were successful
Build and Deploy / Deploy Web (push) Successful in 1m2s
Build and Deploy / Deploy Discord Bot (push) Successful in 44s

This commit is contained in:
Xeovalyte 2023-06-05 10:17:35 +02:00
parent b17771755d
commit 12e92b8106
4 changed files with 64 additions and 4 deletions

View File

@ -1,4 +1,4 @@
import jwt from 'jsonwebtoken' import * as jwt from 'jsonwebtoken'
type AccessTokenResponse = { type AccessTokenResponse = {
access_token: string, access_token: string,

View File

@ -1,5 +1,21 @@
export default defineEventHandler((event) => { export default defineEventHandler(async (event) => {
return { const userId: string = event.context.params ? event.context.params.id : '@me'
hello: 'world'
if (userId === '@me') {
return await getCurrentUser(event)
}
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' })
} }
}) })

View File

@ -0,0 +1,43 @@
import * as jwt from 'jsonwebtoken'
interface IDecodedToken {
discordId: string,
accessToken: string,
refreshToken: string
}
export const getCurrentUser = async (event: any) => {
const token = getCookie(event, 'jwt') || null
if (!token) {
throw createError({ statusCode: 401, statusMessage: 'JWT token is invalid' })
}
let decodedToken
try {
decodedToken = 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'
})
}
try {
const user = await UserModel.findOne({ 'discord.id': decodedToken.discordId })
if (!user) {
throw createError({ statusCode: 500, statusMessage: 'User query returned null' })
}
user.accessToken = decodedToken.accessToken
return user
} catch (e) {
console.error('Failed to get user', e)
throw createError({ statusCode: 500, statusMessage: 'Failed to get user' })
}
}

View File

@ -19,5 +19,6 @@ declare global {
moderator: boolean, moderator: boolean,
}, },
teamId: string, teamId: string,
accessToken?: string
} }
} }