Skip to content

Commit aae2765

Browse files
authored
Merge pull request #249 from codeharborhub/dev-1
solve issues
2 parents 99d279c + 86c158b commit aae2765

44 files changed

Lines changed: 1843 additions & 25 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"label": "Authentication",
3+
"position": 10,
4+
"link": {
5+
"type": "generated-index",
6+
"title": "Authentication: Securing Your Application",
7+
"description": "Learn how to implement secure authentication mechanisms in your applications. This track covers everything from basic login systems to advanced topics like OAuth, JWT, and multi-factor authentication."
8+
}
9+
}
Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,98 @@
1-
<ComingSoon />
1+
---
2+
title: "Authentication Best Practices"
3+
sidebar_label: "7. Best Practices"
4+
sidebar_position: 7
5+
description: "Essential security checklist for building professional and secure authentication systems."
6+
tags: ["authentication", "security", "best practices", "full-stack development"]
7+
keywords: ["authentication best practices", "password security", "HTTPS", "JWT security", "rate limiting", "multi-factor authentication", "RBAC", "security checklist"]
8+
---
9+
10+
In the world of security, we assume that attackers are smart and persistent. Following these rules will protect your application from 99% of common attacks.
11+
12+
## 1. Password Security
13+
14+
### Use Salted Hashing
15+
16+
As we learned, never store passwords as plain text. Use **Bcrypt** with at least **10-12 salt rounds**.
17+
18+
### Enforce Strong Password Policies
19+
20+
Don't let users use `password123`. Require a mix of:
21+
* Minimum 8-12 characters.
22+
* At least one uppercase letter.
23+
* At least one number and one special character.
24+
25+
## 2. Transport & Storage
26+
27+
### HTTPS is Non-Negotiable
28+
Without SSL/TLS (HTTPS), passwords and JWTs are sent across the internet in plain text. Any "man-in-the-middle" can steal them. **Always use HTTPS in production.**
29+
30+
### Use HttpOnly and Secure Cookies
31+
If you store tokens in cookies, set these flags:
32+
* `HttpOnly`: Prevents JavaScript from reading the cookie (stops XSS attacks).
33+
* `Secure`: Ensures the cookie is only sent over HTTPS.
34+
* `SameSite=Strict`: Prevents CSRF (Cross-Site Request Forgery) attacks.
35+
36+
## 3. Handling JWTs (Tokens)
37+
38+
### Keep Secrets Secret
39+
Never hardcode your `JWT_SECRET`. Use environment variables (`.env`) and make sure `.env` is in your `.gitignore`.
40+
41+
### Use Short Expiration Times
42+
Tokens should not last forever. A good standard is **15 minutes to 1 hour** for access tokens.
43+
44+
## 4. Protection Against Attacks
45+
46+
### Rate Limiting
47+
Prevent "Brute Force" attacks (where a bot tries thousands of passwords) by limiting how many requests an IP can make to your `/login` route.
48+
49+
```javascript title="rateLimiter.js"
50+
const rateLimit = require('express-rate-limit');
51+
52+
const loginLimiter = rateLimit({
53+
windowMs: 15 * 60 * 1000, // 15 minutes
54+
max: 5, // Limit each IP to 5 login requests per window
55+
message: "Too many login attempts, please try again after 15 minutes"
56+
});
57+
58+
app.use('/api/auth/login', loginLimiter);
59+
60+
```
61+
62+
### Generic Error Messages
63+
64+
Never tell a hacker *which* part of the login was wrong.
65+
66+
* **Bad:** "User not found" or "Incorrect password."
67+
* **Good:** "Invalid email or password."
68+
69+
## 5. Multi-Factor Authentication (MFA)
70+
71+
For high-security apps, a password isn't enough. Implement MFA using:
72+
73+
* **TOTP:** Apps like Google Authenticator.
74+
* **Email/SMS:** Sending a one-time code (OTP).
75+
76+
## 6. The "Master" Checklist
77+
78+
| Category | Requirement | Check |
79+
| --- | --- | --- |
80+
| **Passwords** | Hashed with Bcrypt + Salt ||
81+
| **Transport** | All traffic over HTTPS ||
82+
| **Tokens** | Short-lived + Securely stored ||
83+
| **Database** | Roles (RBAC) implemented ||
84+
| **Monitoring** | Logs for failed login attempts ||
85+
86+
## Practice: The Vulnerability Hunt
87+
88+
Go through your current project and check:
89+
90+
1. Is your `JWT_SECRET` in a `.env` file?
91+
2. Do your login routes have a rate limiter?
92+
3. Are you using generic error messages?
93+
94+
If you answered "No" to any of these, now is the time to fix it!
95+
96+
:::info Security Audits
97+
Use tools like `npm audit` frequently. It will scan your project for libraries with known security holes and tell you how to patch them.
98+
:::
Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,65 @@
1-
<ComingSoon />
1+
---
2+
title: "Introduction to Authentication"
3+
sidebar_label: "1. Introduction"
4+
sidebar_position: 1
5+
description: "Learn the fundamental concepts of Authentication vs. Authorization and how security works in web apps."
6+
tags: ["authentication", "authorization", "security", "full-stack development"]
7+
keywords: ["authentication", "authorization", "security", "JWT", "sessions", "hashing", "bcrypt"]
8+
---
9+
10+
In full-stack development, security isn't just an "add-on"—it's the foundation. Before we write any code, we need to understand the two most important concepts in security.
11+
12+
## 1. Authentication vs. Authorization
13+
14+
These terms sound similar, but they do very different things. Think of a **Hotel**:
15+
16+
* **Authentication (AuthN):** This is the **Check-in** process. You show your ID to prove you are who you say you are. The hotel gives you a Key Card.
17+
* *Question:* "Who are you?"
18+
* **Authorization (AuthZ):** This is the **Key Card** itself. Your card lets you into your room (Room 302), but it won't let you into the Manager's office or the Kitchen.
19+
* *Question:* "What are you allowed to do?"
20+
21+
## 2. How it works on the Web
22+
23+
The web is "stateless," meaning the server forgets you the moment a request is finished. To stay logged in, we use a cycle:
24+
25+
1. **Identify:** The user sends their `email` and `password`.
26+
2. **Verify:** The server checks the database (MongoDB/Postgres) to see if the password matches.
27+
3. **Token/Session:** The server sends back a "Proof of Identity" (like a JWT or a Session ID).
28+
4. **Persistence:** The browser stores this proof (usually in a Cookie or LocalStorage) and sends it with every future request.
29+
30+
## 3. Common Auth Methods
31+
32+
At the Hub, we focus on the two industry standards:
33+
34+
### JSON Web Tokens (JWT)
35+
The most popular method for modern MERN apps. The server gives you a "Digital Ticket" (the token). You keep the ticket. Every time you want data, you show the ticket. The server doesn't need to check the database every time; it just validates the ticket.
36+
* **Best for:** Mobile apps, APIs, and Scalable apps.
37+
38+
### Session-Based (Cookies)
39+
The server creates a "file" for you in its memory (or Redis) and gives you an ID number. Your browser saves that ID in a cookie.
40+
* **Best for:** Traditional websites and high-security banking apps.
41+
42+
## 4. The Golden Rules of Security
43+
44+
As you start building auth systems, follow these "Master" principles:
45+
46+
1. **Never store plain-text passwords:** If a hacker steals your database, they shouldn't see "password123." We use **Hashing** (like Bcrypt) to turn passwords into unreadable gibberish.
47+
2. **Always use HTTPS:** Without encryption, anyone on the same Wi-Fi can see the passwords being sent to your server.
48+
3. **Don't reinvent the wheel:** Security is hard. Use trusted libraries like `Passport.js`, `Bcrypt`, or `JsonWebToken`.
49+
50+
## 5. Key Vocabulary
51+
52+
* **Credentials:** Your username and password.
53+
* **Hashing:** A one-way mathematical function that hides passwords.
54+
* **Salt:** Random data added to a password before hashing to make it even harder to crack.
55+
* **Middleware:** The code that stands between a user and a protected route to check if they are logged in.
56+
57+
## Practice: The Security Audit
58+
59+
Look at the apps on your phone (Instagram, WhatsApp, Bank).
60+
* How do they **Authenticate** you? (Password? FaceID? OTP?)
61+
* What are you **Authorized** to see? (Can you see your friend's private messages? Why not?)
62+
63+
:::info
64+
Authentication is where most beginners make mistakes. In the next few lessons, we will build a "Safe" login system step-by-step. **Take your time here—it’s the most important skill in a backend developer's resume.**
65+
:::
Lines changed: 104 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,104 @@
1-
<ComingSoon />
1+
---
2+
title: "JWT (JSON Web Tokens) Explained"
3+
sidebar_label: "3. JWT Tokens"
4+
sidebar_position: 3
5+
description: "Learn how to use JSON Web Tokens for stateless authentication in your MERN stack applications."
6+
tags: ["authentication", "JWT", "json web tokens", "security", "full-stack development"]
7+
keywords: ["JWT", "json web tokens", "authentication", "Node.js", "Express", "MongoDB", "PostgreSQL", "jsonwebtoken", "token-based authentication"]
8+
---
9+
10+
A **JWT** is a compact, URL-safe way of representing claims to be transferred between two parties. In simple terms: it is a digital ID card that proves who you are.
11+
12+
## 1. Why use JWT?
13+
14+
In modern web apps (like the ones we build at the Hub), we want our backend to be **Stateless**.
15+
* **Stateful:** The server must remember every logged-in user in its RAM. (Heavy and hard to scale).
16+
* **Stateless (JWT):** The server doesn't remember you. You carry your own "Identity" in your token. The server just verifies the signature on the token.
17+
18+
19+
## 2. Anatomy of a JWT
20+
21+
A JWT looks like a long string of gibberish separated by two dots: `xxxxx.yyyyy.zzzzz`. It has three parts:
22+
23+
1. **Header:** Tells the server what algorithm is used (e.g., HS256).
24+
2. **Payload:** Contains the user data (claims) like `userId` or `username`. **Warning:** Never put passwords here! This part is encoded, not encrypted (anyone can read it).
25+
3. **Signature:** This is the secret sauce. It is a combination of the Header, Payload, and a **Secret Key** known only to your server.
26+
27+
> If a user tries to change the `userId` in the Payload, the **Signature** will no longer match, and the server will reject the token!
28+
29+
## 3. Using JWT in Node.js
30+
31+
We use the `jsonwebtoken` library to handle tokens.
32+
33+
### Installation
34+
35+
```bash
36+
npm install jsonwebtoken
37+
```
38+
39+
### Generating a Token (On Login)
40+
41+
When a user successfully logs in, you "Sign" a token and send it to them.
42+
43+
```javascript title="generateToken.js"
44+
const jwt = require('jsonwebtoken');
45+
46+
const token = jwt.sign(
47+
{ userId: user._id, role: 'student' }, // Payload
48+
process.env.JWT_SECRET, // Your Secret Key
49+
{ expiresIn: '1h' } // Token expires in 1 hour
50+
);
51+
52+
res.json({ token });
53+
54+
```
55+
56+
### Verifying a Token (Middleware)
57+
58+
When the user wants to access a "Protected" route, they send the token in the **Header**. Your server verifies it:
59+
60+
```javascript title="verifyToken.js"
61+
const verifyToken = (req, res, next) => {
62+
const token = req.header('Authorization');
63+
64+
if (!token) return res.status(401).send("Access Denied!");
65+
66+
try {
67+
const verified = jwt.verify(token, process.env.JWT_SECRET);
68+
req.user = verified; // Add user info to the request object
69+
next(); // Move to the actual route
70+
} catch (err) {
71+
res.status(400).send("Invalid Token!");
72+
}
73+
};
74+
75+
```
76+
77+
## 4. Where to store the Token?
78+
79+
As a developer, you have two main choices for where the browser should save the token:
80+
81+
| Location | Security | Complexity |
82+
| --- | --- | --- |
83+
| **LocalStorage** | Vulnerable to XSS (Scripts can steal it). | Very Easy to use. |
84+
| **HttpOnly Cookie** | Immune to XSS. (Best Practice). | Requires more setup. |
85+
86+
At **CodeHarborHub**, we recommend starting with LocalStorage for learning, but moving to **HttpOnly Cookies** for professional projects.
87+
88+
## 5. The "Secret Key" Rule
89+
90+
Your `JWT_SECRET` is the most important piece of data in your backend.
91+
92+
* If someone gets your secret, they can create tokens for **any user** and log in as anyone (even the Admin!).
93+
* **Always** store your secret in a `.env` file and **never** push it to GitHub.
94+
95+
## Practice: The Token Decoder
96+
97+
1. Go to [JWT.io](https://jwt.io/).
98+
2. Paste a token you generated in your code.
99+
3. Look at the "Payload" on the right. Can you see your `userId`?
100+
4. Try changing a single letter in the token string. Watch how the "Signature Invalid" warning appears!
101+
102+
:::info Token Expiration
103+
Always set an expiration time (like `1h` or `7d`). If a token is ever stolen, it won't be useful forever. For "Master" level security, look into **Refresh Tokens** later!
104+
:::
Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,89 @@
1-
<ComingSoon />
1+
---
2+
title: "OAuth & Social Login"
3+
sidebar_label: "4. OAuth (Social Login)"
4+
sidebar_position: 4
5+
description: "Understand how OAuth works and how to integrate Login with Google using Passport.js."
6+
tags: ["authentication", "oauth", "social login", "passport.js", "google login", "full-stack development"]
7+
keywords: ["oauth", "social login", "passport.js", "google login", "authentication", "Node.js", "Express", "MongoDB", "PostgreSQL"]
8+
---
9+
10+
**OAuth 2.0** is an open-standard authorization protocol that allows a website to access a user's information from another service (like Google or Facebook) without actually seeing the user's password.
11+
12+
## 1. How the OAuth Flow Works
13+
14+
Think of OAuth as a **Valet Key** for a car. You give the valet a special key that lets them park the car, but it won't let them open the trunk or glove box.
15+
16+
1. **The Request:** The user clicks "Login with Google."
17+
2. **The Permission:** Google asks the user, "Do you allow CodeHarborHub to see your email and profile?"
18+
3. **The Code:** Google sends a temporary "Authorization Code" back to your server.
19+
4. **The Exchange:** Your server sends that code + your **Secret Key** to Google to prove it's really you.
20+
5. **The Token:** Google gives your server an `access_token` and the user's profile data.
21+
6. **The Session:** Your server saves the user to the database and logs them in.
22+
23+
## 2. Key Terms You Need to Know
24+
25+
* **Resource Owner:** The User (You).
26+
* **Client:** Your Application (CodeHarborHub).
27+
* **Authorization Server:** The service providing the login (Google/GitHub).
28+
* **Client ID:** A public identifier for your app (given by Google).
29+
* **Client Secret:** A private password for your server (KEEP THIS SECRET!).
30+
* **Callback URL (Redirect URI):** The specific link where Google sends the user after they log in.
31+
32+
## 3. Implementing OAuth with Passport.js
33+
34+
In the Node.js ecosystem, **Passport.js** is the "Master" middleware for authentication. It uses "Strategies" for different providers.
35+
36+
### Installation
37+
38+
```bash
39+
npm install passport passport-google-oauth20 express-session
40+
```
41+
42+
### Basic Configuration
43+
44+
```javascript title="passportConfig.js"
45+
const passport = require('passport');
46+
const GoogleStrategy = require('passport-google-oauth20').Strategy;
47+
48+
passport.use(new GoogleStrategy({
49+
clientID: process.env.GOOGLE_CLIENT_ID,
50+
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
51+
callbackURL: "/auth/google/callback"
52+
},
53+
async (accessToken, refreshToken, profile, done) => {
54+
// 1. Check if user exists in our DB
55+
// 2. If not, create a new user using profile.id and profile.emails[0].value
56+
// 3. Return the user
57+
return done(null, profile);
58+
}
59+
));
60+
61+
```
62+
63+
## 4. The Developer Console Step
64+
65+
You cannot code OAuth without first registering your app with the provider.
66+
67+
1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
68+
2. Create a Project and go to **APIs & Services > Credentials**.
69+
3. Create an **OAuth 2.0 Client ID**.
70+
4. Set the **Authorized Redirect URI** to `http://localhost:5000/auth/google/callback`.
71+
5. Copy your `CLIENT_ID` and `CLIENT_SECRET` to your `.env` file.
72+
73+
## 5. Pros and Cons of OAuth
74+
75+
| Pros | Cons |
76+
| --- | --- |
77+
| **User Experience:** One-click login is faster. | **Dependence:** If Google goes down, users can't log in. |
78+
| **High Security:** No passwords stored on your server. | **Privacy:** Some users don't like sharing data between sites. |
79+
| **Verified Emails:** You know the user's email is real. | **Complexity:** Setting up multiple providers can be tedious. |
80+
81+
## Practice: The Social Audit
82+
83+
1. Go to your Google Account settings under **"Security"**.
84+
2. Find **"Your connections to third-party apps & services"**.
85+
3. See which websites you have given "Valet Keys" to. Notice how you can revoke access at any time!
86+
87+
:::info
88+
When building a real project, always offer a **Hybrid** approach: Let users sign up with an Email/Password (using Bcrypt) OR use Social Login (OAuth). This gives your users the most flexibility!
89+
:::

0 commit comments

Comments
 (0)