How use guard in nitro or specific middleware to a route #910
-
i wanna secure |
Beta Was this translation helpful? Give feedback.
Answered by
stafyniaksacha
Feb 5, 2023
Replies: 1 comment
-
You can create your own custom createEventHandler like export interface PrivateContext {
user: Record<string, any>
}
export function definePrivateEventHandler<T>(
handler: (event: H3Event, cxt: PrivateContext) => T,
options: { requireAuth: boolean } = { requireAuth: true }
) {
return defineEventHandler(async (event) => {
// you can check request hmac, user, token, etc..
const token = event.node.req.headers['authorization']
const user = await getUser(token)
if (options.requireAuth && !user) {
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized',
})
}
return handler(event, {
user,
})
})
}) then use it in replacement of export default definePrivateEventHandler(async (event, { user }) => {
//
})
// or public
export default definePrivateEventHandler(async (event, { user }) => {
//
}, { requireAuth: false }) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Cyrs2001
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can create your own custom createEventHandler like
then use it i…