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: add hashPassword & verifyPassword server utils #156

Merged
merged 7 commits into from
Sep 25, 2024

Conversation

Barbapapazes
Copy link
Contributor

@Barbapapazes Barbapapazes commented Sep 3, 2024

resolves #155

This PR introduces 2 news utilities that can be used to register and login a user with a password:

  • hashPassword(password)
  • verifyPassword(hashedPassword, password)

This PR is still in draft because I need to rework the current login route (used with predefined password).

  • Move current login to another route (with a better name
  • Reuse login for log in a user after a registration (register).

possible thanks to the work of Atinux (https://github.com/atinux/nuxt-bcrypt-edge)

@carlos-duran
Copy link

Thank you so much for this feature!

I implemented my login endpoint in a similar way, but having it out of the box is really great.

In mi case I had to use await fetch() (await) because I do a navigation and I have an auth middleware in the target page.

// app/pages/login.vue

//...
const { fetch } = useUserSession()

async function onSubmit(event: FormSubmitEvent<LoginDTO>) {
  $fetch("/api/auth/login", { method: "POST", body: event.data })
    .then(async () => {
      await fetch();
      navigateTo("/");
    })
    .catch((error: FetchError) => {
      toast.add({ title: "Error", description: error?.data.message, color: "red" });
    });
}
// server/api/auth/login.post.ts
import { Admin, LoginDTOSchema } from "@app/schemas";

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { data, error } = LoginDTOSchema.safeParse(body);

  if (error) {
    throw createError({
      statusCode: 400,
      message: "Invalid request body",
      data: error.errors,
    });
  }

  const db = useDB();
  const admin = await db.collection<Admin>("admins").findOne({
    email: data.email,
  });

  if (!admin) {
    throw createError({
      statusCode: 401,
      message: "Invalid email or password",
    });
  }

  const isValid = await Bun.password.verify(data.password, admin.password);

  if (!isValid) {
    throw createError({
      statusCode: 401,
      message: "Invalid email or password",
    });
  }

  const { password: _, ...user } = admin;

  await setUserSession(event, { user });

  return {
    message: "Logged in successfully",
  };
});
// app/middleare/auth.global.ts
export default defineNuxtRouteMiddleware((to) => {
  const { loggedIn } = useUserSession();

  if (to.path !== "/login") {
    if (!loggedIn.value) {
      return navigateTo("/login");
    }
  } else {
    if (loggedIn.value) {
      return navigateTo("/");
    }
  }
});

Kudos!

@IsraelOrtuno
Copy link
Contributor

I came up with right the same solution too, this is a really great improvement.

@atinux
Copy link
Owner

atinux commented Sep 5, 2024

So, I also added support for scrypt which is support natively in CF workers environment: https://github.com/atinux/nuxt-bcrypt-edge/blob/main/server/api/scrypt/hash.post.ts

It does need a small hack though in the meantime (working with Pooya to avoid this)

@anuragkumar19
Copy link

We should also add a utility for checking compromised passwords.

https://haveibeenpwned.com/API/v3#PwnedPasswords

@atinux atinux changed the title feat: support password feat: add hashPassword & verifyPassword server utils Sep 25, 2024
@atinux atinux marked this pull request as ready for review September 25, 2024 15:00
@atinux atinux merged commit 0c4d050 into atinux:main Sep 25, 2024
3 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.

Add hashPassword() and verifyPassword() server utils
5 participants