feat: add authentication modal component and user authentication logic

- Implemented AuthModal.vue for user login and registration with form handling.
- Created useAuth composable for managing user state and authentication requests.
- Added admin route middleware to protect admin routes.
- Developed admin login page with authentication checks.
- Implemented API endpoints for user management (login, logout, fetch user, register).
- Created database migrations for users table and updated movies table.
- Added utility functions for password hashing and JWT token management.
This commit is contained in:
ngthanhvu
2026-07-22 04:26:58 -04:00
parent ad8d577493
commit d982449464
29 changed files with 1965 additions and 178 deletions
+56
View File
@@ -0,0 +1,56 @@
import { users } from '../../database/schema'
import { eq, sql } from 'drizzle-orm'
import { hashPassword, signToken } from '../../utils/auth'
export default defineEventHandler(async (event) => {
const db = useDb()
const body = await readBody(event)
const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : ''
const password = typeof body.password === 'string' ? body.password : ''
const name = typeof body.name === 'string' ? body.name.trim() : ''
if (!email || !password) {
throw createError({ statusCode: 400, message: 'Email và mật khẩu là bắt buộc' })
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
throw createError({ statusCode: 400, message: 'Email không hợp lệ' })
}
if (password.length < 6) {
throw createError({ statusCode: 400, message: 'Mật khẩu phải có ít nhất 6 ký tự' })
}
const existing = await db.select().from(users).where(eq(users.email, email)).limit(1)
if (existing.length) {
throw createError({ statusCode: 409, message: 'Email đã được sử dụng' })
}
const hashedPassword = await hashPassword(password)
const isAdmin = (await db.select({ count: sql<number>`count(*)` }).from(users))[0]?.count === 0
const result = await db.insert(users).values({
email,
password: hashedPassword,
name: name || email.split('@')[0],
role: isAdmin ? 'admin' : 'user',
})
const userId = result[0].insertId
const user = { id: userId, email, role: isAdmin ? 'admin' : 'user' }
const token = signToken(user)
setCookie(event, 'token', token, {
httpOnly: true,
secure: false,
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 7,
path: '/',
})
return {
user: { id: userId, email, name: name || email.split('@')[0], role: user.role },
token,
}
})