Skip to content

Commit db0c5cb

Browse files
committed
test:example
1 parent 5f1e70d commit db0c5cb

4 files changed

Lines changed: 98 additions & 6 deletions

File tree

plugins/auth-jwt/src/index.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ import {
4141
} from "./constants";
4242
import { getPluginSettings } from "./util/getPluginSettings";
4343
import { beforeCreateSeed } from "./events/createSeed";
44-
44+
import { replacePlaceholdersInModuleMap } from "./static-file-utils";
4545
const ARGS_ID = builders.identifier("args");
4646
const PASSWORD_FIELD_ASYNC_METHODS = new Set(["create", "update"]);
4747
const DATA_ID = builders.identifier("data");
@@ -141,6 +141,16 @@ class JwtAuthPlugin implements AmplicationPlugin {
141141
context.serverDirectories.srcDirectory
142142
);
143143

144+
const updatedModuleMap = replacePlaceholdersInModuleMap(
145+
modules,
146+
{
147+
"{{USER_SERVICE}}": "userService",
148+
},
149+
{
150+
"{{USER_SERVICE}}": "userService",
151+
}
152+
);
153+
144154
// 1. create jwtStrategy base file.
145155
const jwyStrategyBase = await createJwtStrategyBase(context);
146156
await modules.set(jwyStrategyBase);

plugins/auth-jwt/src/middle.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { ModuleMap } from "@amplication/code-gen-types";
2+
3+
export function replacePlaceholdersInModuleMap(
4+
moduleMap: ModuleMap,
5+
templateReplacements: Record<string, string>,
6+
stringReplacements: Record<string, string>
7+
): ModuleMap {
8+
moduleMap.modules().forEach((module) => {
9+
module.code = replacePlaceholders(module.code, templateReplacements);
10+
module.code = replaceText(module.code, stringReplacements);
11+
});
12+
13+
return moduleMap;
14+
}
15+
16+
export function replacePlaceholders(
17+
template: string,
18+
replacements: Record<string, string>
19+
): string {
20+
return template.replace(/{{(.*?)}}/g, (match, key) => {
21+
// Return the replacement value if it exists (even if it's an empty string)
22+
// Otherwise, keep the placeholder
23+
return Object.prototype.hasOwnProperty.call(replacements, key.trim())
24+
? replacements[key.trim()]
25+
: match;
26+
});
27+
}
28+
29+
export function replaceText(
30+
template: string,
31+
replacements: Record<string, string>
32+
): string {
33+
return Object.entries(replacements).reduce((result, [key, value]) => {
34+
return result.replaceAll(key, value);
35+
}, template);
36+
}

plugins/auth-jwt/src/types.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
export interface Settings {
2-
/**
3-
* The Secrets Provider reference for the jwt secret key used to sign the JWT token.
4-
* i.e. for the basic secrets provider (env variables), this would be the name of the environment variable containg the JWT Secret Key.
5-
*/
6-
JwtSecretKeyReference: string;
2+
tokenPropertyName: string;
3+
authEntityFieldName: string;
74
}

0 commit comments

Comments
 (0)