File size: 2,189 Bytes
aeca117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { NextResponse } from 'next/server';

/**
 * Next.js Middleware — runs before every matched request.
 * Enforces authentication (hf_user cookie) on write API endpoints.
 */

// Routes that require authentication (write operations)
const PROTECTED_ROUTES = [
    '/api/annotate',    // POST: add annotation, DELETE: remove, PUT: update
    '/api/validate',    // PUT: validate mention, DELETE: remove mention
];

export function middleware(request) {
    const { pathname } = request.nextUrl;

    // Only protect write endpoints
    const isProtected = PROTECTED_ROUTES.some(route => pathname.startsWith(route));
    if (!isProtected) return NextResponse.next();

    // Allow GET requests (reads are OK without auth)
    if (request.method === 'GET') return NextResponse.next();

    // Check for hf_user cookie
    const userCookie = request.cookies.get('hf_user');
    if (!userCookie?.value) {
        return NextResponse.json(
            { error: 'Authentication required. Please sign in with HuggingFace.' },
            { status: 401 }
        );
    }

    // Parse and verify user is in allowed list
    try {
        const user = JSON.parse(userCookie.value);
        const username = user.username;

        if (!username) {
            return NextResponse.json(
                { error: 'Invalid session. Please sign in again.' },
                { status: 401 }
            );
        }

        // Check ALLOWED_USERS if set
        const allowedUsers = process.env.ALLOWED_USERS;
        if (allowedUsers) {
            const allowlist = allowedUsers.split(',').map(u => u.trim().toLowerCase());
            if (!allowlist.includes(username.toLowerCase())) {
                return NextResponse.json(
                    { error: `Access denied. User "${username}" is not authorized.` },
                    { status: 403 }
                );
            }
        }
    } catch (e) {
        return NextResponse.json(
            { error: 'Invalid session cookie. Please sign in again.' },
            { status: 401 }
        );
    }

    return NextResponse.next();
}

// Only run middleware on API routes
export const config = {
    matcher: '/api/:path*',
};