Initial commit
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { supabase } from '../lib/supabase';
|
||||
|
||||
export interface AuthenticatedRequest extends Request {
|
||||
user?: any;
|
||||
}
|
||||
|
||||
export const requireAuth = async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'Unauthorized: Missing or invalid token' });
|
||||
}
|
||||
|
||||
const token = authHeader.split(' ')[1];
|
||||
const { data: { user }, error } = await supabase.auth.getUser(token);
|
||||
|
||||
if (error || !user) {
|
||||
return res.status(401).json({ error: 'Unauthorized: Invalid token' });
|
||||
}
|
||||
|
||||
// P0-2: Lisans Kontrolü
|
||||
const { data: profile } = await supabase
|
||||
.from('profiles')
|
||||
.select('license_status')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
|
||||
if (!profile || (profile.license_status !== 'active' && profile.license_status !== 'trial')) {
|
||||
return res.status(403).json({ error: 'Forbidden: License is not active or in trial' });
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
|
||||
// P0-3: Kaynak Sahipliği Doğrulama (Eğer istekte caseId veya case_id varsa)
|
||||
const caseId = req.params.caseId || req.body?.case_id;
|
||||
if (caseId) {
|
||||
const { data: caseRecord, error: caseError } = await supabase
|
||||
.from('cases')
|
||||
.select('id')
|
||||
.eq('id', caseId)
|
||||
.eq('user_id', user.id)
|
||||
.single();
|
||||
|
||||
if (caseError || !caseRecord) {
|
||||
return res.status(403).json({ error: 'Forbidden: You do not own this case' });
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error('Auth middleware error:', error);
|
||||
res.status(500).json({ error: 'Internal server error during authentication' });
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user