Spaces:
Sleeping

File size: 2,486 Bytes
7f81110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { JtiStore } from "../../../../infrastructure/memory/JtiStore";
import { UnauthorizedError } from "../../../../domain/errors/UnauthorizedError";
import { env } from "../../../../../../config/env";

const JWT_SECRET = env.SESSION_SECRET || "dev-secret-change-in-production";

export const AuthMiddleware = async (req: Request, res: Response, next: NextFunction) => {
    try {
        let token = "";

        const authHeader = req.headers.authorization;
        if (authHeader && authHeader.startsWith("Bearer ")) {
            token = authHeader.split(" ")[1];
        } else if (req.headers.cookie) {
            const match = req.headers.cookie.match(/(?:token|accessToken|access_token|session)=([^;]+)/);
            if (match) {
                token = match[1];
            }
        }

        if (!token) {
            return next(new UnauthorizedError("Token missing"));
        }

        // ── 1. Verify JWT signature ───────────────────────────────────────
        let payload: any;
        try {
            payload = jwt.verify(token, JWT_SECRET) as any;
        } catch (err: any) {
            if (err.name === "TokenExpiredError") {
                return next(new UnauthorizedError("Token expired"));
            }
            return next(new UnauthorizedError("Invalid token signature"));
        }

        if (!payload?.sub || !payload?.jti) {
            return next(new UnauthorizedError("Token payload invalid"));
        }

        // ── 2. Check JTI in memory store ──────────────────────────────────
        const entry = JtiStore.get(payload.jti);
        if (!entry) {
            return next(new UnauthorizedError("Token revoked or invalid"));
        }

        // ── 3. Attach identity to request ─────────────────────────────────
        req.userId = String(payload.sub);
        req.jti = String(payload.jti);
        (req as any).user = {
            claims: {
                sub: payload.sub,
                organizationId: payload.organizationId,
                storeId: payload.storeId,
            },
        };

        next();
    } catch (error) {
        next(new UnauthorizedError("Authentication failed"));
    }
};