-
Notifications
You must be signed in to change notification settings - Fork 86
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
Conversation
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 // 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! |
I came up with right the same solution too, this is a really great improvement. |
So, I also added support for It does need a small hack though in the meantime (working with Pooya to avoid this) |
We should also add a utility for checking compromised passwords. |
hashPassword
& verifyPassword
server utils
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).login
to another route (with a better namelogin
for log in a user after a registration (register
).possible thanks to the work of Atinux (https://github.com/atinux/nuxt-bcrypt-edge)