jwtmoshiur 1.1.1 → 1.1.2

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/readme.md +79 -108
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jwtmoshiur",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "JWT auto-setup package with token generation and verification",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/readme.md CHANGED
@@ -1,42 +1,36 @@
1
- # 🔐 JWT Moshiur
1
+ ![JWT Moshiur](https://i.postimg.cc/wTPjXQF8/jwtmoshiur.gif)
2
2
 
3
- > Zero-configuration JWT token generator and verifier with automatic project setup.
3
+ # JWT Moshiur
4
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!
5
+ JWT Moshiur is a zero-configuration npm package for quickly adding JWT token generation and verification to Node.js applications. It creates the necessary project files automatically and keeps integration simple.
6
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)
7
+ [![npm version](https://img.shields.io/npm/v/jwtmoshiur.svg)](https://www.npmjs.com/package/jwtmoshiur) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
9
8
 
10
- ## ✨ Features
9
+ ## Overview
11
10
 
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
11
+ JWT Moshiur simplifies JWT integration by generating a `.env` file and utility scripts during installation. The package supports both JavaScript and TypeScript projects, so you can begin issuing and validating tokens with minimal setup.
20
12
 
21
- ## Installation
13
+ ## Installation
22
14
 
23
15
  ```bash
24
16
  npm install jwtmoshiur
25
17
  ```
26
- # After running npm install jwtmoshiur then just run below command and boom 💥
18
+
19
+ Once installation completes, run the setup command to generate configuration and utility files:
20
+
27
21
  ```bash
28
22
  npx jwtmoshiur
29
23
  ```
30
24
 
31
- That's it! The package automatically:
32
- - Creates a `.env` file with secure JWT configuration
33
- - Generates `utils/generateToken.js` (or `.ts` for TypeScript projects)
34
- - Generates `utils/verifyToken.js` (or `.ts`)
35
- - Installs all required dependencies
25
+ After this command, your project will contain:
36
26
 
37
- ## Quick Start
27
+ - `.env` with JWT configuration
28
+ - `utils/generateToken.js` or `utils/generateToken.ts`
29
+ - `utils/verifyToken.js` or `utils/verifyToken.ts`
38
30
 
39
- ### 1. Generate a Token
31
+ ## Quick Start
32
+
33
+ ### Generate a Token
40
34
 
41
35
  ```javascript
42
36
  const { generateToken } = require('./utils/generateToken');
@@ -48,10 +42,9 @@ const token = generateToken({
48
42
  });
49
43
 
50
44
  console.log(token);
51
- // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
52
45
  ```
53
46
 
54
- ### 2. Verify a Token
47
+ ### Verify a Token
55
48
 
56
49
  ```javascript
57
50
  const { verifyToken } = require('./utils/verifyToken');
@@ -59,13 +52,12 @@ const { verifyToken } = require('./utils/verifyToken');
59
52
  try {
60
53
  const decoded = verifyToken(token);
61
54
  console.log(decoded);
62
- // { userId: '12345', email: 'user@example.com', role: 'admin', iat: 1715772..., exp: 1715858... }
63
55
  } catch (error) {
64
56
  console.error('Token is invalid or expired');
65
57
  }
66
58
  ```
67
59
 
68
- ## Usage Examples
60
+ ## Usage Examples
69
61
 
70
62
  ### Express.js Authentication Middleware
71
63
 
@@ -76,30 +68,28 @@ const { generateToken } = require('./utils/generateToken');
76
68
 
77
69
  const app = express();
78
70
 
79
- // Middleware to protect routes
80
71
  const authMiddleware = (req, res, next) => {
81
- const token = req.headers.authorization?.split(' ')[1];
82
-
72
+ const authorization = req.headers.authorization;
73
+ const token = authorization ? authorization.split(' ')[1] : null;
74
+
83
75
  if (!token) {
84
76
  return res.status(401).json({ error: 'No token provided' });
85
77
  }
86
-
78
+
87
79
  try {
88
80
  req.user = verifyToken(token);
89
81
  next();
90
- } catch (error) {
91
- res.status(401).json({ error: 'Invalid token' });
82
+ } catch (err) {
83
+ return res.status(401).json({ error: 'Invalid token' });
92
84
  }
93
85
  };
94
86
 
95
- // Login endpoint
96
87
  app.post('/login', (req, res) => {
97
88
  const user = { id: 1, email: 'user@example.com' };
98
89
  const token = generateToken(user);
99
90
  res.json({ token });
100
91
  });
101
92
 
102
- // Protected endpoint
103
93
  app.get('/profile', authMiddleware, (req, res) => {
104
94
  res.json({ user: req.user });
105
95
  });
@@ -107,29 +97,21 @@ app.get('/profile', authMiddleware, (req, res) => {
107
97
  app.listen(3000, () => console.log('Server running on port 3000'));
108
98
  ```
109
99
 
110
- ### Async/Await Pattern
100
+ ### Simple Async/Await Example
111
101
 
112
102
  ```javascript
113
103
  const { generateToken, verifyToken } = require('./utils');
114
104
 
115
105
  async function authenticateUser(credentials) {
116
- try {
117
- // Generate token for user
118
- const token = generateToken({
119
- userId: credentials.id,
120
- email: credentials.email,
121
- timestamp: Date.now()
122
- });
123
-
124
- // Later, verify the token
125
- const payload = verifyToken(token);
126
- console.log('User authenticated:', payload.email);
127
-
128
- return payload;
129
- } catch (error) {
130
- console.error('Authentication failed:', error.message);
131
- throw error;
132
- }
106
+ const token = generateToken({
107
+ userId: credentials.id,
108
+ email: credentials.email,
109
+ timestamp: Date.now()
110
+ });
111
+
112
+ const payload = verifyToken(token);
113
+ console.log('Authenticated user:', payload.email);
114
+ return payload;
133
115
  }
134
116
  ```
135
117
 
@@ -138,19 +120,14 @@ async function authenticateUser(credentials) {
138
120
  ```javascript
139
121
  const { generateToken } = require('./utils/generateToken');
140
122
 
141
- // Create a token that expires in 1 hour
142
- const shortToken = generateToken(
143
- { userId: '123' }
144
- );
145
-
146
- // The expiry is controlled by JWT_EXPIRY in .env
147
- // Default: 24h
148
- // Options: 1h, 7d, 30d, etc.
123
+ const token = generateToken({ userId: '123' });
149
124
  ```
150
125
 
151
- ## Configuration
126
+ Token expiry is controlled by `JWT_EXPIRY` in `.env`.
127
+
128
+ ## Configuration
152
129
 
153
- Edit your `.env` file to customize JWT settings:
130
+ Update your `.env` file to customize JWT settings:
154
131
 
155
132
  ```env
156
133
  # JWT Moshiur Configuration
@@ -162,26 +139,22 @@ JWT_EXPIRY=24h
162
139
 
163
140
  | Variable | Default | Description |
164
141
  |----------|---------|-------------|
165
- | `JWT_SECRET` | Generated | Secret key for signing tokens (change this!) |
166
- | `JWT_EXPIRY` | `24h` | Token expiration time (`1h`, `7d`, `30d`, etc.) |
142
+ | `JWT_SECRET` | Generated | Secret used to sign tokens |
143
+ | `JWT_EXPIRY` | `24h` | Token expiry period |
167
144
 
168
- ** Important:** Always change `JWT_SECRET` to a strong, unique value in production!
145
+ > Use a strong, unique secret in production.
169
146
 
170
- ## API Reference
147
+ ## API Reference
171
148
 
172
149
  ### `generateToken(payload: object): string`
173
150
 
174
151
  Generates a signed JWT token.
175
152
 
176
- **Parameters:**
177
- - `payload` (object): Data to encode in the token
178
-
179
- **Returns:** JWT token string
180
-
181
153
  **Example:**
154
+
182
155
  ```javascript
183
- const token = generateToken({
184
- userId: '123',
156
+ const token = generateToken({
157
+ userId: '123',
185
158
  email: 'user@example.com',
186
159
  role: 'user'
187
160
  });
@@ -189,38 +162,30 @@ const token = generateToken({
189
162
 
190
163
  ### `verifyToken(token: string): object`
191
164
 
192
- Verifies and decodes a JWT token.
193
-
194
- **Parameters:**
195
- - `token` (string): JWT token to verify
196
-
197
- **Returns:** Decoded payload object
198
-
199
- **Throws:** Error if token is invalid or expired
165
+ Verifies a JWT token and returns the decoded payload.
200
166
 
201
167
  **Example:**
168
+
202
169
  ```javascript
203
170
  try {
204
171
  const payload = verifyToken(token);
205
172
  console.log('Valid token:', payload);
206
173
  } catch (error) {
207
- console.log('Invalid token:', error.message);
174
+ console.error('Invalid token:', error.message);
208
175
  }
209
176
  ```
210
177
 
211
- ## Manual Setup
178
+ ## Manual Setup
212
179
 
213
- If you need to re-run the setup process:
180
+ If you need to run setup again:
214
181
 
215
182
  ```bash
216
183
  npx jwtmoshiur
217
184
  ```
218
185
 
219
- This will regenerate the `.env` file and utility files if they don't exist.
220
-
221
- ## Project Structure
186
+ ## Project Structure
222
187
 
223
- After installation, your project will have:
188
+ After setup, your project will include:
224
189
 
225
190
  ```
226
191
  your-project/
@@ -233,31 +198,37 @@ your-project/
233
198
  └── package.json
234
199
  ```
235
200
 
236
- ## Security Best Practices
201
+ ## Security Guidelines
202
+
203
+ - Do not commit `.env` to source control.
204
+ - Use a strong JWT secret.
205
+ - Rotate secrets periodically.
206
+ - Use HTTPS in production.
207
+ - Choose an expiry period that fits your security requirements.
208
+
209
+ ## Troubleshooting
210
+
211
+ #### Setup did not run automatically
212
+
213
+ Run:
214
+
215
+ ```bash
216
+ npx jwtmoshiur
217
+ ```
237
218
 
238
- 1. **Never commit `.env` to version control**
239
- ```bash
240
- # Add to .gitignore
241
- .env
242
- .env.local
243
- ```
219
+ #### Token verification fails
244
220
 
245
- 2. **Use strong secrets**
246
- ```bash
247
- # Generate a strong secret (Linux/Mac)
248
- openssl rand -base64 32
249
-
250
- # Or use a random string generator
251
- node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
252
- ```
221
+ - Confirm `JWT_SECRET` is present in `.env`
222
+ - Confirm token has not expired
223
+ - Confirm the token was generated with the same secret
253
224
 
254
- 3. **Rotate secrets regularly** in production
225
+ #### `.env` file is missing
255
226
 
256
- 4. **Use HTTPS** only in production
227
+ Run the setup command manually and verify the file exists.
257
228
 
258
- 5. **Set appropriate expiry times** for your use case
229
+ ## License
259
230
 
260
- ## 🛠️ Troubleshooting
231
+ MIT
261
232
 
262
233
  ### Issue: Auto setup not working after npm install
263
234
  **Solution:** Manually run the setup command: