Jastranet Solution Ltd

Jastranet Solution Ltd

Technology, Information and Internet

About us

Build and provide training and tutor on cutting-edge world technologies for web development.

Website
https://jastranet.onrender.com
Industry
Technology, Information and Internet
Company size
2-10 employees
Type
Self-Employed
Founded
2020

Updates

  • Which one do you commonly use at any giving task as a asynchronous programming? 1. Promise 2. Callback function 3. Async and await function and which one do you preferred most in handling errors. 1. try and catch 2. dot then and catch 3. error handling middleware.

  • Enhancing JWT Authentication in Node.js JSON Web Tokens (JWTs) are a popular way to authenticate and authorize users in web applications. They consist of three parts: a header, a payload, and a signature. The header contains information about the token, such as the algorithm used for signing. The payload contains the claims, which are statements about the user. The signature is a hash of the header, payload, and a secret key, which ensures the integrity of the token. To get started, you’ll need to install the necessary dependencies. Open your terminal and navigate to your Node.js project directory. Then run the following command: npm install express jsonwebtoken Now, let’s create an Express application that handles user authentication using JWTs. Create a new file, for example, app.js, and add the following code: const express = require('express'); const jwt = require('jsonwebtoken'); const app = express(); app.use(express.json()); const secretKey = 'your-secret-key'; // Endpoint for generating and returning a JWT token app.post('/login', (req, res) => { // In a real-world scenario, you would typically validate the user's credentials here const { username, password } = req.body; // Check if the username and password are correct if (username === 'john' && password === 'password') { // Generate a JWT token const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' }); // Return the token to the client res.json({ token }); } else { res.status(401).json({ message: 'Invalid username or password' }); } }); // Protected endpoint that requires a valid JWT token app.get('/protected', authenticateToken, (req, res) => { res.json({ message: 'You are authorized to access this protected resource.' }); }); // Middleware for authenticating JWT token function authenticateToken(req, res, next) { // Extract the token from the Authorization header const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) { return res.status(401).json({ message: 'No token provided' }); } // Verify and decode the token jwt.verify(token, secretKey, (err, decoded) => { if (err) { return res.status(403).json({ message: 'Invalid token' }); } // Add the decoded user information to the request object req.user = decoded; next(); }); } // Start the server app.listen(3000, () => { console.log('Server started on port 3000'); }); In this example, we have two endpoints: /login for generating a JWT token, and /protected as a protected resource that requires a valid token for access. When a user makes a POST request to /login with a JSON payload containing their username and password, we check if the provided credentials are valid. If they are, we generate a JWT token using jwt.sign(), passing in the username as the payload. The secretKey is used to sign the token, and we also specify an expiration time of 1 hour.

  • Implementing API key authentication with rate limiting in Node.js (Express) using MongoDB: Create a new Node.js project and install dependencies: npm init -y npm install express mongoose uuid Mongoose Model for Users: Create a models/user.js file: const mongoose = require('mongoose'); const uuidv4 = require('uuid/v4'); const userSchema = new mongoose.Schema({ name: String, apiKey: { type: String, default: uuidv4() }, // Generate a unique API key on creation usage: [{ date: Date, count: Number }], rateLimit: Number // Optional: Define a custom rate limit }); module.exports = mongoose.model('User', userSchema); Authentication Middleware: Create a middleware/auth.js file: const User = require('../models/user'); const authenticateKey = async (req, res, next) => { const apiKey = req.headers['x-api-key']; if (!apiKey) { return res.status(401).send('Unauthorized: API key is missing'); } const user = await User.findOne({ apiKey }); if (!user) { return res.status(401).send('Unauthorized: Invalid API key'); } // Rate limiting logic: const today = new Date().toISOString().split('T')[0]; const usageIndex = user.usage.findIndex((day) => day.date === today); if (usageIndex >= 0) { if (user.usage[usageIndex].count >= user.rateLimit || user.rateLimit === 0) { return res.status(429).send('Too many requests'); } user.usage[usageIndex].count++; } else { user.usage.push({ date: today, count: 1 }); } await user.save(); req.user = user; next(); }; module.exports = authenticateKey; Registering a User (Optional): // POST request handler for user registration // You might want to secure this with passwords or other methods const registerUser = async (req, res) => { try { const user = await new User(req.body).save(); res.status(201).send(user); } catch (error) { console.error(error); res.status(500).send('Error creating user'); } }; Applying Middleware and Protected API Routes: In your app.js file, apply the middleware and define a protected route: const express = require('express'); const mongoose = require('mongoose'); const authenticateKey = require('./middleware/auth'); const app = express(); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/MyDB', { useNewUrlParser: true, useUnifiedTopology: true }); app.use(express.json()); app.get('/protected-route', authenticateKey, (req, res) => { res.json({ message: 'Welcome, authorized user!' }); }); app.listen(3000, () => { console.log('Server listening on port 3000'); }); Consider security measures like securing API keys during transmission and storage. Adjust rate limiting logic as needed.

  • For a beginner, TypeScript can be overwhelming at times. However, with the right tips and techniques, you can harness the power of TypeScript to write safer, more reliable code. In this post, I will share 4 TypeScript Tips to help you improve your development workflow and improve your understanding of the language. 1. Enable Strict Mode: One of the best features of TypeScript is its strict type-checking system. By enabling strict mode, TypeScript performs more thorough type checking and provides better error messages. To enable strict mode, add the "strict": true option to your tsconfig.json file: Example { "compilerOptions": { "strict": true } } Enabling strict mode from the beginning of your project will help you catch potential errors early on and ensure better code quality. 2. Use Explicit Types: TypeScript is about types, so it’s important to be explicit when defining types. Avoid relying on type inference and be explicit about variable types, function parameters, and return values. This improves the readability of your code and makes it easier for other developers to understand your code. For example: Example function addNumbers(a: number, b: number): number { return a + b; } Take Advantage of Interfaces Interfaces in TypeScript allow you to define the shape of objects and specify the types of their properties. They are a powerful tool for creating reusable and maintainable code. Instead of using inline type annotations, consider defining interfaces for complex data structures. For example: Example interface User { name: string; age: number; email: string; } function sendEmail(user: User) { // ... } Using interfaces not only improves code clarity but also allows type-checking of object properties. 3. Utilize Union Types and Type Guards: Union types allow you to define a variable that can have multiple types. This is useful when dealing with situations where a variable may have different possible values. Type guards like typeof and instanceof, help you narrow down the type in a conditional block. Here's an example: By using union types and type protection, you can write more flexible and robust code that handles different scenarios. Example type Shape = 'circle' | 'square' | 'triangle'; function getArea(shape: Shape, size: number): number { if (shape === 'circle') { return Math.PI * size * size; } else if (shape === 'square') { return size * size; } else if (shape === 'triangle') { return (Math.sqrt(3) / 4) * size * size; } } const area = getArea('circle', 5); By using union types and type protection, you can write more flexible and robust code that handles different scenarios. 4. Destructure Objects and Arrays:

  • Protect Your APIs Like a Ninja: A Node.js Authentication Server for RESTful Services: Introduction This simple article will walk you through, step-by-step guide for setting up your Authentication server. You’ll get: Clear instructions: Easy-to-follow steps with explanations to guide you like a pro. Ready-to-use source code: Copy, paste, and customize to build your authentication server in no time. Here’s the list of essential APIs for a Node.js authentication server: User Registration API: Handles new user signups. Accepts user data (username, email, password). Securely stores user information (hashed and salted passwords). 2. User Login API: Verifies user credentials. Compares entered password with stored hash. Upon successful authentication, generates and returns a token (e.g., JWT). 3. User Verification API: Fetches and returns user profile information. Requires a valid authentication token. 5. Token Refresh API: Issues new access tokens upon expiration. Extends user sessions without requiring re-login. User Registration This API is designed to register users in our database. Access to our private APIs is limited to registered users only. Install Required Dependencies: npm install express mongoose bcryptjs 2. Create User Model: // models/user.js const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const userSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, }); userSchema.pre('save', async function (next) { if (this.isModified('password')) { this.password = await bcrypt.hash(this.password, 10); // Hash password with salt } next(); }); module.exports = mongoose.model('User', userSchema); 3. Create Registration Route: // routes/register.js const express = require('express'); const router = express.Router(); const User = require('../models/user'); router.post('/', async (req, res) => { try { const { username, email, password } = req.body; // Validate user input here (e.g., using a validation library) const existingUser = await User.findOne({ email }); if (existingUser) { return res.status(400).json({ message: 'Email already exists' }); } const user = new User({ username, email, password }); await user.save(); res.status(201).json({ message: 'User registered successfully' }); } catch (err) { console.error(err); res.status(500).json({ message: 'Registration failed' }); } }); module.exports = router;

Similar pages