|
| 1 | +import { NextFunction } from "express"; |
| 2 | +import { AuthServicePlaceholderService } from "../authServicePlaceholder/authServicePlaceholder.service"; |
| 3 | +import { Injectable, NestMiddleware } from "@nestjs/common"; |
| 4 | +import * as jwt from "jsonwebtoken"; |
| 5 | + |
| 6 | +@Injectable() |
| 7 | +export class UserValidateActiveDirectory implements NestMiddleware { |
| 8 | + constructor(private userService: AuthServicePlaceholderService) {} |
| 9 | + |
| 10 | + async use(req: any, res: any, next: NextFunction) { |
| 11 | + try { |
| 12 | + // Extract the token from the Authorization header |
| 13 | + const authHeader = req.headers["authorization"]; |
| 14 | + if (!authHeader || !authHeader.startsWith("Bearer ")) { |
| 15 | + return res.status(401).send({ |
| 16 | + status: "error", |
| 17 | + text: "Authorization header is missing or invalid", |
| 18 | + }); |
| 19 | + } |
| 20 | + const token = authHeader.split(" ")[1]; // Remove "Bearer " prefix |
| 21 | + try { |
| 22 | + // Decode the token without verification (this assumes you're not verifying the signature here) |
| 23 | + const decodedToken = jwt.decode(token) as { tokenFieldName?: string }; |
| 24 | + res.tokenFieldName = (decodedToken as any)["cognito:username"]; |
| 25 | + const loginUser = await this.userService.authServicePlaceholder({ |
| 26 | + where: { authEntityFieldName: res.tokenFieldName }, |
| 27 | + }); |
| 28 | + if (loginUser) { |
| 29 | + req.user = loginUser; |
| 30 | + next(); |
| 31 | + } else { |
| 32 | + res.send({ |
| 33 | + status: "error", |
| 34 | + text: "user with the given tokenFieldName does not exist", |
| 35 | + }); |
| 36 | + } |
| 37 | + } catch (error) { |
| 38 | + // Handle errors (e.g., invalid token) |
| 39 | + console.error("Error decoding token:", error); |
| 40 | + return null; |
| 41 | + } |
| 42 | + } catch (error) { |
| 43 | + console.error("Error in middleware:", error); |
| 44 | + res |
| 45 | + .status(500) |
| 46 | + .send({ status: "error", text: "Internal server error", error }); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments