69 lines
1.6 KiB
TypeScript
69 lines
1.6 KiB
TypeScript
import bcrypt from 'bcryptjs';
|
|
import jwt from 'jsonwebtoken';
|
|
import { cookies } from 'next/headers';
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || '4916c430ed2682c2f023762e47531d95c6e51c4c5ab4ca8af79f6f010e203cf9';
|
|
const ADMIN_USERNAME = process.env.ADMIN_USERNAME || 'admin';
|
|
const ADMIN_PASSWORD_HASH = process.env.ADMIN_PASSWORD_HASH || '$2b$10$VNZQMk1mQDoHif6moT9ceuB1wMoB7VImq21LxQecf3mlTwIUGahBO';
|
|
|
|
export interface JWTPayload {
|
|
username: string;
|
|
iat: number;
|
|
exp: number;
|
|
}
|
|
|
|
/**
|
|
* Verify username and password
|
|
*/
|
|
export async function verifyCredentials(username: string, password: string): Promise<boolean> {
|
|
if (username !== ADMIN_USERNAME) {
|
|
return false;
|
|
}
|
|
return bcrypt.compare(password, ADMIN_PASSWORD_HASH);
|
|
}
|
|
|
|
/**
|
|
* Create JWT token
|
|
*/
|
|
export function createToken(username: string): string {
|
|
return jwt.sign(
|
|
{ username },
|
|
JWT_SECRET,
|
|
{ expiresIn: '24h' }
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Verify JWT token
|
|
*/
|
|
export function verifyToken(token: string): JWTPayload | null {
|
|
try {
|
|
return jwt.verify(token, JWT_SECRET) as JWTPayload;
|
|
} catch (error) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get current user from cookies
|
|
*/
|
|
export async function getCurrentUser(): Promise<string | null> {
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get('auth-token')?.value;
|
|
|
|
if (!token) {
|
|
return null;
|
|
}
|
|
|
|
const payload = verifyToken(token);
|
|
return payload ? payload.username : null;
|
|
}
|
|
|
|
/**
|
|
* Check if user is authenticated
|
|
*/
|
|
export async function isAuthenticated(): Promise<boolean> {
|
|
const user = await getCurrentUser();
|
|
return user !== null;
|
|
}
|