Spaces:
Sleeping
Sleeping
| import { Request, Response, NextFunction } from 'express'; | |
| import { verifyToken } from '../utils/jwt'; | |
| import prisma from '../utils/db'; | |
| import { gagal } from '../utils/response'; | |
| export interface AuthenticatedRequest extends Request { | |
| user?: any; | |
| } | |
| export const authenticate = async ( | |
| req: AuthenticatedRequest, | |
| res: Response, | |
| next: NextFunction | |
| ) => { | |
| try { | |
| const authHeader = req.headers.authorization; | |
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | |
| return gagal(res, 401, 'Token tidak ditemukan atau tidak valid'); | |
| } | |
| const token = authHeader.split(' ')[1]; | |
| const decoded = verifyToken(token); | |
| if (!decoded || decoded.type !== 'access') { | |
| return gagal(res, 401, 'Token tidak valid atau kedaluwarsa'); | |
| } | |
| const username = decoded.sub; | |
| const user = await prisma.user.findFirst({ | |
| where: { | |
| username, | |
| aktif: 1, | |
| }, | |
| }); | |
| if (!user) { | |
| return gagal(res, 401, 'Pengguna tidak aktif atau tidak ditemukan'); | |
| } | |
| req.user = user; | |
| next(); | |
| } catch (error) { | |
| next(error); | |
| } | |
| }; | |
| export const requireAdmin = ( | |
| req: AuthenticatedRequest, | |
| res: Response, | |
| next: NextFunction | |
| ) => { | |
| if (!req.user || req.user.role !== 'admin') { | |
| return gagal(res, 403, 'Akses ditolak. Peran Admin diperlukan.'); | |
| } | |
| next(); | |
| }; | |