jwtmoshiur 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/.env ADDED
@@ -0,0 +1,3 @@
1
+ # JWT Moshiur Configuration
2
+ JWT_SECRET=ljmsik0qrd6cg1h2kd3la
3
+ JWT_EXPIRY=24h
package/bin/cli.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { initializeJwtMoshiur } = require('../dist/setup');
4
+
5
+ console.log(' Initializing JWT Moshiur...');
6
+ initializeJwtMoshiur();
@@ -0,0 +1,8 @@
1
+ interface TokenPayload {
2
+ userId?: string;
3
+ email?: string;
4
+ role?: string;
5
+ [key: string]: any;
6
+ }
7
+ export declare function generateToken(payload: TokenPayload): string;
8
+ export {};
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateToken = generateToken;
4
+ const jwt = require('jsonwebtoken');
5
+ const dotenv = require('dotenv');
6
+ dotenv.config();
7
+ const JWT_SECRET = (process.env.JWT_SECRET || 'fallback-secret');
8
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
9
+ function generateToken(payload) {
10
+ return jwt.sign(payload, JWT_SECRET, {
11
+ expiresIn: JWT_EXPIRY
12
+ });
13
+ }
@@ -0,0 +1,11 @@
1
+ import { initializeJwtMoshiur } from './setup';
2
+ interface TokenPayload {
3
+ userId?: string;
4
+ email?: string;
5
+ role?: string;
6
+ [key: string]: any;
7
+ }
8
+ export declare function generateToken(payload: TokenPayload, options?: any): string;
9
+ export declare function verifyToken(token: string): any;
10
+ export declare function setup(): void;
11
+ export { initializeJwtMoshiur };
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initializeJwtMoshiur = void 0;
4
+ exports.generateToken = generateToken;
5
+ exports.verifyToken = verifyToken;
6
+ exports.setup = setup;
7
+ const jwt = require('jsonwebtoken');
8
+ const dotenv = require('dotenv');
9
+ const setup_1 = require("./setup");
10
+ Object.defineProperty(exports, "initializeJwtMoshiur", { enumerable: true, get: function () { return setup_1.initializeJwtMoshiur; } });
11
+ dotenv.config();
12
+ const JWT_SECRET = (process.env.JWT_SECRET || 'fallback-secret');
13
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '1h';
14
+ function generateToken(payload, options) {
15
+ return jwt.sign(payload, JWT_SECRET, {
16
+ expiresIn: JWT_EXPIRY,
17
+ ...options
18
+ });
19
+ }
20
+ function verifyToken(token) {
21
+ try {
22
+ return jwt.verify(token, JWT_SECRET);
23
+ }
24
+ catch (error) {
25
+ throw new Error('Invalid or expired token');
26
+ }
27
+ }
28
+ function setup() {
29
+ return (0, setup_1.initializeJwtMoshiur)();
30
+ }
@@ -0,0 +1 @@
1
+ export declare function initializeJwtMoshiur(): void;
package/dist/setup.js ADDED
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.initializeJwtMoshiur = initializeJwtMoshiur;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const child_process_1 = require("child_process");
10
+ function initializeJwtMoshiur() {
11
+ const projectRoot = process.cwd();
12
+ // Generate a random secret if JWT_SECRET is not provided
13
+ const randomSecret = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
14
+ // Create .env with JWT configuration
15
+ const envContent = `# JWT Moshiur Configuration
16
+ JWT_SECRET=${randomSecret}
17
+ JWT_EXPIRY=24h
18
+ `;
19
+ // Check if .env exists, if not create it
20
+ const envPath = path_1.default.join(projectRoot, '.env');
21
+ if (!fs_1.default.existsSync(envPath)) {
22
+ fs_1.default.writeFileSync(envPath, envContent);
23
+ console.log('āœ“ .env file created with JWT configuration');
24
+ }
25
+ else {
26
+ // Check if JWT_SECRET already exists
27
+ const envData = fs_1.default.readFileSync(envPath, 'utf-8');
28
+ if (!envData.includes('JWT_SECRET')) {
29
+ fs_1.default.appendFileSync(envPath, `\n${envContent}`);
30
+ console.log('āœ“ JWT configuration added to existing .env');
31
+ }
32
+ else {
33
+ console.log('āœ“ JWT configuration already exists in .env');
34
+ }
35
+ }
36
+ // Create utils directory
37
+ const utilsDir = path_1.default.join(projectRoot, 'utils');
38
+ if (!fs_1.default.existsSync(utilsDir)) {
39
+ fs_1.default.mkdirSync(utilsDir);
40
+ }
41
+ // Determine if this is a TypeScript project
42
+ const isTypeScript = fs_1.default.existsSync(path_1.default.join(projectRoot, 'tsconfig.json'));
43
+ // Get the path to templates in the jwtmoshiur package
44
+ const packageDir = path_1.default.dirname(path_1.default.dirname(__filename)); // Go up from dist to package root
45
+ const templatesDir = path_1.default.join(packageDir, 'dist', 'templates');
46
+ // If templates not found in dist, try src (for development)
47
+ const actualTemplatesDir = fs_1.default.existsSync(templatesDir)
48
+ ? templatesDir
49
+ : path_1.default.join(packageDir, 'src', 'templates');
50
+ // Generate token function content
51
+ const generateTokenContent = `const jwt = require('jsonwebtoken');
52
+ const dotenv = require('dotenv');
53
+
54
+ dotenv.config();
55
+
56
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
57
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
58
+
59
+ function generateToken(payload) {
60
+ return jwt.sign(payload, JWT_SECRET, {
61
+ expiresIn: JWT_EXPIRY
62
+ });
63
+ }
64
+
65
+ module.exports = { generateToken };
66
+ `;
67
+ // Generate token TS content
68
+ const generateTokenTsContent = `import jwt from 'jsonwebtoken';
69
+ import dotenv from 'dotenv';
70
+
71
+ dotenv.config();
72
+
73
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
74
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
75
+
76
+ interface TokenPayload {
77
+ userId: string;
78
+ email: string;
79
+ role?: string;
80
+ [key: string]: any;
81
+ }
82
+
83
+ export function generateToken(payload: TokenPayload): string {
84
+ return jwt.sign(payload, JWT_SECRET, {
85
+ expiresIn: JWT_EXPIRY
86
+ });
87
+ }
88
+ `;
89
+ // Verify token function content
90
+ const verifyTokenContent = `const jwt = require('jsonwebtoken');
91
+ const dotenv = require('dotenv');
92
+
93
+ dotenv.config();
94
+
95
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
96
+
97
+ function verifyToken(token) {
98
+ try {
99
+ return jwt.verify(token, JWT_SECRET);
100
+ } catch (error) {
101
+ throw new Error('Invalid or expired token');
102
+ }
103
+ }
104
+
105
+ module.exports = { verifyToken };
106
+ `;
107
+ // Verify token TS content
108
+ const verifyTokenTsContent = `import jwt from 'jsonwebtoken';
109
+ import dotenv from 'dotenv';
110
+
111
+ dotenv.config();
112
+
113
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
114
+
115
+ export function verifyToken(token: string): any {
116
+ try {
117
+ return jwt.verify(token, JWT_SECRET);
118
+ } catch (error) {
119
+ throw new Error('Invalid or expired token');
120
+ }
121
+ }
122
+ `;
123
+ // Create token files based on project type
124
+ if (isTypeScript) {
125
+ const generateTokenPath = path_1.default.join(utilsDir, 'generateToken.ts');
126
+ const verifyTokenPath = path_1.default.join(utilsDir, 'verifyToken.ts');
127
+ if (!fs_1.default.existsSync(generateTokenPath)) {
128
+ fs_1.default.writeFileSync(generateTokenPath, generateTokenTsContent);
129
+ console.log('āœ“ generateToken.ts created in utils folder');
130
+ }
131
+ if (!fs_1.default.existsSync(verifyTokenPath)) {
132
+ fs_1.default.writeFileSync(verifyTokenPath, verifyTokenTsContent);
133
+ console.log('āœ“ verifyToken.ts created in utils folder');
134
+ }
135
+ }
136
+ else {
137
+ const generateTokenPath = path_1.default.join(utilsDir, 'generateToken.js');
138
+ const verifyTokenPath = path_1.default.join(utilsDir, 'verifyToken.js');
139
+ if (!fs_1.default.existsSync(generateTokenPath)) {
140
+ fs_1.default.writeFileSync(generateTokenPath, generateTokenContent);
141
+ console.log('āœ“ generateToken.js created in utils folder');
142
+ }
143
+ if (!fs_1.default.existsSync(verifyTokenPath)) {
144
+ fs_1.default.writeFileSync(verifyTokenPath, verifyTokenContent);
145
+ console.log('āœ“ verifyToken.js created in utils folder');
146
+ }
147
+ }
148
+ // Install necessary packages if not already installed
149
+ console.log('šŸ“¦ Checking dependencies...');
150
+ try {
151
+ const packageJsonPath = path_1.default.join(projectRoot, 'package.json');
152
+ if (fs_1.default.existsSync(packageJsonPath)) {
153
+ const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf-8'));
154
+ const hasJwt = packageJson.dependencies?.jsonwebtoken || packageJson.devDependencies?.jsonwebtoken;
155
+ const hasDotenv = packageJson.dependencies?.dotenv || packageJson.devDependencies?.dotenv;
156
+ if (!hasJwt || !hasDotenv) {
157
+ (0, child_process_1.execSync)('npm install jsonwebtoken dotenv', { stdio: 'inherit' });
158
+ }
159
+ if (isTypeScript) {
160
+ const hasTypes = packageJson.devDependencies?.['@types/jsonwebtoken'];
161
+ if (!hasTypes) {
162
+ (0, child_process_1.execSync)('npm install --save-dev @types/jsonwebtoken', { stdio: 'inherit' });
163
+ }
164
+ }
165
+ }
166
+ }
167
+ catch (error) {
168
+ console.log('⚠ Warning: Could not verify or install dependencies');
169
+ }
170
+ console.log('\nšŸŽ‰ JWT Moshiur setup complete!');
171
+ console.log('šŸ“ Next steps:');
172
+ console.log(' 1. Edit .env and change JWT_SECRET to a strong secret key');
173
+ console.log(' 2. Import and use generateToken() and verifyToken() from utils/');
174
+ }
@@ -0,0 +1,8 @@
1
+ interface TokenPayload {
2
+ userId?: string;
3
+ email?: string;
4
+ role?: string;
5
+ [key: string]: any;
6
+ }
7
+ export declare function generateToken(payload: TokenPayload): string;
8
+ export {};
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateToken = generateToken;
4
+ const jwt = require('jsonwebtoken');
5
+ const dotenv = require('dotenv');
6
+ dotenv.config();
7
+ const JWT_SECRET = (process.env.JWT_SECRET || 'fallback-secret');
8
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
9
+ function generateToken(payload) {
10
+ return jwt.sign(payload, JWT_SECRET, {
11
+ expiresIn: JWT_EXPIRY
12
+ });
13
+ }
@@ -0,0 +1 @@
1
+ export declare function verifyToken(token: string): any;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.verifyToken = verifyToken;
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const dotenv_1 = __importDefault(require("dotenv"));
9
+ dotenv_1.default.config();
10
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
11
+ function verifyToken(token) {
12
+ try {
13
+ return jsonwebtoken_1.default.verify(token, JWT_SECRET);
14
+ }
15
+ catch (error) {
16
+ throw new Error('Invalid or expired token');
17
+ }
18
+ }
@@ -0,0 +1 @@
1
+ export declare function verifyToken(token: string): any;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.verifyToken = verifyToken;
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const dotenv_1 = __importDefault(require("dotenv"));
9
+ dotenv_1.default.config();
10
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
11
+ function verifyToken(token) {
12
+ try {
13
+ return jsonwebtoken_1.default.verify(token, JWT_SECRET);
14
+ }
15
+ catch (error) {
16
+ throw new Error('Invalid or expired token');
17
+ }
18
+ }
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "jwtmoshiur",
3
+ "version": "1.0.0",
4
+ "description": "JWT auto-setup package with token generation and verification",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "bin": {
8
+ "jwtmoshiur": "bin/cli.js"
9
+ },
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "prepublishOnly": "npm run build",
13
+ "postinstall": "node bin/cli.js"
14
+ },
15
+ "keywords": ["jwtmoshiur","jwt", "authentication", "token", "security"],
16
+ "author": "Moshiur Rahman Deap",
17
+ "license": "MIT",
18
+ "dependencies": {
19
+ "dotenv": "^17.4.2",
20
+ "jsonwebtoken": "^9.0.3"
21
+ },
22
+ "devDependencies": {
23
+ "@types/jsonwebtoken": "^9.0.10",
24
+ "@types/node": "^25.8.0",
25
+ "typescript": "^6.0.3"
26
+ }
27
+ }
package/readme.md ADDED
@@ -0,0 +1,295 @@
1
+ # šŸ” JWT Moshiur
2
+
3
+ > Zero-configuration JWT token generator and verifier with automatic project setup.
4
+
5
+ A lightweight, zero-configuration npm package that automatically sets up JWT authentication for your Node.js projects. Install once, get JWT utilities instantly!
6
+
7
+ [![npm version](https://img.shields.io/npm/v/jwtmoshiur.svg)](https://www.npmjs.com/package/jwtmoshiur)
8
+ [![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
9
+
10
+ ## ✨ Features
11
+
12
+ - šŸš€ **Zero Configuration** - Automatic setup on installation
13
+ - šŸ“ **Auto Project Setup** - Generates `.env` and utility files
14
+ - šŸ”‘ **Generate Tokens** - Simple, intuitive token creation
15
+ - āœ… **Verify Tokens** - Built-in token validation
16
+ - šŸ›”ļø **Secure** - Uses industry-standard `jsonwebtoken` library
17
+ - šŸ“¦ **Lightweight** - Minimal dependencies
18
+ - šŸŽÆ **TypeScript Ready** - Full TypeScript support
19
+ - ⚔ **Easy Integration** - Works with any Node.js project
20
+
21
+ ## šŸ“¦ Installation
22
+
23
+ ```bash
24
+ npm install jwtmoshiur
25
+ ```
26
+
27
+ That's it! The package automatically:
28
+ - āœ… Creates a `.env` file with secure JWT configuration
29
+ - āœ… Generates `utils/generateToken.js` (or `.ts` for TypeScript projects)
30
+ - āœ… Generates `utils/verifyToken.js` (or `.ts`)
31
+ - āœ… Installs all required dependencies
32
+
33
+ ## šŸš€ Quick Start
34
+
35
+ ### 1. Generate a Token
36
+
37
+ ```javascript
38
+ const { generateToken } = require('./utils/generateToken');
39
+
40
+ const token = generateToken({
41
+ userId: '12345',
42
+ email: 'user@example.com',
43
+ role: 'admin'
44
+ });
45
+
46
+ console.log(token);
47
+ // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
48
+ ```
49
+
50
+ ### 2. Verify a Token
51
+
52
+ ```javascript
53
+ const { verifyToken } = require('./utils/verifyToken');
54
+
55
+ try {
56
+ const decoded = verifyToken(token);
57
+ console.log(decoded);
58
+ // { userId: '12345', email: 'user@example.com', role: 'admin', iat: 1715772..., exp: 1715858... }
59
+ } catch (error) {
60
+ console.error('Token is invalid or expired');
61
+ }
62
+ ```
63
+
64
+ ## šŸ“š Usage Examples
65
+
66
+ ### Express.js Authentication Middleware
67
+
68
+ ```javascript
69
+ const express = require('express');
70
+ const { verifyToken } = require('./utils/verifyToken');
71
+ const { generateToken } = require('./utils/generateToken');
72
+
73
+ const app = express();
74
+
75
+ // Middleware to protect routes
76
+ const authMiddleware = (req, res, next) => {
77
+ const token = req.headers.authorization?.split(' ')[1];
78
+
79
+ if (!token) {
80
+ return res.status(401).json({ error: 'No token provided' });
81
+ }
82
+
83
+ try {
84
+ req.user = verifyToken(token);
85
+ next();
86
+ } catch (error) {
87
+ res.status(401).json({ error: 'Invalid token' });
88
+ }
89
+ };
90
+
91
+ // Login endpoint
92
+ app.post('/login', (req, res) => {
93
+ const user = { id: 1, email: 'user@example.com' };
94
+ const token = generateToken(user);
95
+ res.json({ token });
96
+ });
97
+
98
+ // Protected endpoint
99
+ app.get('/profile', authMiddleware, (req, res) => {
100
+ res.json({ user: req.user });
101
+ });
102
+
103
+ app.listen(3000, () => console.log('Server running on port 3000'));
104
+ ```
105
+
106
+ ### Async/Await Pattern
107
+
108
+ ```javascript
109
+ const { generateToken, verifyToken } = require('./utils');
110
+
111
+ async function authenticateUser(credentials) {
112
+ try {
113
+ // Generate token for user
114
+ const token = generateToken({
115
+ userId: credentials.id,
116
+ email: credentials.email,
117
+ timestamp: Date.now()
118
+ });
119
+
120
+ // Later, verify the token
121
+ const payload = verifyToken(token);
122
+ console.log('User authenticated:', payload.email);
123
+
124
+ return payload;
125
+ } catch (error) {
126
+ console.error('Authentication failed:', error.message);
127
+ throw error;
128
+ }
129
+ }
130
+ ```
131
+
132
+ ### Custom Token Expiry
133
+
134
+ ```javascript
135
+ const { generateToken } = require('./utils/generateToken');
136
+
137
+ // Create a token that expires in 1 hour
138
+ const shortToken = generateToken(
139
+ { userId: '123' }
140
+ );
141
+
142
+ // The expiry is controlled by JWT_EXPIRY in .env
143
+ // Default: 24h
144
+ // Options: 1h, 7d, 30d, etc.
145
+ ```
146
+
147
+ ## āš™ļø Configuration
148
+
149
+ Edit your `.env` file to customize JWT settings:
150
+
151
+ ```env
152
+ # JWT Moshiur Configuration
153
+ JWT_SECRET=your-super-secret-key-change-this-in-production
154
+ JWT_EXPIRY=24h
155
+ ```
156
+
157
+ ### Environment Variables
158
+
159
+ | Variable | Default | Description |
160
+ |----------|---------|-------------|
161
+ | `JWT_SECRET` | Generated | Secret key for signing tokens (change this!) |
162
+ | `JWT_EXPIRY` | `24h` | Token expiration time (`1h`, `7d`, `30d`, etc.) |
163
+
164
+ **āš ļø Important:** Always change `JWT_SECRET` to a strong, unique value in production!
165
+
166
+ ## šŸ“– API Reference
167
+
168
+ ### `generateToken(payload: object): string`
169
+
170
+ Generates a signed JWT token.
171
+
172
+ **Parameters:**
173
+ - `payload` (object): Data to encode in the token
174
+
175
+ **Returns:** JWT token string
176
+
177
+ **Example:**
178
+ ```javascript
179
+ const token = generateToken({
180
+ userId: '123',
181
+ email: 'user@example.com',
182
+ role: 'user'
183
+ });
184
+ ```
185
+
186
+ ### `verifyToken(token: string): object`
187
+
188
+ Verifies and decodes a JWT token.
189
+
190
+ **Parameters:**
191
+ - `token` (string): JWT token to verify
192
+
193
+ **Returns:** Decoded payload object
194
+
195
+ **Throws:** Error if token is invalid or expired
196
+
197
+ **Example:**
198
+ ```javascript
199
+ try {
200
+ const payload = verifyToken(token);
201
+ console.log('Valid token:', payload);
202
+ } catch (error) {
203
+ console.log('Invalid token:', error.message);
204
+ }
205
+ ```
206
+
207
+ ## šŸ”„ Manual Setup
208
+
209
+ If you need to re-run the setup process:
210
+
211
+ ```bash
212
+ npx jwtmoshiur
213
+ ```
214
+
215
+ This will regenerate the `.env` file and utility files if they don't exist.
216
+
217
+ ## šŸ“ Project Structure
218
+
219
+ After installation, your project will have:
220
+
221
+ ```
222
+ your-project/
223
+ ā”œā”€ā”€ .env
224
+ ā”œā”€ā”€ utils/
225
+ │ ā”œā”€ā”€ generateToken.js
226
+ │ └── verifyToken.js
227
+ ā”œā”€ā”€ node_modules/
228
+ │ └── jwtmoshiur/
229
+ └── package.json
230
+ ```
231
+
232
+ ## šŸ” Security Best Practices
233
+
234
+ 1. **Never commit `.env` to version control**
235
+ ```bash
236
+ # Add to .gitignore
237
+ .env
238
+ .env.local
239
+ ```
240
+
241
+ 2. **Use strong secrets**
242
+ ```bash
243
+ # Generate a strong secret (Linux/Mac)
244
+ openssl rand -base64 32
245
+
246
+ # Or use a random string generator
247
+ node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
248
+ ```
249
+
250
+ 3. **Rotate secrets regularly** in production
251
+
252
+ 4. **Use HTTPS** only in production
253
+
254
+ 5. **Set appropriate expiry times** for your use case
255
+
256
+ ## šŸ› ļø Troubleshooting
257
+
258
+ ### Issue: Token generation fails
259
+ **Solution:** Ensure `JWT_SECRET` is set in `.env`
260
+
261
+ ### Issue: "Invalid token" error
262
+ **Solution:** Verify the token hasn't expired or been tampered with
263
+
264
+ ### Issue: `.env` not created
265
+ **Solution:** Run `npx jwtmoshiur` to manually trigger setup
266
+
267
+ ## šŸ“‹ Requirements
268
+
269
+ - Node.js >= 14.0.0
270
+ - npm >= 6.0.0
271
+
272
+ ## šŸ“¦ Dependencies
273
+
274
+ - `jsonwebtoken` - JWT signing and verification
275
+ - `dotenv` - Environment variable management
276
+
277
+ ## šŸ“„ License
278
+
279
+ MIT License - see LICENSE file for details
280
+
281
+ ## šŸ‘Øā€šŸ’» Author
282
+
283
+ Created by **Moshiur Rahman Deap**
284
+
285
+ ## šŸ¤ Contributing
286
+
287
+ Contributions are welcome! Feel free to submit issues and pull requests.
288
+
289
+ ## šŸ“ž Support
290
+
291
+ If you have any questions or issues, please open an issue on GitHub or contact the maintainer.
292
+
293
+ ---
294
+
295
+ **Happy coding! šŸŽ‰**
@@ -0,0 +1,20 @@
1
+ const jwt = require('jsonwebtoken');
2
+ const dotenv = require('dotenv');
3
+
4
+ dotenv.config();
5
+
6
+ const JWT_SECRET: string = (process.env.JWT_SECRET || 'fallback-secret') as string;
7
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
8
+
9
+ interface TokenPayload {
10
+ userId?: string;
11
+ email?: string;
12
+ role?: string;
13
+ [key: string]: any;
14
+ }
15
+
16
+ export function generateToken(payload: TokenPayload): string {
17
+ return jwt.sign(payload, JWT_SECRET, {
18
+ expiresIn: JWT_EXPIRY
19
+ });
20
+ }
package/src/index.ts ADDED
@@ -0,0 +1,36 @@
1
+ const jwt = require('jsonwebtoken');
2
+ const dotenv = require('dotenv');
3
+ import { initializeJwtMoshiur } from './setup';
4
+
5
+ dotenv.config();
6
+
7
+ const JWT_SECRET: string = (process.env.JWT_SECRET || 'fallback-secret') as string;
8
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '1h';
9
+
10
+ interface TokenPayload {
11
+ userId?: string;
12
+ email?: string;
13
+ role?: string;
14
+ [key: string]: any;
15
+ }
16
+
17
+ export function generateToken(payload: TokenPayload, options?: any): string {
18
+ return jwt.sign(payload, JWT_SECRET, {
19
+ expiresIn: JWT_EXPIRY,
20
+ ...options
21
+ });
22
+ }
23
+
24
+ export function verifyToken(token: string): any {
25
+ try {
26
+ return jwt.verify(token, JWT_SECRET);
27
+ } catch (error) {
28
+ throw new Error('Invalid or expired token');
29
+ }
30
+ }
31
+
32
+ export function setup() {
33
+ return initializeJwtMoshiur();
34
+ }
35
+
36
+ export { initializeJwtMoshiur };
package/src/setup.ts ADDED
@@ -0,0 +1,185 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { execSync } from 'child_process';
4
+
5
+ export function initializeJwtMoshiur() {
6
+ const projectRoot = process.cwd();
7
+
8
+ // Generate a random secret if JWT_SECRET is not provided
9
+ const randomSecret = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
10
+
11
+ // Create .env with JWT configuration
12
+ const envContent = `# JWT Moshiur Configuration
13
+ JWT_SECRET=${randomSecret}
14
+ JWT_EXPIRY=24h
15
+ `;
16
+
17
+ // Check if .env exists, if not create it
18
+ const envPath = path.join(projectRoot, '.env');
19
+ if (!fs.existsSync(envPath)) {
20
+ fs.writeFileSync(envPath, envContent);
21
+ console.log('āœ“ .env file created with JWT configuration');
22
+ } else {
23
+ // Check if JWT_SECRET already exists
24
+ const envData = fs.readFileSync(envPath, 'utf-8');
25
+ if (!envData.includes('JWT_SECRET')) {
26
+ fs.appendFileSync(envPath, `\n${envContent}`);
27
+ console.log('āœ“ JWT configuration added to existing .env');
28
+ } else {
29
+ console.log('āœ“ JWT configuration already exists in .env');
30
+ }
31
+ }
32
+
33
+ // Create utils directory
34
+ const utilsDir = path.join(projectRoot, 'utils');
35
+ if (!fs.existsSync(utilsDir)) {
36
+ fs.mkdirSync(utilsDir);
37
+ }
38
+
39
+ // Determine if this is a TypeScript project
40
+ const isTypeScript = fs.existsSync(path.join(projectRoot, 'tsconfig.json'));
41
+
42
+ // Get the path to templates in the jwtmoshiur package
43
+ const packageDir = path.dirname(path.dirname(__filename)); // Go up from dist to package root
44
+ const templatesDir = path.join(packageDir, 'dist', 'templates');
45
+
46
+ // If templates not found in dist, try src (for development)
47
+ const actualTemplatesDir = fs.existsSync(templatesDir)
48
+ ? templatesDir
49
+ : path.join(packageDir, 'src', 'templates');
50
+
51
+ // Generate token function content
52
+ const generateTokenContent = `const jwt = require('jsonwebtoken');
53
+ const dotenv = require('dotenv');
54
+
55
+ dotenv.config();
56
+
57
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
58
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
59
+
60
+ function generateToken(payload) {
61
+ return jwt.sign(payload, JWT_SECRET, {
62
+ expiresIn: JWT_EXPIRY
63
+ });
64
+ }
65
+
66
+ module.exports = { generateToken };
67
+ `;
68
+
69
+ // Generate token TS content
70
+ const generateTokenTsContent = `import jwt from 'jsonwebtoken';
71
+ import dotenv from 'dotenv';
72
+
73
+ dotenv.config();
74
+
75
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
76
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
77
+
78
+ interface TokenPayload {
79
+ userId: string;
80
+ email: string;
81
+ role?: string;
82
+ [key: string]: any;
83
+ }
84
+
85
+ export function generateToken(payload: TokenPayload): string {
86
+ return jwt.sign(payload, JWT_SECRET, {
87
+ expiresIn: JWT_EXPIRY
88
+ });
89
+ }
90
+ `;
91
+
92
+ // Verify token function content
93
+ const verifyTokenContent = `const jwt = require('jsonwebtoken');
94
+ const dotenv = require('dotenv');
95
+
96
+ dotenv.config();
97
+
98
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
99
+
100
+ function verifyToken(token) {
101
+ try {
102
+ return jwt.verify(token, JWT_SECRET);
103
+ } catch (error) {
104
+ throw new Error('Invalid or expired token');
105
+ }
106
+ }
107
+
108
+ module.exports = { verifyToken };
109
+ `;
110
+
111
+ // Verify token TS content
112
+ const verifyTokenTsContent = `import jwt from 'jsonwebtoken';
113
+ import dotenv from 'dotenv';
114
+
115
+ dotenv.config();
116
+
117
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
118
+
119
+ export function verifyToken(token: string): any {
120
+ try {
121
+ return jwt.verify(token, JWT_SECRET);
122
+ } catch (error) {
123
+ throw new Error('Invalid or expired token');
124
+ }
125
+ }
126
+ `;
127
+
128
+ // Create token files based on project type
129
+ if (isTypeScript) {
130
+ const generateTokenPath = path.join(utilsDir, 'generateToken.ts');
131
+ const verifyTokenPath = path.join(utilsDir, 'verifyToken.ts');
132
+
133
+ if (!fs.existsSync(generateTokenPath)) {
134
+ fs.writeFileSync(generateTokenPath, generateTokenTsContent);
135
+ console.log('āœ“ generateToken.ts created in utils folder');
136
+ }
137
+
138
+ if (!fs.existsSync(verifyTokenPath)) {
139
+ fs.writeFileSync(verifyTokenPath, verifyTokenTsContent);
140
+ console.log('āœ“ verifyToken.ts created in utils folder');
141
+ }
142
+ } else {
143
+ const generateTokenPath = path.join(utilsDir, 'generateToken.js');
144
+ const verifyTokenPath = path.join(utilsDir, 'verifyToken.js');
145
+
146
+ if (!fs.existsSync(generateTokenPath)) {
147
+ fs.writeFileSync(generateTokenPath, generateTokenContent);
148
+ console.log('āœ“ generateToken.js created in utils folder');
149
+ }
150
+
151
+ if (!fs.existsSync(verifyTokenPath)) {
152
+ fs.writeFileSync(verifyTokenPath, verifyTokenContent);
153
+ console.log('āœ“ verifyToken.js created in utils folder');
154
+ }
155
+ }
156
+
157
+ // Install necessary packages if not already installed
158
+ console.log('šŸ“¦ Checking dependencies...');
159
+ try {
160
+ const packageJsonPath = path.join(projectRoot, 'package.json');
161
+ if (fs.existsSync(packageJsonPath)) {
162
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
163
+ const hasJwt = packageJson.dependencies?.jsonwebtoken || packageJson.devDependencies?.jsonwebtoken;
164
+ const hasDotenv = packageJson.dependencies?.dotenv || packageJson.devDependencies?.dotenv;
165
+
166
+ if (!hasJwt || !hasDotenv) {
167
+ execSync('npm install jsonwebtoken dotenv', { stdio: 'inherit' });
168
+ }
169
+
170
+ if (isTypeScript) {
171
+ const hasTypes = packageJson.devDependencies?.['@types/jsonwebtoken'];
172
+ if (!hasTypes) {
173
+ execSync('npm install --save-dev @types/jsonwebtoken', { stdio: 'inherit' });
174
+ }
175
+ }
176
+ }
177
+ } catch (error) {
178
+ console.log('⚠ Warning: Could not verify or install dependencies');
179
+ }
180
+
181
+ console.log('\nšŸŽ‰ JWT Moshiur setup complete!');
182
+ console.log('šŸ“ Next steps:');
183
+ console.log(' 1. Edit .env and change JWT_SECRET to a strong secret key');
184
+ console.log(' 2. Import and use generateToken() and verifyToken() from utils/');
185
+ }
@@ -0,0 +1,3 @@
1
+ # JWT Moshiur Configuration
2
+ JWT_SECRET=your-super-secret-key-change-this-placeholder
3
+ JWT_EXPIRY=24h
@@ -0,0 +1,20 @@
1
+ const jwt = require('jsonwebtoken');
2
+ const dotenv = require('dotenv');
3
+
4
+ dotenv.config();
5
+
6
+ const JWT_SECRET: string = (process.env.JWT_SECRET || 'fallback-secret') as string;
7
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
8
+
9
+ interface TokenPayload {
10
+ userId?: string;
11
+ email?: string;
12
+ role?: string;
13
+ [key: string]: any;
14
+ }
15
+
16
+ export function generateToken(payload: TokenPayload): string {
17
+ return jwt.sign(payload, JWT_SECRET, {
18
+ expiresIn: JWT_EXPIRY
19
+ });
20
+ }
@@ -0,0 +1,14 @@
1
+ import jwt from 'jsonwebtoken';
2
+ import dotenv from 'dotenv';
3
+
4
+ dotenv.config();
5
+
6
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
7
+
8
+ export function verifyToken(token: string): any {
9
+ try {
10
+ return jwt.verify(token, JWT_SECRET);
11
+ } catch (error) {
12
+ throw new Error('Invalid or expired token');
13
+ }
14
+ }
@@ -0,0 +1,14 @@
1
+ import jwt from 'jsonwebtoken';
2
+ import dotenv from 'dotenv';
3
+
4
+ dotenv.config();
5
+
6
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
7
+
8
+ export function verifyToken(token: string): any {
9
+ try {
10
+ return jwt.verify(token, JWT_SECRET);
11
+ } catch (error) {
12
+ throw new Error('Invalid or expired token');
13
+ }
14
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "commonjs",
5
+ "declaration": true,
6
+ "outDir": "./dist",
7
+ "rootDir": "./src",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true
11
+ },
12
+ "include": ["src/**/*"],
13
+ "exclude": ["node_modules", "dist"]
14
+ }
@@ -0,0 +1,20 @@
1
+ import jwt from 'jsonwebtoken';
2
+ import dotenv from 'dotenv';
3
+
4
+ dotenv.config();
5
+
6
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
7
+ const JWT_EXPIRY = process.env.JWT_EXPIRY || '24h';
8
+
9
+ interface TokenPayload {
10
+ userId: string;
11
+ email: string;
12
+ role?: string;
13
+ [key: string]: any;
14
+ }
15
+
16
+ export function generateToken(payload: TokenPayload): string {
17
+ return jwt.sign(payload, JWT_SECRET, {
18
+ expiresIn: JWT_EXPIRY
19
+ });
20
+ }
@@ -0,0 +1,14 @@
1
+ import jwt from 'jsonwebtoken';
2
+ import dotenv from 'dotenv';
3
+
4
+ dotenv.config();
5
+
6
+ const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret';
7
+
8
+ export function verifyToken(token: string): any {
9
+ try {
10
+ return jwt.verify(token, JWT_SECRET);
11
+ } catch (error) {
12
+ throw new Error('Invalid or expired token');
13
+ }
14
+ }