atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
973 stars 91 forks source link

feat(webauthn): add event to validateUser to track authenticated users #287

Closed atinux closed 6 days ago

atinux commented 6 days ago

resolves #272

By giving the event as 2nd argument to validateUser(userBody, event), we can now check if the user is authenticated to check if the user.userName is part of the userSession.

Example:

export default defineWebAuthnRegisterEventHandler({
  // optional
  async validateUser(userBody, event) {
    // bonus: check if the user is already authenticated to link a credential to his account
    // We first check if the user is already authenticated by getting the session
    // And verify that the email is the same as the one in session
    const session = await getUserSession(event)
    if (session.user?.email && session.user.email !== body.userName) {
      throw createError({ statusCode: 400, message: 'Email not matching curent session' })
    }

    // If he registers a new account with credentials
    return z.object({
      // we want the userName to be a valid email
      userName: z.string().email() 
    }).parse(userBody)
  },
  // ...
})

On the frontend, we can give the email as part of the userName:

<script setup lang="ts">

const { user } = useUserSession()
const { register } = useWebAuthn()

async function registerPasskeyForUser() {
  register({ userName: user.value.email })
}
</script>
pkg-pr-new[bot] commented 6 days ago

Open in Stackblitz

pnpm add https://pkg.pr.new/atinux/nuxt-auth-utils@287

commit: 8eacfb3