Files

36 lines
1.1 KiB
JavaScript

import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import { readDb } from './db.js'
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret'
export function authMiddleware(req, res, next) {
const header = req.headers.authorization
if (!header?.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' })
}
try {
req.user = jwt.verify(header.slice(7), JWT_SECRET)
next()
} catch {
return res.status(401).json({ error: 'Invalid token' })
}
}
export function loginHandler(req, res) {
const { email, password } = req.body || {}
const adminEmail = process.env.ADMIN_EMAIL || 'admin@norostudio.ir'
const adminPassword = process.env.ADMIN_PASSWORD || 'admin123'
if (email !== adminEmail || password !== adminPassword) {
return res.status(401).json({ error: 'ایمیل یا رمز عبور نادرست است' })
}
const token = jwt.sign({ email, role: 'admin' }, JWT_SECRET, { expiresIn: '7d' })
res.json({ token, user: { email, role: 'admin' } })
}
export function meHandler(req, res) {
res.json({ user: req.user })
}