feat: Added get user by id, closes #18
This commit is contained in:
parent
b17771755d
commit
12e92b8106
@ -1,4 +1,4 @@
|
||||
import jwt from 'jsonwebtoken'
|
||||
import * as jwt from 'jsonwebtoken'
|
||||
|
||||
type AccessTokenResponse = {
|
||||
access_token: string,
|
||||
|
@ -1,5 +1,21 @@
|
||||
export default defineEventHandler((event) => {
|
||||
return {
|
||||
hello: 'world'
|
||||
export default defineEventHandler(async (event) => {
|
||||
const userId: string = event.context.params ? event.context.params.id : '@me'
|
||||
|
||||
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' })
|
||||
}
|
||||
})
|
||||
|
43
webv2/server/utils/user.ts
Normal file
43
webv2/server/utils/user.ts
Normal 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' })
|
||||
}
|
||||
}
|
1
webv2/types/global.d.ts
vendored
1
webv2/types/global.d.ts
vendored
@ -19,5 +19,6 @@ declare global {
|
||||
moderator: boolean,
|
||||
},
|
||||
teamId: string,
|
||||
accessToken?: string
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user