Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Nov 15, 2024

Conversation

atinux
Copy link
Owner

@atinux atinux commented Nov 15, 2024

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>

Copy link

pkg-pr-new bot commented Nov 15, 2024

Open in Stackblitz

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

commit: 8eacfb3

@atinux atinux merged commit 5392da9 into main Nov 15, 2024
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

How do we link a passkey to an existing user? Since there's only register and authenticate methods
1 participant