nodejs-backpack 0.0.1-security → 2.0.28

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.

Potentially problematic release.


This version of nodejs-backpack might be problematic. Click here for more details.

package/package.json CHANGED
@@ -1,6 +1,53 @@
1
- {
2
- "name": "nodejs-backpack",
3
- "version": "0.0.1-security",
4
- "description": "security holding package",
5
- "repository": "npm/security-holder"
6
- }
1
+ {
2
+ "name": "nodejs-backpack",
3
+ "version": "2.0.28",
4
+ "description": "NodeJs Backpack is a powerful tool designed to simplify the development of Node.js REST APIs with ease and precision. It provides a streamlined workflow by automatically generating Mongoose schemas and handling the necessary configurations in your project. With just a few simple commands, NodeJs Backpack can create REST API components such as controllers and routes, while also ensuring route validation is implemented flawlessly. Additionally, NodeJs Backpack offers a command to generate sample files, providing a solid starting point for your project. With NodeJs Backpack, you can quickly set up your project and focus on building your APIs, letting the tool handle the repetitive tasks and allowing you to follow a smooth development process.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [
10
+ "cli",
11
+ "CRUD Functionality",
12
+ "REST APIs",
13
+ "Files",
14
+ "Routing",
15
+ "Controllers",
16
+ "Models",
17
+ "Mongoose",
18
+ "jsonwebtoken",
19
+ "Authentication",
20
+ "JWT",
21
+ "Validation",
22
+ "Automation",
23
+ "Backpack",
24
+ "npm",
25
+ "node",
26
+ "node cli",
27
+ "node js",
28
+ "Node Js Project Builder",
29
+ "Project Builder",
30
+ "nodejs-backpack",
31
+ "jkg",
32
+ "jaykumar-gohil"
33
+ ],
34
+ "author": "Jaykumar Gohil",
35
+ "license": "CC BY-NC-ND 4.0",
36
+ "dependencies": {
37
+ "axios": "^1.6.2",
38
+ "cli-color": "^2.0.3",
39
+ "express": "^4.18.2",
40
+ "express-validator": "^7.0.1",
41
+ "jsonwebtoken": "^9.0.1",
42
+ "fs-extra": "^11.1.1",
43
+ "mongoose": "^7.3.1",
44
+ "mongoose-backpack": "^0.2.7",
45
+ "rest-api-response-npm": "^0.1.4"
46
+ },
47
+ "devDependencies": {
48
+ "uglify-js": "^3.17.4"
49
+ },
50
+ "bin": {
51
+ "nodejs-backpack": "./index.js"
52
+ }
53
+ }
package/readme.md ADDED
@@ -0,0 +1,155 @@
1
+ # NodeJs Backpack
2
+
3
+ NodeJs Backpack is a powerful tool designed to simplify the development of Node.js REST APIs with ease and precision. It provides a streamlined workflow by automatically generating Mongoose schemas and handling the necessary configurations in your project.
4
+
5
+ With just a few simple commands, NodeJs Backpack can create REST API components such as controllers and routes, while also ensuring route validation is implemented flawlessly. Additionally, NodeJs Backpack offers a command to generate sample files, providing a solid starting point for your project.
6
+
7
+ With NodeJs Backpack, you can quickly set up your project and focus on building your APIs, letting the tool handle the repetitive tasks and allowing you to follow a smooth development process.
8
+
9
+ ## Installation
10
+
11
+ Install package globally with npm
12
+
13
+ ```bash
14
+ npm install nodejs-backpack -g
15
+ ```
16
+
17
+ ## Features
18
+
19
+ - Robust REST APIs
20
+ - Focus on optimized code
21
+ - Auto file creation for schemas, routes, controllers and validations
22
+ - helpers (modelsParams, appendParams, etc)
23
+ - Mongoose DB support,
24
+ - AppendParams for append data in APIs using Mongoose schema
25
+ - Executable for generating applications quickly
26
+ - Auto create logic for API CRUD
27
+
28
+ ## YouTube Tutorial
29
+
30
+ [![Watch the video](https://img.youtube.com/vi/-L80PJucbEo/0.jpg)](https://youtu.be/-L80PJucbEo)
31
+
32
+ ## Quick Start (Rest APIs)
33
+
34
+ The quickest way to get started with nodejs-backpack is to utilize the executable to generate an REST APIs as shown below:
35
+
36
+ **Step1:** Create an empty directory:
37
+
38
+ ```bash
39
+ mkdir NodeJs-REST-APIs
40
+ ```
41
+
42
+ **Step2:** Enter into directory:
43
+
44
+ ```bash
45
+ cd NodeJs-REST-APIs
46
+ ```
47
+
48
+ **Step3:** Run Command:
49
+
50
+ ```bash
51
+ nodejs-backpack sample:files
52
+ ```
53
+
54
+ - File "`sample-app.js`", "`sample-package.json`" & "`.sample-env`" created in the root directory.
55
+ - **Rename sample files** to "**`app.js`**", "**`package.json`**" & "**`.env`**" which are created in the root directory.
56
+
57
+ ![](https://github.com/GohilJaykumar/sharable/blob/main/typing.gif)
58
+
59
+ - Update .env > **`DB=mongodb+srv...`** with valid connection.
60
+
61
+ ```bash
62
+ PORT=3000
63
+ DB="mongodb+srv://........mongodb.net/node_backpack"
64
+ JWT_SIGNATURE=node_backpack
65
+ HOST=http://localhost:3000
66
+ ```
67
+
68
+ **Step4:** Run Command:
69
+
70
+ ```bash
71
+ npm install
72
+ ```
73
+
74
+ **Step5:** Run Command:
75
+
76
+ ```bash
77
+ nodejs-backpack make:schema Tests
78
+ ```
79
+
80
+ **Step6:** Run Command:
81
+
82
+ ```bash
83
+ nodejs-backpack make:apis Test --url=tests --schema=Tests
84
+ ```
85
+
86
+ - Rename schema name in comand as per your requirement **_nodejs-backpack make:apis Test --url=tests --schema=Tests_**.
87
+ - Example: _nodejs-backpack make:apis **ROUTE_NAME** --url=**ROUTE_URL** --schema=**SCHEMA_NAME**_.
88
+ - **Note:** _`SCHEMA_NAME` must exist in model directory `/models/SCHEMA_NAME`_
89
+
90
+ **Step7:** Install 'nodemon' on global level for development purpose:
91
+
92
+ ```bash
93
+ npm install nodemon -g
94
+ ```
95
+
96
+ **Step8:** Now your APIs are ready to use and Server your project with:
97
+
98
+ ```bash
99
+ npm run dev
100
+ ```
101
+
102
+ **Step9:** Open Postman and create new collection and check the below apis:
103
+
104
+ - Based on my command,
105
+ **_nodejs-backpack make:apis `Test` --url=`tests` --schema=`Tests`_**.
106
+ - ROUTE_NAME = `Test`
107
+ - ROUTE_URL = `tests`
108
+ - SCHEMA_NAME = `Tests`
109
+ - Below are list of APIs created by commands `.../api/ROUTE_URL`:
110
+ - _**Get List API**_: **`GET:`** _`http://localhost:3000/api/tests?page_no=1&page_limit=20&search=` (Parameters: page_no, page_limit, search)_
111
+ - _**Get Detail API**_: **`GET:`** _`http://localhost:3000/api/tests/64a41036174844d0394e7b2f`_
112
+ - _**Store API**_: **`POST:`** _`http://localhost:3000/api/tests` (Body-Parameters: based on model schema)_
113
+ - _**Update API**_: **`PUT:`** _`http://localhost:3000/api/tests/64a41036174844d0394e7b2f` (Body-Parameters: based on model schema)_
114
+ - _**Delete API**_: **`DELETE:`** _`http://localhost:3000/api/tests/64a41036174844d0394e7b2f`_
115
+
116
+ ## Quick Start (Authentication APIs)
117
+
118
+ The quickest way to get started with **signup**, **register**, **forgot-password**, **reset-password**, **get-profile** API's using nodejs-backpack is to utilize the executable to generate an REST APIs as shown below:
119
+
120
+ **Step1:** Run Command:
121
+
122
+ ```bash
123
+ nodejs-backpack make:auth
124
+ ```
125
+
126
+ - Under **./routes/\*** '**IndexRoute.js**' and '**AuthRoute.js**' file will be create/updated.
127
+ - '**AuthController.js**' file will be create in the '**./controllers/AuthController.js**' folder with all neccessary logics.
128
+ - '**AuthMiddleware.js**' file will be create in the '**./middleware/AuthMiddleware.js**' folder with all neccessary JWT token verification logics.
129
+ - mailtrap.js file will be create in the '**./config/mailtrap.js**' folder where you can configure SMTP mail credentials.
130
+ - Under **./models/\*** '**User.js**' and '**ResetToken.js**' file will be create.
131
+
132
+ **Step2:** Open Postman and create new collection and check the below apis:
133
+
134
+ - Below are list of APIs created by commands `.../api/ROUTE_URL`:
135
+ - _**Register API**_: **`POST:`** _`http://localhost:3000/api/register` (Body-Parameters: first_name, last_name, email, password)_
136
+ - _**Login API**_: **`POST:`** _`http://localhost:3000/api/login` (Body-Parameters: email, password)_
137
+ - _**Forgot Password API**_: **`POST:`** _`http://localhost:3000/api/forgot-password` (Body-Parameters: email)_
138
+ - _**Reset Password API**_: **`POST:`** _`http://localhost:3000/api/reset-password` (Body-Parameters: email, password, reset_token)_. **Note**: Forgot password reset link will contain '**reset_token**' on mail.
139
+ - _**Logout API**_: **`GET:`** _`http://localhost:3000/api/logout`_
140
+ - _**Get Profile API**_: **`GET:`** _`http://localhost:3000/api/get-profile`_
141
+
142
+ ## Environment Variables
143
+
144
+ To run this project, you will need to add the following environment variables to your .env file.
145
+
146
+ ```bash
147
+ PORT=3000
148
+ DB="mongodb+srv://........mongodb.net/node_backpack"
149
+ JWT_SIGNATURE=node_backpack
150
+ HOST=http://localhost:3000
151
+ ```
152
+
153
+ ## Authors
154
+
155
+ - Jaykumar Gohil ([@jksk21](https://www.npmjs.com/~jksk21))
package/sample-app.js ADDED
@@ -0,0 +1,41 @@
1
+ const express = require("express");
2
+ const app = express();
3
+ const routes = require("./routes/IndexRoute");
4
+ const dotenv = require("dotenv").config().parsed;
5
+ const mongoose = require("mongoose");
6
+ const { catchError } = require("rest-api-response-npm");
7
+
8
+ app.use((req, res, next) => {
9
+ res.setHeader("Access-Control-Allow-Origin", "*");
10
+ res.setHeader(
11
+ "Access-Control-Allow-Methods",
12
+ "OPTIONS, GET, POST, PUT, PATCH, DELETE"
13
+ );
14
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
15
+ next();
16
+ });
17
+
18
+ // Routes
19
+ app.use("/api", routes);
20
+
21
+ // default error messgae
22
+ app.use((error, req, res, next) => {
23
+ catchError(res, error);
24
+ console.error(error);
25
+ });
26
+
27
+ // Serve files from the 'public' directory
28
+ app.use(express.static("public"));
29
+
30
+ // Start server mongooes and port
31
+ mongoose
32
+ .connect(dotenv.DB)
33
+ .then((result) => {
34
+ const port = dotenv.PORT;
35
+ app.listen(port, () => {
36
+ console.log(`Server started on port http://localhost:${port}`);
37
+ });
38
+ })
39
+ .catch((err) => {
40
+ console.log(err);
41
+ });
@@ -0,0 +1,217 @@
1
+ const User = require("../models/User"); //
2
+ const ResetToken = require("../models/ResetToken");
3
+ const bcrypt = require("bcryptjs");
4
+ const jwt = require("jsonwebtoken");
5
+ const dotenv = require("dotenv").config().parsed;
6
+ const crypto = require("crypto");
7
+ const {
8
+ successResponse,
9
+ checkValidationResult,
10
+ customResponse,
11
+ errorResponse,
12
+ } = require("rest-api-response-npm");
13
+ const nodemailer = require("../config/mailtrap");
14
+
15
+ const AuthController = {
16
+ signUp: (req, res, next) => {
17
+ const response = checkValidationResult(res, req);
18
+ if (response["status_code"] === 422) {
19
+ return errorResponse(
20
+ res,
21
+ response["data"],
22
+ response["message"],
23
+ response["status_code"]
24
+ );
25
+ }
26
+ const password = req.body.password;
27
+ bcrypt
28
+ .hash(password, 12)
29
+ .then((hashPw) => {
30
+ req.body.password = hashPw;
31
+ const user = new User(req.body);
32
+ return user.save();
33
+ })
34
+ .then((result) => {
35
+ return successResponse(res, result, "User Registerd Successfully");
36
+ })
37
+ .catch((err) => {
38
+ next(err);
39
+ });
40
+ },
41
+ login: (req, res, next) => {
42
+ const response = checkValidationResult(res, req);
43
+ if (response["status_code"] === 422) {
44
+ return errorResponse(
45
+ res,
46
+ response["data"],
47
+ response["message"],
48
+ response["status_code"]
49
+ );
50
+ }
51
+ const email = req.body.email;
52
+ const password = req.body.password;
53
+ let loadedUser;
54
+ User.findOne({ email: email })
55
+ .then((user) => {
56
+ loadedUser = user;
57
+ return bcrypt.compare(password, user.password);
58
+ })
59
+ .then((isEqual) => {
60
+ if (!isEqual) {
61
+ data = {
62
+ password: ["Wrong Password"],
63
+ };
64
+ return customResponse(res, data, "Wrong Password", 422);
65
+ }
66
+ // create new token using sign
67
+ return jwt.sign(
68
+ {
69
+ userId: loadedUser._id,
70
+ },
71
+ dotenv.JWT_SIGNATURE,
72
+ { expiresIn: "365d" }
73
+ );
74
+ })
75
+ .then((token) => {
76
+ loadedUser.token = token;
77
+ loadedUser.save();
78
+ return successResponse(
79
+ res,
80
+ { access_token: token, user_data: loadedUser },
81
+ "Login Successfully"
82
+ );
83
+ })
84
+ .catch((err) => {
85
+ next(err);
86
+ });
87
+ },
88
+ logout: (req, res, next) => {
89
+ const filter = { _id: req.userId };
90
+ const update = { token: "" };
91
+ User.findOneAndUpdate(filter, update)
92
+ .then(() => {
93
+ return successResponse(res, null, "You have been Logged Out");
94
+ })
95
+ .catch((err) => {
96
+ next(err);
97
+ });
98
+ },
99
+ forgotPassword: (req, res, next) => {
100
+ const response = checkValidationResult(res, req);
101
+ if (response["status_code"] === 422) {
102
+ return errorResponse(
103
+ res,
104
+ response["data"],
105
+ response["message"],
106
+ response["status_code"]
107
+ );
108
+ }
109
+ crypto.randomBytes(32, (err, buffer) => {
110
+ if (err) {
111
+ return customResponse(res, null, "Something went wrong", 400);
112
+ }
113
+ const token = buffer.toString("hex");
114
+ User.findOne({ email: req.body.email })
115
+ .then((user) => {
116
+ const reset_token = new ResetToken({
117
+ reset_token: token,
118
+ email: user.email,
119
+ });
120
+ return reset_token.save();
121
+ })
122
+ .then((result) => {
123
+ nodemailer.sendMail({
124
+ to: req.body.email,
125
+ from: "ats@technomarktest.io",
126
+ subject: "Password reset",
127
+ html: `
128
+ <p>You requested a password reset</p>
129
+ <p>Click this <a href="${dotenv?.HOST}/reset/?token=${token}&email=${req.body.email}">link</a> to set a new password.</p>
130
+ `,
131
+ });
132
+ return successResponse(
133
+ res,
134
+ null,
135
+ "Reset password link send your registerd email address"
136
+ );
137
+ })
138
+ .catch((err) => {
139
+ next(err);
140
+ });
141
+ });
142
+ },
143
+ resetPassword: (req, res, next) => {
144
+ const response = checkValidationResult(res, req);
145
+ if (response["status_code"] === 422) {
146
+ return errorResponse(
147
+ res,
148
+ response["data"],
149
+ response["message"],
150
+ response["status_code"]
151
+ );
152
+ }
153
+ const new_password = req.body.password;
154
+ const r_token = req.body.reset_token;
155
+ const email = req.body.email;
156
+ let resetUser;
157
+ ResetToken.findOne({
158
+ email: email,
159
+ reset_token: r_token,
160
+ })
161
+ .then((result) => {
162
+ if (!result) {
163
+ return customResponse(
164
+ res,
165
+ null,
166
+ `Reset token has expired. Please try the 'forgot password' option again to get a new reset token!`,
167
+ 401
168
+ );
169
+ }
170
+ return User.findOne({
171
+ email: email,
172
+ });
173
+ })
174
+ .then((user) => {
175
+ resetUser = user;
176
+ return bcrypt.hash(new_password, 12);
177
+ })
178
+ .then((hashedPassword) => {
179
+ resetUser.password = hashedPassword;
180
+ return resetUser.save();
181
+ })
182
+ .then((result1) => {
183
+ return ResetToken.findOneAndDelete({
184
+ email: email,
185
+ reset_token: r_token,
186
+ });
187
+ })
188
+ .then((result1) => {
189
+ return successResponse(res, null, "Your Password Change Successfully");
190
+ })
191
+ .catch((err) => {
192
+ next(err);
193
+ });
194
+ },
195
+ profile: (req, res, next) => {
196
+ const usertoken = req.headers.authorization;
197
+ const token = usertoken.split(" ");
198
+ const user = jwt.verify(token[1], dotenv.JWT_SIGNATURE);
199
+ User.findOne({ _id: user.userId })
200
+ .then((userData) => {
201
+ if (!userData) {
202
+ return customResponse(
203
+ res,
204
+ null,
205
+ "A user with this email could not be found",
206
+ 400
207
+ );
208
+ }
209
+ return successResponse(res, userData);
210
+ })
211
+ .catch((err) => {
212
+ next(err);
213
+ });
214
+ },
215
+ };
216
+
217
+ module.exports = AuthController;
@@ -0,0 +1,44 @@
1
+ const jwt = require("jsonwebtoken");
2
+ const dotenv = require("dotenv").config().parsed;
3
+ const User = require("../models/User"); //
4
+ const { customResponse } = require("rest-api-response-npm");
5
+
6
+ function authenticateToken(req, res, next) {
7
+ const authHeader = req.headers["authorization"];
8
+
9
+ if (authHeader) {
10
+ const token = authHeader.split(" ")[1];
11
+
12
+ if (token) {
13
+ try {
14
+ const jwt_secret_key = dotenv?.JWT_SIGNATURE;
15
+ const decoded = jwt.verify(token, jwt_secret_key);
16
+ // Token is valid, you can access the decoded payload
17
+ console.log("decoded?.data?.token", decoded?.userId);
18
+ if (decoded?.userId) {
19
+ User.findOne({ _id: decoded?.userId })
20
+ .then((userData) => {
21
+ console.log("token", token);
22
+ console.log("userData", userData);
23
+ if (userData && token === userData?.token) {
24
+ req.user = decoded.data;
25
+ req.userId = decoded.userId;
26
+ next();
27
+ } else {
28
+ return customResponse(res, null, "Token is expired", 401);
29
+ }
30
+ })
31
+ .catch((err) => {});
32
+ }
33
+ } catch (err) {
34
+ return customResponse(res, null, "Token is invalid or expired", 401);
35
+ }
36
+ } else {
37
+ return customResponse(res, null, "No token found", 401);
38
+ }
39
+ } else {
40
+ return customResponse(res, null, "No authorization header", 401);
41
+ }
42
+ }
43
+
44
+ module.exports = authenticateToken;
@@ -0,0 +1,19 @@
1
+ const express = require('express');
2
+ const router = express.Router();
3
+ const AuthController = require('../controllers/AuthController');
4
+ const signUpRequestValidationRequest = require('./validationRequest/Auth/signUpRequestValidationRequest');
5
+ const signInValidationRequest = require('./validationRequest/Auth/signInValidationRequest');
6
+ const forgotPasswordValidationRequest = require('./validationRequest/Auth/forgotPasswordValidationRequest');
7
+ const resetPasswordValidationRequest = require('./validationRequest/Auth/resetPasswordValidationRequest');
8
+ const formParser = require('../helpers/formParser');
9
+ const isAuth = require("../middleware/AuthMiddleware");
10
+
11
+
12
+ router.post(`/register`,formParser,signUpRequestValidationRequest, AuthController.signUp);
13
+ router.post(`/login`,formParser,signInValidationRequest, AuthController.login);
14
+ router.post(`/forgot-password`,formParser,forgotPasswordValidationRequest, AuthController.forgotPassword);
15
+ router.post(`/reset-password`,formParser,resetPasswordValidationRequest, AuthController.resetPassword);
16
+ router.get(`/logout`,formParser,isAuth, AuthController.logout);
17
+ router.get(`/get-profile`,formParser,isAuth, AuthController.profile);
18
+
19
+ module.exports = router;
@@ -0,0 +1,10 @@
1
+ const nodemailer = require("nodemailer");
2
+ module.exports = defaultExport = nodemailer.createTransport({
3
+ service: "mailtrap",
4
+ host: "sandbox.smtp.mailtrap.io",
5
+ port: 2525,
6
+ auth: {
7
+ user: "1f60b50#########",
8
+ pass: "f0dfc61#########",
9
+ },
10
+ });