mirror of
https://github.com/ngthanhvu/kr-phim.git
synced 2026-08-10 17:27:47 +00:00
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:
@@ -0,0 +1,46 @@
|
||||
import bcrypt from 'bcryptjs'
|
||||
import jwt from 'jsonwebtoken'
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'cinek-secret-key-change-in-production-2024'
|
||||
const JWT_EXPIRES = '7d'
|
||||
const SALT_ROUNDS = 10
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
return bcrypt.hash(password, SALT_ROUNDS)
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
|
||||
return bcrypt.compare(password, hash)
|
||||
}
|
||||
|
||||
export function signToken(payload: { id: number, email: string, role: string }): string {
|
||||
return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES })
|
||||
}
|
||||
|
||||
export function verifyToken(token: string): { id: number, email: string, role: string } | null {
|
||||
try {
|
||||
return jwt.verify(token, JWT_SECRET) as { id: number, email: string, role: string }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function getTokenFromEvent(event: any): string | null {
|
||||
const authHeader = getHeader(event, 'authorization')
|
||||
if (authHeader?.startsWith('Bearer ')) {
|
||||
return authHeader.slice(7)
|
||||
}
|
||||
|
||||
const cookies = parseCookies(event)
|
||||
return cookies.token || null
|
||||
}
|
||||
|
||||
function parseCookies(event: any): Record<string, string> {
|
||||
const cookieHeader = getHeader(event, 'cookie') || ''
|
||||
const cookies: Record<string, string> = {}
|
||||
cookieHeader.split(';').forEach((pair: string) => {
|
||||
const [key, ...vals] = pair.trim().split('=')
|
||||
if (key) cookies[key] = decodeURIComponent(vals.join('='))
|
||||
})
|
||||
return cookies
|
||||
}
|
||||
Reference in New Issue
Block a user