nuxt-users
Version:
A comprehensive user management module for Nuxt 3 and Nuxt 4 applications with authentication, authorization, database support, and CLI tools
57 lines (56 loc) • 2.12 kB
JavaScript
import { createError, defineEventHandler, readBody, setCookie } from "h3";
import bcrypt from "bcrypt";
import crypto from "node:crypto";
import { useRuntimeConfig } from "#imports";
import { useDb } from "../../../utils/index.js";
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const { email, password } = body;
if (!email || !password) {
throw createError({
statusCode: 400,
statusMessage: "Email and password are required"
});
}
const { nuxtUsers } = useRuntimeConfig();
const options = nuxtUsers;
const db = await useDb(options);
const usersTable = options.tables.users;
const personalAccessTokensTable = options.tables.personalAccessTokens;
const userResult = await db.sql`SELECT * FROM {${usersTable}} WHERE email = ${email}`;
if (userResult.rows.length === 0) {
throw createError({
statusCode: 401,
statusMessage: "Invalid email or password"
});
}
const user = userResult.rows[0];
const storedPassword = user.password;
const passwordMatch = await bcrypt.compare(password, storedPassword);
if (!passwordMatch) {
throw createError({
statusCode: 401,
statusMessage: "Invalid email or password"
});
}
const token = crypto.randomBytes(64).toString("hex");
const tokenName = "auth_token";
const expiresAt = /* @__PURE__ */ new Date();
expiresAt.setMinutes(expiresAt.getMinutes() + options.auth.tokenExpiration);
await db.sql`
INSERT INTO {${personalAccessTokensTable}} (tokenable_type, tokenable_id, name, token, expires_at, created_at, updated_at)
VALUES ('user', ${user.id}, ${tokenName}, ${token}, ${expiresAt.toISOString().slice(0, 19).replace("T", " ")}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
`;
setCookie(event, "auth_token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
// Use secure cookies in production
sameSite: "lax",
// Adjust as needed
maxAge: 60 * 60 * 24 * 7,
// 7 days
path: "/"
});
const { password: _, ...userWithoutPassword } = user;
return { user: userWithoutPassword };
});