crypt-express-app 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/index.js +20 -0
- package/dist/scripts/generate-app.js +96 -0
- package/dist/scripts/generate-locales.js +29 -0
- package/dist/scripts/generate-middleware.js +165 -0
- package/dist/scripts/generate-module.js +677 -0
- package/dist/scripts/generate-root-files.js +123 -0
- package/dist/scripts/generate-utils.js +191 -0
- package/dist/scripts/middleware.js +165 -0
- package/dist/scripts/setup-prisma.js +21 -0
- package/index.ts +29 -0
- package/package.json +23 -0
- package/scripts/generate-app.ts +104 -0
- package/scripts/generate-locales.ts +36 -0
- package/scripts/generate-middleware.ts +176 -0
- package/scripts/generate-module.ts +715 -0
- package/scripts/generate-root-files.ts +147 -0
- package/scripts/generate-utils.ts +208 -0
- package/scripts/setup-prisma.ts +26 -0
- package/tsconfig.json +10 -0
package/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# crypt-express-app
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execSync } from "child_process";
|
|
3
|
+
const projectName = process.argv[2];
|
|
4
|
+
if (!projectName) {
|
|
5
|
+
console.error("❌ project-name required");
|
|
6
|
+
console.log("Usage: npx crypt-express-app <project-name>");
|
|
7
|
+
process.exit(1);
|
|
8
|
+
}
|
|
9
|
+
process.env.PROJECT_NAME = projectName;
|
|
10
|
+
function run(cmd) {
|
|
11
|
+
execSync(cmd, { stdio: "inherit" });
|
|
12
|
+
}
|
|
13
|
+
// run generators
|
|
14
|
+
// run("tsx scripts/generate-root-files.ts");
|
|
15
|
+
// run("tsx scripts/generate-utils.ts");
|
|
16
|
+
// run("tsx scripts/generate-locales.ts");
|
|
17
|
+
// run("tsx scripts/setup-prisma.ts");
|
|
18
|
+
// run("tsx scripts/generate-middleware.ts");
|
|
19
|
+
// run("tsx scripts/generate-module.ts common");
|
|
20
|
+
console.log("✅ project generated");
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// generate-utils.ts
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
const basePath = path.join(__dirname, "..");
|
|
5
|
+
if (!fs.existsSync(basePath)) {
|
|
6
|
+
fs.mkdirSync(basePath, { recursive: true });
|
|
7
|
+
}
|
|
8
|
+
/* ================= redis.ts ================= */
|
|
9
|
+
const appContent = `
|
|
10
|
+
import express, { type Express } from "express";
|
|
11
|
+
import cors from "cors";
|
|
12
|
+
import morgan from "morgan";
|
|
13
|
+
import { json, urlencoded } from "express";
|
|
14
|
+
import i18next from 'i18next';
|
|
15
|
+
import Backend from 'i18next-fs-backend';
|
|
16
|
+
import middleware from 'i18next-http-middleware';
|
|
17
|
+
import path from 'path';
|
|
18
|
+
import { errorMiddleware } from "./middlewares/error.middleware";
|
|
19
|
+
import { loggerMiddleware } from "./middlewares/logger.middleware";
|
|
20
|
+
import swaggerUi from "swagger-ui-express";
|
|
21
|
+
import { swaggerSpec } from "./utils/swagger";
|
|
22
|
+
|
|
23
|
+
export const app: Express = express();
|
|
24
|
+
|
|
25
|
+
// i18n
|
|
26
|
+
i18next
|
|
27
|
+
.use(Backend)
|
|
28
|
+
.use(middleware.LanguageDetector)
|
|
29
|
+
.init({
|
|
30
|
+
fallbackLng: 'en',
|
|
31
|
+
preload: ['en', 'bn'],
|
|
32
|
+
backend: {
|
|
33
|
+
loadPath: path.join(__dirname, 'locales/{{lng}}/translation.json')
|
|
34
|
+
},
|
|
35
|
+
detection: {
|
|
36
|
+
order: ['querystring', 'cookie', 'header'],
|
|
37
|
+
caches: ['cookie']
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Middlewares
|
|
42
|
+
app.use(cors());
|
|
43
|
+
app.use(json());
|
|
44
|
+
app.use(urlencoded({ extended: true }));
|
|
45
|
+
app.use(morgan("dev"));
|
|
46
|
+
app.use(middleware.handle(i18next));
|
|
47
|
+
|
|
48
|
+
// Logger middleware should come first
|
|
49
|
+
app.use(loggerMiddleware);
|
|
50
|
+
|
|
51
|
+
// Routes
|
|
52
|
+
app.get('/', (req, res) => {
|
|
53
|
+
res.send(req.t('WELCOME')); // automatically returns text in detected language
|
|
54
|
+
});
|
|
55
|
+
app.use("/api/docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
|
|
56
|
+
swaggerOptions: {
|
|
57
|
+
persistAuthorization: true, // ✅ এটা রাখে token reload-এও
|
|
58
|
+
},
|
|
59
|
+
}));
|
|
60
|
+
|
|
61
|
+
// Error handler
|
|
62
|
+
app.use(errorMiddleware);
|
|
63
|
+
|
|
64
|
+
export default app;
|
|
65
|
+
`;
|
|
66
|
+
fs.writeFileSync(path.join(basePath, "src", "app.ts"), appContent);
|
|
67
|
+
/* ================= redis.ts ================= */
|
|
68
|
+
const serverContent = `
|
|
69
|
+
import app from "./src/app";
|
|
70
|
+
import bootstrapSystem from "./src/utils/bootstrap";
|
|
71
|
+
import { connectRedis } from "./src/utils/redis";
|
|
72
|
+
|
|
73
|
+
async function startServer() {
|
|
74
|
+
try{
|
|
75
|
+
await bootstrapSystem(); // 🔥 important
|
|
76
|
+
await connectRedis();
|
|
77
|
+
|
|
78
|
+
app.listen(5010, () => {
|
|
79
|
+
console.log("🚀 Server running at http://localhost:3000");
|
|
80
|
+
console.log("📘 Swagger docs at http://localhost:3000/api/docs");
|
|
81
|
+
});
|
|
82
|
+
}catch(error){
|
|
83
|
+
console.log("Error.........\\n\\n")
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
process.on("uncaughtException", (err) => {
|
|
87
|
+
console.error("🔥 Uncaught Exception:", err);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
process.on("unhandledRejection", (reason) => {
|
|
91
|
+
console.error("🔥 Unhandled Rejection:", reason);
|
|
92
|
+
});
|
|
93
|
+
startServer();
|
|
94
|
+
`;
|
|
95
|
+
fs.writeFileSync(path.join(basePath, "server.ts"), serverContent);
|
|
96
|
+
console.log("✅ App files generated successfully inside src");
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// generate-locales.ts
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
const basePath = path.join(__dirname, "..", "src", "locales");
|
|
5
|
+
const bnPath = path.join(basePath, "bn");
|
|
6
|
+
const enPath = path.join(basePath, "en");
|
|
7
|
+
// ফোল্ডার তৈরি
|
|
8
|
+
[basePath, bnPath, enPath].forEach((dir) => {
|
|
9
|
+
if (!fs.existsSync(dir)) {
|
|
10
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
11
|
+
}
|
|
12
|
+
});
|
|
13
|
+
// বাংলা translation
|
|
14
|
+
const bnContent = `
|
|
15
|
+
{
|
|
16
|
+
"WELCOME": "আমাদের এপিতে স্বাগতম",
|
|
17
|
+
"USER_NOT_FOUND": "ব্যবহারকারী পাওয়া যায়নি"
|
|
18
|
+
}
|
|
19
|
+
`;
|
|
20
|
+
// ইংরেজি translation
|
|
21
|
+
const enContent = `
|
|
22
|
+
{
|
|
23
|
+
"WELCOME": "Welcome to our API",
|
|
24
|
+
"USER_NOT_FOUND": "User not found"
|
|
25
|
+
}
|
|
26
|
+
`;
|
|
27
|
+
fs.writeFileSync(path.join(bnPath, "translation.json"), bnContent.trim());
|
|
28
|
+
fs.writeFileSync(path.join(enPath, "translation.json"), enContent.trim());
|
|
29
|
+
console.log("Locales generated successfully inside src/locales");
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
const projectRoot = process.cwd();
|
|
4
|
+
const basePath = path.join(projectRoot, "src", "middlewares");
|
|
5
|
+
if (!fs.existsSync(basePath)) {
|
|
6
|
+
fs.mkdirSync(basePath, { recursive: true });
|
|
7
|
+
}
|
|
8
|
+
/* ================= AUTHORIZATION ================= */
|
|
9
|
+
const authorizationContent = `
|
|
10
|
+
import { Request, Response, NextFunction } from "express";
|
|
11
|
+
import { ResourceType, ActionsType, Resource } from "../utils/consts";
|
|
12
|
+
import { cacheService } from "../utils/redis";
|
|
13
|
+
|
|
14
|
+
export function authorizationMiddleware(authorization: {
|
|
15
|
+
resource: Resource;
|
|
16
|
+
resourceType: ResourceType;
|
|
17
|
+
actions: ActionsType[];
|
|
18
|
+
}) {
|
|
19
|
+
return async (req: Request, res: Response, next: NextFunction) => {
|
|
20
|
+
try {
|
|
21
|
+
const userId = req?.user?.userId;
|
|
22
|
+
if (!userId) {
|
|
23
|
+
return res.status(401).json({ message: "Unauthorized" });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const cached = await cacheService.get(\`user:\${userId}:permissions\`);
|
|
27
|
+
if (!cached) {
|
|
28
|
+
return res.status(403).json({ message: "Permissions not loaded" });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const profile = JSON.parse(cached as string);
|
|
32
|
+
const permissions: string[] = profile.permissions || [];
|
|
33
|
+
|
|
34
|
+
const allowed = permissions.some((perm) => {
|
|
35
|
+
const [resName, action, type] = perm.split(":");
|
|
36
|
+
return (
|
|
37
|
+
resName === authorization.resource &&
|
|
38
|
+
type === authorization.resourceType &&
|
|
39
|
+
authorization.actions.includes(action as ActionsType)
|
|
40
|
+
);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
if (!allowed) {
|
|
44
|
+
return res.status(403).json({ message: "Access denied" });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
next();
|
|
48
|
+
} catch (error) {
|
|
49
|
+
console.error(error);
|
|
50
|
+
return res.status(500).json({ message: "Authorization error" });
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
`;
|
|
55
|
+
fs.writeFileSync(path.join(basePath, "authorization.middleware.ts"), authorizationContent.trim());
|
|
56
|
+
/* ================= AUTH ================= */
|
|
57
|
+
const authContent = `
|
|
58
|
+
import { Request, Response, NextFunction } from "express";
|
|
59
|
+
import jwt from "jsonwebtoken";
|
|
60
|
+
import prisma from "../../prisma/client";
|
|
61
|
+
import { cacheService } from "../utils/redis";
|
|
62
|
+
|
|
63
|
+
interface JwtPayload {
|
|
64
|
+
realmId: string;
|
|
65
|
+
sessionId: string;
|
|
66
|
+
userId: string;
|
|
67
|
+
email: string;
|
|
68
|
+
clientIdInternal: string;
|
|
69
|
+
isMasterRealmUser: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
declare global {
|
|
73
|
+
namespace Express {
|
|
74
|
+
interface Request {
|
|
75
|
+
user?: JwtPayload;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const authMiddleware = async (req: Request, res: Response, next: NextFunction) => {
|
|
81
|
+
const authHeader = req.headers.authorization;
|
|
82
|
+
if (!authHeader) return res.status(401).json({ message: "Authorization header missing" });
|
|
83
|
+
|
|
84
|
+
const [scheme, tokenRaw] = authHeader.split(" ");
|
|
85
|
+
if (scheme !== "Bearer" || !tokenRaw) {
|
|
86
|
+
return res.status(401).json({ message: "Invalid Authorization header format" });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const token = tokenRaw.replace(/^\"|\"$/g, "");
|
|
90
|
+
|
|
91
|
+
const decodedPayload = jwt.decode(token) as JwtPayload | null;
|
|
92
|
+
if (!decodedPayload || !decodedPayload.realmId) {
|
|
93
|
+
return res.status(401).json({ message: "Invalid token: realmId missing" });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const realmId = decodedPayload.realmId;
|
|
97
|
+
|
|
98
|
+
const secretKey = \`realm:\${realmId}:secret\`;
|
|
99
|
+
const secret = await cacheService.get(secretKey);
|
|
100
|
+
if (!secret) {
|
|
101
|
+
return res.status(500).json({ message: "JWT secret not configured in Redis" });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
const decoded = jwt.verify(token, secret as string, {
|
|
106
|
+
algorithms: ["HS256"],
|
|
107
|
+
}) as JwtPayload & { userId: string; sessionId: string };
|
|
108
|
+
|
|
109
|
+
const session = await prisma.userSession.findUnique({
|
|
110
|
+
where: { userSessionId: decoded.sessionId },
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
if (!session) {
|
|
114
|
+
return res.status(401).json({ message: "Session invalid or logged out" });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
req.user = decoded;
|
|
118
|
+
next();
|
|
119
|
+
} catch (err: any) {
|
|
120
|
+
if (err.name === "TokenExpiredError") {
|
|
121
|
+
return res.status(401).json({ message: "Token expired" });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return res.status(401).json({ message: "Invalid token" });
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
`;
|
|
128
|
+
fs.writeFileSync(path.join(basePath, "auth.middleware.ts"), authContent.trim());
|
|
129
|
+
/* ================= ERROR ================= */
|
|
130
|
+
const errorContent = `
|
|
131
|
+
import { Request, Response, NextFunction } from "express";
|
|
132
|
+
|
|
133
|
+
export const errorMiddleware = (err: any, req: Request, res: Response, next: NextFunction) => {
|
|
134
|
+
console.error(err);
|
|
135
|
+
|
|
136
|
+
const status = err.status || 500;
|
|
137
|
+
const message = err.message || "Internal Server Error";
|
|
138
|
+
|
|
139
|
+
res.status(status).json({
|
|
140
|
+
success: false,
|
|
141
|
+
status,
|
|
142
|
+
message,
|
|
143
|
+
...(process.env.NODE_ENV === "development" && { stack: err.stack }),
|
|
144
|
+
});
|
|
145
|
+
};
|
|
146
|
+
`;
|
|
147
|
+
fs.writeFileSync(path.join(basePath, "error.middleware.ts"), errorContent.trim());
|
|
148
|
+
/* ================= LOGGER ================= */
|
|
149
|
+
const loggerContent = `
|
|
150
|
+
import { Request, Response, NextFunction } from "express";
|
|
151
|
+
import logger from "../utils/logger";
|
|
152
|
+
|
|
153
|
+
export const loggerMiddleware = (req: Request, res: Response, next: NextFunction) => {
|
|
154
|
+
const start = Date.now();
|
|
155
|
+
|
|
156
|
+
res.on("finish", () => {
|
|
157
|
+
const duration = Date.now() - start;
|
|
158
|
+
logger.info(\`[\${new Date().toISOString()}] \${req.method} \${req.originalUrl} \${res.statusCode} - \${duration}ms\`);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
next();
|
|
162
|
+
};
|
|
163
|
+
`;
|
|
164
|
+
fs.writeFileSync(path.join(basePath, "logger.middleware.ts"), loggerContent.trim());
|
|
165
|
+
console.log(`✅ Middleware files generated successfully at ${basePath}`);
|