@madhusha_99/exp-gen 1.2.1 → 1.2.3
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/LICENSE +21 -0
- package/README.md +97 -0
- package/bin/copyDir.js +37 -0
- package/bin/copyDir.js.map +1 -0
- package/bin/copyTemplates.js +44 -0
- package/bin/copyTemplates.js.map +1 -0
- package/bin/installDependencies.js +36 -0
- package/bin/installDependencies.js.map +1 -0
- package/bin/scaffoldProject.js +45 -0
- package/bin/scaffoldProject.js.map +1 -0
- package/bin/script.js +138 -0
- package/bin/script.js.map +1 -0
- package/bin/type/projectConfig.js +2 -0
- package/bin/type/projectConfig.js.map +1 -0
- package/package.json +1 -1
- package/src/templates/js/mongodb/app.js +42 -0
- package/src/templates/js/mongodb/configs/db.js +14 -0
- package/src/templates/js/mongodb/controllers/auth.controller.js +71 -0
- package/src/templates/js/mongodb/controllers/user.controller.js +27 -0
- package/src/templates/js/mongodb/default.env +4 -0
- package/src/templates/js/mongodb/middlewares/auth.middleware.js +64 -0
- package/src/templates/js/mongodb/models/user.model.js +13 -0
- package/src/templates/js/mongodb/package.json +29 -0
- package/src/templates/js/mongodb/repositories/user.repository.js +21 -0
- package/src/templates/js/mongodb/routes/auth.route.js +9 -0
- package/src/templates/js/mongodb/routes/user.route.js +24 -0
- package/src/templates/js/mongodb/services/user.service.js +50 -0
- package/src/templates/js/mongodb/utils/asyncHandler.js +5 -0
- package/src/templates/js/mongodb/utils/response.js +13 -0
- package/src/templates/js/mysql/app.js +42 -0
- package/src/templates/js/mysql/configs/config.js +17 -0
- package/src/templates/js/mysql/configs/db.js +50 -0
- package/src/templates/js/mysql/controllers/auth.controller.js +83 -0
- package/src/templates/js/mysql/controllers/user.controller.js +27 -0
- package/src/templates/js/mysql/default.env +9 -0
- package/src/templates/js/mysql/middlewares/auth.middleware.js +64 -0
- package/src/templates/js/mysql/models/user.model.js +22 -0
- package/src/templates/js/mysql/package-lock.json +4386 -0
- package/src/templates/js/mysql/package.json +29 -0
- package/src/templates/js/mysql/repositories/user.repository.js +84 -0
- package/src/templates/js/mysql/routes/auth.route.js +9 -0
- package/src/templates/js/mysql/routes/user.route.js +24 -0
- package/src/templates/js/mysql/services/user.service.js +50 -0
- package/src/templates/js/mysql/utils/asyncHandler.js +5 -0
- package/src/templates/js/mysql/utils/response.js +13 -0
- package/src/templates/js/none/app.js +32 -0
- package/src/templates/js/none/default.env +4 -0
- package/src/templates/js/none/package.json +23 -0
- package/src/templates/js/none/routes/api.route.js +9 -0
- package/src/templates/js/postgresql/default.env +10 -0
- package/src/templates/js/postgresql/package.json +29 -0
- package/src/templates/js/postgresql/src/app.js +42 -0
- package/src/templates/js/postgresql/src/configs/db.js +29 -0
- package/src/templates/js/postgresql/src/controllers/auth.controller.js +72 -0
- package/src/templates/js/postgresql/src/controllers/user.controller.js +27 -0
- package/src/templates/js/postgresql/src/middlewares/auth.middleware.js +64 -0
- package/src/templates/js/postgresql/src/repositories/user.repository.js +46 -0
- package/src/templates/js/postgresql/src/routes/auth.route.js +9 -0
- package/src/templates/js/postgresql/src/routes/user.route.js +24 -0
- package/src/templates/js/postgresql/src/services/user.service.js +50 -0
- package/src/templates/js/postgresql/src/utils/asyncHandler.js +5 -0
- package/src/templates/js/postgresql/src/utils/response.js +13 -0
- package/src/templates/js/sqlite/.gitkeep +0 -0
- package/src/templates/ts/mongodb/default.env +4 -0
- package/src/templates/ts/mongodb/package.json +34 -0
- package/src/templates/ts/mongodb/src/app.ts +45 -0
- package/src/templates/ts/mongodb/src/configs/db.ts +11 -0
- package/src/templates/ts/mongodb/src/controllers/auth.controller.ts +78 -0
- package/src/templates/ts/mongodb/src/controllers/user.controller.ts +31 -0
- package/src/templates/ts/mongodb/src/dtos/user.dto.ts +13 -0
- package/src/templates/ts/mongodb/src/interfaces/IUser.ts +8 -0
- package/src/templates/ts/mongodb/src/interfaces/express.d.ts +9 -0
- package/src/templates/ts/mongodb/src/middlewares/auth.middleware.ts +82 -0
- package/src/templates/ts/mongodb/src/models/user.model.ts +14 -0
- package/src/templates/ts/mongodb/src/repositories/user.repository.ts +22 -0
- package/src/templates/ts/mongodb/src/routes/auth.route.ts +9 -0
- package/src/templates/ts/mongodb/src/routes/user.route.ts +25 -0
- package/src/templates/ts/mongodb/src/services/user.service.ts +52 -0
- package/src/templates/ts/mongodb/src/utils/asyncHandler.ts +14 -0
- package/src/templates/ts/mongodb/src/utils/response.ts +18 -0
- package/src/templates/ts/mongodb/tsconfig.json +16 -0
- package/src/templates/ts/none/default.env +4 -0
- package/src/templates/ts/none/package.json +34 -0
- package/src/templates/ts/none/src/app.ts +40 -0
- package/src/templates/ts/none/src/routes/api.route.ts +10 -0
- package/src/templates/ts/none/tsconfig.json +16 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "js-mysql",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Modern Express API with mysql, ES Modules, and async CRUD",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "app.js",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"dev": "nodemon app.js",
|
|
9
|
+
"start": "node app.js",
|
|
10
|
+
"lint": "eslint .",
|
|
11
|
+
"format": "prettier --write ."
|
|
12
|
+
},
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"bcryptjs": "^3.0.3",
|
|
15
|
+
"cors": "^2.8.5",
|
|
16
|
+
"dotenv": "^16.4.5",
|
|
17
|
+
"express": "^4.19.2",
|
|
18
|
+
"http-errors": "^2.0.0",
|
|
19
|
+
"jsonwebtoken": "^9.0.3",
|
|
20
|
+
"mysql2": "^3.6.0",
|
|
21
|
+
"morgan": "^1.10.0"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"eslint": "^9.0.0",
|
|
25
|
+
"eslint-plugin-import": "^2.29.1",
|
|
26
|
+
"nodemon": "^3.1.14",
|
|
27
|
+
"prettier": "^3.2.5"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { query } from "../configs/db.js";
|
|
2
|
+
|
|
3
|
+
export const getAllUsers = async () => {
|
|
4
|
+
const rows = await query(
|
|
5
|
+
"SELECT id, name, email, age, created_at, updated_at FROM users"
|
|
6
|
+
);
|
|
7
|
+
return rows;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export const getUserById = async (id) => {
|
|
11
|
+
const rows = await query(
|
|
12
|
+
"SELECT id, name, email, age, created_at, updated_at FROM users WHERE id = ?",
|
|
13
|
+
[id]
|
|
14
|
+
);
|
|
15
|
+
return rows[0] || null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export const getUserByEmail = async (email) => {
|
|
19
|
+
const rows = await query(
|
|
20
|
+
"SELECT id, name, email, password, age, created_at, updated_at FROM users WHERE email = ?",
|
|
21
|
+
[email]
|
|
22
|
+
);
|
|
23
|
+
return rows[0] || null;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export const createUser = async (data) => {
|
|
27
|
+
const { name, email, password, age = 0 } = data;
|
|
28
|
+
const insertResult = await query(
|
|
29
|
+
"INSERT INTO users (name, email, password, age, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())",
|
|
30
|
+
[name, email, password, age]
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
if (!insertResult || !insertResult.insertId) {
|
|
34
|
+
throw new Error("Failed to create user - no insert ID returned");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return await getUserById(insertResult.insertId);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export const updateUser = async (id, data) => {
|
|
41
|
+
const fields = [];
|
|
42
|
+
const params = [];
|
|
43
|
+
|
|
44
|
+
if (data.name !== undefined) {
|
|
45
|
+
fields.push("name = ?");
|
|
46
|
+
params.push(data.name);
|
|
47
|
+
}
|
|
48
|
+
if (data.email !== undefined) {
|
|
49
|
+
fields.push("email = ?");
|
|
50
|
+
params.push(data.email);
|
|
51
|
+
}
|
|
52
|
+
if (data.password !== undefined) {
|
|
53
|
+
fields.push("password = ?");
|
|
54
|
+
params.push(data.password);
|
|
55
|
+
}
|
|
56
|
+
if (data.age !== undefined) {
|
|
57
|
+
fields.push("age = ?");
|
|
58
|
+
params.push(data.age);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (fields.length === 0) {
|
|
62
|
+
return await getUserById(id);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
params.push(id);
|
|
66
|
+
const updateResult = await query(
|
|
67
|
+
`UPDATE users SET ${fields.join(", ")}, updated_at = NOW() WHERE id = ?`,
|
|
68
|
+
params
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
if (!updateResult || updateResult.affectedRows === 0) {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return await getUserById(id);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
export const deleteUser = async (id) => {
|
|
79
|
+
const user = await getUserById(id);
|
|
80
|
+
if (!user) return null;
|
|
81
|
+
|
|
82
|
+
await query("DELETE FROM users WHERE id = ?", [id]);
|
|
83
|
+
return user;
|
|
84
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Router } from "express";
|
|
2
|
+
import {
|
|
3
|
+
getUsers,
|
|
4
|
+
getUser,
|
|
5
|
+
createUser,
|
|
6
|
+
updateUser,
|
|
7
|
+
deleteUser,
|
|
8
|
+
} from "../controllers/user.controller.js";
|
|
9
|
+
import { protect } from "../middlewares/auth.middleware.js";
|
|
10
|
+
import { successResponse } from "../utils/response.js";
|
|
11
|
+
|
|
12
|
+
const router = Router();
|
|
13
|
+
|
|
14
|
+
router.get("/protected", protect, (req, res) => {
|
|
15
|
+
res.json(successResponse({ user: req.user }, "Protected route accessed"));
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
router.get("/users", getUsers);
|
|
19
|
+
router.get("/users/:id", protect, getUser);
|
|
20
|
+
router.post("/users", createUser);
|
|
21
|
+
router.put("/users/:id", updateUser);
|
|
22
|
+
router.delete("/users/:id", deleteUser);
|
|
23
|
+
|
|
24
|
+
export default router;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import * as userRepo from "../repositories/user.repository.js";
|
|
2
|
+
import { successResponse, errorResponse } from "../utils/response.js";
|
|
3
|
+
|
|
4
|
+
export const getUsers = async () => {
|
|
5
|
+
try {
|
|
6
|
+
const users = await userRepo.getAllUsers();
|
|
7
|
+
return successResponse(users, "Users fetched successfully");
|
|
8
|
+
} catch (err) {
|
|
9
|
+
return errorResponse(err, "Failed to fetch users");
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const getUser = async (id) => {
|
|
14
|
+
try {
|
|
15
|
+
const user = await userRepo.getUserById(id);
|
|
16
|
+
if (!user) throw new Error("User not found");
|
|
17
|
+
return successResponse(user, "User fetched successfully");
|
|
18
|
+
} catch (err) {
|
|
19
|
+
return errorResponse(err, "Failed to fetch user");
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const createNewUser = async (data) => {
|
|
24
|
+
try {
|
|
25
|
+
const user = await userRepo.createUser(data);
|
|
26
|
+
return successResponse(user, "User created successfully");
|
|
27
|
+
} catch (err) {
|
|
28
|
+
return errorResponse(err, "Failed to create user");
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const updateExistingUser = async (id, data) => {
|
|
33
|
+
try {
|
|
34
|
+
const user = await userRepo.updateUser(id, data);
|
|
35
|
+
if (!user) throw new Error("User not found");
|
|
36
|
+
return successResponse(user, "User updated successfully");
|
|
37
|
+
} catch (err) {
|
|
38
|
+
return errorResponse(err, "Failed to update user");
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const deleteExistingUser = async (id) => {
|
|
43
|
+
try {
|
|
44
|
+
const user = await userRepo.deleteUser(id);
|
|
45
|
+
if (!user) throw new Error("User not found");
|
|
46
|
+
return successResponse(user, "User deleted successfully");
|
|
47
|
+
} catch (err) {
|
|
48
|
+
return errorResponse(err, "Failed to delete user");
|
|
49
|
+
}
|
|
50
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export const successResponse = (data, message = "Success") => ({
|
|
2
|
+
status: 200,
|
|
3
|
+
success: true,
|
|
4
|
+
message,
|
|
5
|
+
data,
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
export const errorResponse = (error, message = "Error") => ({
|
|
9
|
+
status: error.status || 500,
|
|
10
|
+
success: false,
|
|
11
|
+
message,
|
|
12
|
+
error: error.message || message,
|
|
13
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import createError from "http-errors";
|
|
3
|
+
import morgan from "morgan";
|
|
4
|
+
import dotenv from "dotenv";
|
|
5
|
+
import apiRoutes from "./routes/api.route.js";
|
|
6
|
+
|
|
7
|
+
dotenv.config();
|
|
8
|
+
const app = express();
|
|
9
|
+
app.use(express.json());
|
|
10
|
+
app.use(express.urlencoded({ extended: false }));
|
|
11
|
+
app.use(morgan("dev"));
|
|
12
|
+
|
|
13
|
+
app.get("/", async (req, res) => {
|
|
14
|
+
res.send({ message: "Awesome it works 🐻" });
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
app.use("/api", apiRoutes);
|
|
18
|
+
|
|
19
|
+
app.use((req, res, next) => {
|
|
20
|
+
next(createError.NotFound());
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
app.use((err, req, res) => {
|
|
24
|
+
res.status(err.status || 500);
|
|
25
|
+
res.send({
|
|
26
|
+
status: err.status || 500,
|
|
27
|
+
message: err.message,
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const PORT = process.env.PORT || 3000;
|
|
32
|
+
app.listen(PORT, () => console.log(`🚀 @ http://localhost:${PORT}`));
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "js-none",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "app.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"start": "node app.js",
|
|
8
|
+
"dev": "nodemon app.js"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [],
|
|
11
|
+
"author": "",
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"dotenv": "^17.3.1",
|
|
16
|
+
"express": "^5.2.1",
|
|
17
|
+
"http-errors": "^2.0.1",
|
|
18
|
+
"morgan": "^1.10.1"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"nodemon": "^3.1.14"
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "js-postgresql-api",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Modern Express API with PostgreSQL, ES Modules, and async CRUD",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/app.js",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"dev": "nodemon app.js",
|
|
9
|
+
"start": "node app.js",
|
|
10
|
+
"lint": "eslint .",
|
|
11
|
+
"format": "prettier --write ."
|
|
12
|
+
},
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"bcryptjs": "^3.0.3",
|
|
15
|
+
"cors": "^2.8.5",
|
|
16
|
+
"dotenv": "^16.4.5",
|
|
17
|
+
"express": "^4.19.2",
|
|
18
|
+
"http-errors": "^2.0.0",
|
|
19
|
+
"jsonwebtoken": "^9.0.3",
|
|
20
|
+
"pg": "^8.20.0",
|
|
21
|
+
"morgan": "^1.10.0"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"eslint": "^9.0.0",
|
|
25
|
+
"eslint-plugin-import": "^2.29.1",
|
|
26
|
+
"nodemon": "^3.1.14",
|
|
27
|
+
"prettier": "^3.2.5"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import morgan from "morgan";
|
|
3
|
+
import createError from "http-errors";
|
|
4
|
+
import cors from "cors";
|
|
5
|
+
import dotenv from "dotenv";
|
|
6
|
+
import apiRoutes from "./routes/user.route.js";
|
|
7
|
+
import authRoutes from "./routes/auth.route.js";
|
|
8
|
+
import { connectDB } from "./configs/db.js";
|
|
9
|
+
|
|
10
|
+
dotenv.config();
|
|
11
|
+
connectDB();
|
|
12
|
+
|
|
13
|
+
const app = express();
|
|
14
|
+
|
|
15
|
+
// Middlewares
|
|
16
|
+
app.use(cors());
|
|
17
|
+
app.use(express.json());
|
|
18
|
+
app.use(express.urlencoded({ extended: true }));
|
|
19
|
+
app.use(morgan("dev"));
|
|
20
|
+
|
|
21
|
+
// Routes
|
|
22
|
+
app.get("/", (req, res) => res.json({ message: "API is running 🚀" }));
|
|
23
|
+
app.use("/api", apiRoutes); // user routes
|
|
24
|
+
app.use("/api/auth", authRoutes); // login route
|
|
25
|
+
|
|
26
|
+
// 404 handler
|
|
27
|
+
app.use((req, res, next) => {
|
|
28
|
+
next(createError.NotFound());
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// Global error handler
|
|
32
|
+
app.use((err, req, res) => {
|
|
33
|
+
res.status(err.status || 500).json({
|
|
34
|
+
success: false,
|
|
35
|
+
message: err.message || "Internal Server Error",
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const PORT = process.env.PORT || 3000;
|
|
40
|
+
app.listen(PORT, () =>
|
|
41
|
+
console.log(`🚀 Server running @ http://localhost:${PORT}`)
|
|
42
|
+
);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// src/config/db.js
|
|
2
|
+
import pkg from "pg";
|
|
3
|
+
import "dotenv/config";
|
|
4
|
+
|
|
5
|
+
const { Pool } = pkg;
|
|
6
|
+
|
|
7
|
+
const pool = new Pool({
|
|
8
|
+
user: String(process.env.DB_USER),
|
|
9
|
+
host: String(process.env.DB_HOST),
|
|
10
|
+
database: String(process.env.DB_NAME),
|
|
11
|
+
password: String(process.env.DB_PASSWORD),
|
|
12
|
+
port: Number(process.env.DB_PORT),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export const connectDB = async () => {
|
|
16
|
+
try {
|
|
17
|
+
const client = await pool.connect();
|
|
18
|
+
//remove this in production
|
|
19
|
+
console.log("🚀 Connected to PostgreSQL database");
|
|
20
|
+
|
|
21
|
+
client.release();
|
|
22
|
+
} catch (err) {
|
|
23
|
+
//remove this in production
|
|
24
|
+
console.error("DB connection error:", err);
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export default pool;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import asyncHandler from "../utils/asyncHandler.js";
|
|
2
|
+
import jwt from "jsonwebtoken";
|
|
3
|
+
import bcrypt from "bcryptjs";
|
|
4
|
+
import { successResponse, errorResponse } from "../utils/response.js";
|
|
5
|
+
import { findByEmail, createUser } from "../repositories/user.repository.js";
|
|
6
|
+
|
|
7
|
+
// Login endpoint
|
|
8
|
+
export const login = asyncHandler(async (req, res) => {
|
|
9
|
+
try {
|
|
10
|
+
const { email, password } = req.body;
|
|
11
|
+
|
|
12
|
+
// Find user
|
|
13
|
+
// const user = await User.findOne({ email });
|
|
14
|
+
const user = await findByEmail(email);
|
|
15
|
+
if (!user) {
|
|
16
|
+
return res.status(401).json(errorResponse(null, "Invalid credentials"));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Check password
|
|
20
|
+
const isMatch = await bcrypt.compare(password, user.password);
|
|
21
|
+
if (!isMatch) {
|
|
22
|
+
return res.status(401).json(errorResponse(null, "Invalid credentials"));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Generate token
|
|
26
|
+
const token = jwt.sign(
|
|
27
|
+
{ id: user._id, email: user.email },
|
|
28
|
+
process.env.JWT_SECRET,
|
|
29
|
+
{ expiresIn: process.env.JWT_EXPIRES_IN || "1d" }
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
res.json(successResponse({ token }, "Login successful"));
|
|
33
|
+
} catch (error) {
|
|
34
|
+
res.status(500).json(errorResponse(error, "Login failed"));
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
export const signup = asyncHandler(async (req, res) => {
|
|
39
|
+
try {
|
|
40
|
+
const { name, email, password, age } = req.body;
|
|
41
|
+
|
|
42
|
+
// Check if user already exists
|
|
43
|
+
const existingUser = await findByEmail(email);
|
|
44
|
+
if (existingUser) {
|
|
45
|
+
return res.status(400).json(errorResponse(null, "User already exists"));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Hash password
|
|
49
|
+
const hashedPassword = await bcrypt.hash(password, 10);
|
|
50
|
+
|
|
51
|
+
// Create user
|
|
52
|
+
const newUser = await createUser({
|
|
53
|
+
name,
|
|
54
|
+
email,
|
|
55
|
+
password: hashedPassword,
|
|
56
|
+
age: age || 0,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// Generate token
|
|
60
|
+
const token = jwt.sign(
|
|
61
|
+
{ id: newUser.id, email: newUser.email },
|
|
62
|
+
process.env.JWT_SECRET,
|
|
63
|
+
{ expiresIn: process.env.JWT_EXPIRES_IN || "1d" }
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
res
|
|
67
|
+
.status(201)
|
|
68
|
+
.json(successResponse({ token, user: newUser }, "Signup successful"));
|
|
69
|
+
} catch (error) {
|
|
70
|
+
res.status(500).json(errorResponse(error, "Signup failed"));
|
|
71
|
+
}
|
|
72
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import * as userService from "../services/user.service.js";
|
|
2
|
+
import asyncHandler from "../utils/asyncHandler.js";
|
|
3
|
+
|
|
4
|
+
export const getUsers = asyncHandler(async (req, res) => {
|
|
5
|
+
const result = await userService.getUsers();
|
|
6
|
+
res.status(result.status).json(result);
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
export const getUser = asyncHandler(async (req, res) => {
|
|
10
|
+
const result = await userService.getUser(req.params.id);
|
|
11
|
+
res.status(result.status).json(result);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export const createUser = asyncHandler(async (req, res) => {
|
|
15
|
+
const result = await userService.createNewUser(req.body);
|
|
16
|
+
res.status(result.status).json(result);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
export const updateUser = asyncHandler(async (req, res) => {
|
|
20
|
+
const result = await userService.updateExistingUser(req.params.id, req.body);
|
|
21
|
+
res.status(result.status).json(result);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export const deleteUser = asyncHandler(async (req, res) => {
|
|
25
|
+
const result = await userService.deleteExistingUser(req.params.id);
|
|
26
|
+
res.status(result.status).json(result);
|
|
27
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth middleware to protect routes using JWT
|
|
3
|
+
*
|
|
4
|
+
* How to use:
|
|
5
|
+
* 1. Generate a JWT token after user login using `jwt.sign(payload, JWT_SECRET, { expiresIn })`.
|
|
6
|
+
* 2. Send the token in the request headers: Authorization: Bearer <token>
|
|
7
|
+
* 3. Add this middleware to routes you want to protect:
|
|
8
|
+
* router.get('/protected', protect, protectedController)
|
|
9
|
+
* 4. Inside your controller, `req.user` will have the decoded user info
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import jwt from "jsonwebtoken";
|
|
13
|
+
import { errorResponse } from "../utils/response.js";
|
|
14
|
+
|
|
15
|
+
export const protect = (req, res, next) => {
|
|
16
|
+
try {
|
|
17
|
+
const authHeader = req.headers.authorization;
|
|
18
|
+
|
|
19
|
+
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
20
|
+
return res
|
|
21
|
+
.status(401)
|
|
22
|
+
.json(
|
|
23
|
+
errorResponse(
|
|
24
|
+
{ status: 401 },
|
|
25
|
+
"Authorization token missing or malformed"
|
|
26
|
+
)
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Get token from headers
|
|
31
|
+
const token = authHeader.split(" ")[1];
|
|
32
|
+
|
|
33
|
+
if (!token) {
|
|
34
|
+
return res
|
|
35
|
+
.status(401)
|
|
36
|
+
.json(errorResponse({ status: 401 }, "Not authorized, token missing"));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Verify token
|
|
40
|
+
let decoded;
|
|
41
|
+
try {
|
|
42
|
+
decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (err.name === "TokenExpiredError") {
|
|
45
|
+
return res
|
|
46
|
+
.status(401)
|
|
47
|
+
.json(errorResponse({ status: 401 }, "Token expired"));
|
|
48
|
+
}
|
|
49
|
+
return res
|
|
50
|
+
.status(401)
|
|
51
|
+
.json(errorResponse({ status: 401 }, "Unauthorized: Invalid token"));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Attach decoded user info to request
|
|
55
|
+
req.user = decoded;
|
|
56
|
+
|
|
57
|
+
next();
|
|
58
|
+
} catch (err) {
|
|
59
|
+
// Catch any unexpected errors
|
|
60
|
+
return res
|
|
61
|
+
.status(500)
|
|
62
|
+
.json(errorResponse({ status: 500 }, "Server error: " + err.message));
|
|
63
|
+
}
|
|
64
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import pool from "../configs/db.js";
|
|
2
|
+
|
|
3
|
+
//table need to be created before using these functions
|
|
4
|
+
// CREATE TABLE users (
|
|
5
|
+
// id SERIAL PRIMARY KEY,
|
|
6
|
+
// name VARCHAR(100) NOT NULL,
|
|
7
|
+
// email VARCHAR(100) UNIQUE NOT NULL,
|
|
8
|
+
// password VARCHAR(255) NOT NULL,
|
|
9
|
+
// age INTEGER DEFAULT 0
|
|
10
|
+
// );
|
|
11
|
+
export const getAllUsers = async () => {
|
|
12
|
+
const result = await pool.query("SELECT * FROM users ORDER BY id");
|
|
13
|
+
return result.rows;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const getUserById = async (id) => {
|
|
17
|
+
const result = await pool.query("SELECT * FROM users WHERE id=$1", [id]);
|
|
18
|
+
return result.rows[0];
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const createUser = async ({ name, email, password, age }) => {
|
|
22
|
+
const result = await pool.query(
|
|
23
|
+
"INSERT INTO users(name, email, password, age) VALUES($1, $2, $3, $4) RETURNING *",
|
|
24
|
+
[name, email, password, age]
|
|
25
|
+
);
|
|
26
|
+
return result.rows[0];
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const updateUser = async (id, { name, email }) => {
|
|
30
|
+
const result = await pool.query(
|
|
31
|
+
"UPDATE users SET name=$1, email=$2 WHERE id=$3 RETURNING *",
|
|
32
|
+
[name, email, id]
|
|
33
|
+
);
|
|
34
|
+
return result.rows[0];
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export const deleteUser = async (id) => {
|
|
38
|
+
await pool.query("DELETE FROM users WHERE id=$1", [id]);
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const findByEmail = async (email) => {
|
|
42
|
+
const result = await pool.query("SELECT * FROM users WHERE email=$1", [
|
|
43
|
+
email,
|
|
44
|
+
]);
|
|
45
|
+
return result.rows[0];
|
|
46
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Router } from "express";
|
|
2
|
+
import {
|
|
3
|
+
getUsers,
|
|
4
|
+
getUser,
|
|
5
|
+
createUser,
|
|
6
|
+
updateUser,
|
|
7
|
+
deleteUser,
|
|
8
|
+
} from "../controllers/user.controller.js";
|
|
9
|
+
import { protect } from "../middlewares/auth.middleware.js";
|
|
10
|
+
import { successResponse } from "../utils/response.js";
|
|
11
|
+
|
|
12
|
+
const router = Router();
|
|
13
|
+
|
|
14
|
+
router.get("/protected", protect, (req, res) => {
|
|
15
|
+
res.json(successResponse({ user: req.user }, "Protected route accessed"));
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
router.get("/users", getUsers);
|
|
19
|
+
router.get("/users/:id", protect, getUser);
|
|
20
|
+
router.post("/users", createUser);
|
|
21
|
+
router.put("/users/:id", updateUser);
|
|
22
|
+
router.delete("/users/:id", deleteUser);
|
|
23
|
+
|
|
24
|
+
export default router;
|