Skip to content

Commit 1f23af3

Browse files
authored
Merge branch 'CodeHarborHub:main' into main
2 parents d0949b2 + f5717ee commit 1f23af3

File tree

65 files changed

+4371
-323
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+4371
-323
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
---
2+
id: lesson-1
3+
title: "Authentication and Authorization in Next.js"
4+
sidebar_label: Authentication and Authorization
5+
sidebar_position: 1
6+
description: "Authentication and Authorization in Next.js"
7+
tags: [courses,intermediate-level,FramWorks,Introduction]
8+
---
9+
10+
11+
Implementing authentication and authorization in Next.js can be streamlined using libraries like NextAuth.js for handling various authentication strategies, JWT-based authentication for token management, and role-based access control to protect routes and API endpoints.
12+
13+
#### Implementing Authentication with NextAuth.js
14+
15+
NextAuth.js is a flexible authentication library for Next.js applications. It supports various authentication providers like Google, GitHub, and custom email/password.
16+
17+
1. **Install NextAuth.js**:
18+
```bash
19+
npm install next-auth
20+
```
21+
22+
2. **Configure NextAuth.js**:
23+
- Create a new API route for NextAuth in `src/pages/api/auth/[...nextauth].js`:
24+
```javascript
25+
// src/pages/api/auth/[...nextauth].js
26+
import NextAuth from 'next-auth';
27+
import Providers from 'next-auth/providers';
28+
29+
export default NextAuth({
30+
providers: [
31+
Providers.Google({
32+
clientId: process.env.GOOGLE_CLIENT_ID,
33+
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
34+
}),
35+
// Add other providers here
36+
],
37+
database: process.env.DATABASE_URL, // Optional: For storing user accounts in a database
38+
});
39+
```
40+
41+
3. **Add Environment Variables**:
42+
- Create a `.env.local` file in the root of your project and add the required environment variables:
43+
```env
44+
GOOGLE_CLIENT_ID=your-google-client-id
45+
GOOGLE_CLIENT_SECRET=your-google-client-secret
46+
DATABASE_URL=your-database-url
47+
```
48+
49+
4. **Add Authentication to Pages**:
50+
- Use the `useSession` hook to access the authentication session:
51+
```javascript
52+
// src/pages/index.js
53+
import { useSession, signIn, signOut } from 'next-auth/client';
54+
55+
export default function Home() {
56+
const [session, loading] = useSession();
57+
58+
return (
59+
<div>
60+
<h1>NextAuth.js Authentication</h1>
61+
{loading && <p>Loading...</p>}
62+
{!session && (
63+
<div>
64+
<p>You are not signed in.</p>
65+
<button onClick={() => signIn('google')}>Sign in with Google</button>
66+
</div>
67+
)}
68+
{session && (
69+
<div>
70+
<p>Signed in as {session.user.email}</p>
71+
<button onClick={() => signOut()}>Sign out</button>
72+
</div>
73+
)}
74+
</div>
75+
);
76+
}
77+
```
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
---
2+
id: lesson-2
3+
title: "JWT-Based Authentication"
4+
sidebar_label: JWT-Based Authentication
5+
sidebar_position: 2
6+
description: "JWT-Based Authentication"
7+
tags: [courses,intermediate-level,FramWorks,Introduction]
8+
---
9+
10+
11+
JWT (JSON Web Token) is a common method for securing APIs by encoding user information within a token.
12+
13+
1. **Install JWT Dependencies**:
14+
```bash
15+
npm install jsonwebtoken
16+
```
17+
18+
2. **Generate JWTs**:
19+
```javascript
20+
// src/utils/jwt.js
21+
import jwt from 'jsonwebtoken';
22+
23+
const secret = process.env.JWT_SECRET;
24+
25+
export function generateToken(user) {
26+
return jwt.sign({ id: user.id, email: user.email }, secret, { expiresIn: '1h' });
27+
}
28+
29+
export function verifyToken(token) {
30+
try {
31+
return jwt.verify(token, secret);
32+
} catch (err) {
33+
return null;
34+
}
35+
}
36+
```
37+
38+
3. **Protecting API Routes**:
39+
```javascript
40+
// src/pages/api/protected.js
41+
import { verifyToken } from '../../utils/jwt';
42+
43+
export default function handler(req, res) {
44+
const token = req.headers.authorization?.split(' ')[1];
45+
const user = verifyToken(token);
46+
47+
if (!user) {
48+
return res.status(401).json({ message: 'Unauthorized' });
49+
}
50+
51+
res.status(200).json({ message: 'This is a protected route', user });
52+
}
53+
```
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
id: lesson-3
3+
title: "Role-Based Access Control"
4+
sidebar_label: Protecting Routes and API Endpoints
5+
sidebar_position: 3
6+
description: "Role-Based Access Control"
7+
tags: [courses,intermediate-level,FramWorks,Introduction]
8+
---
9+
10+
11+
12+
1. **Assign Roles to Users**:
13+
- Modify your user model to include roles:
14+
```javascript
15+
// src/models/User.js
16+
import mongoose from 'mongoose';
17+
18+
const UserSchema = new mongoose.Schema({
19+
name: String,
20+
email: String,
21+
role: {
22+
type: String,
23+
enum: ['user', 'admin'],
24+
default: 'user',
25+
},
26+
});
27+
28+
export default mongoose.models.User || mongoose.model('User', UserSchema);
29+
```
30+
31+
2. **Create Middleware for Role-Based Access Control**:
32+
```javascript
33+
// src/utils/withRole.js
34+
import { verifyToken } from './jwt';
35+
36+
export function withRole(handler, role) {
37+
return async (req, res) => {
38+
const token = req.headers.authorization?.split(' ')[1];
39+
const user = verifyToken(token);
40+
41+
if (!user || user.role !== role) {
42+
return res.status(403).json({ message: 'Forbidden' });
43+
}
44+
45+
req.user = user;
46+
return handler(req, res);
47+
};
48+
}
49+
```
50+
51+
3. **Protect Routes with Role-Based Access Control**:
52+
```javascript
53+
// src/pages/api/admin.js
54+
import { withRole } from '../../utils/withRole';
55+
56+
const handler = (req, res) => {
57+
res.status(200).json({ message: 'Admin route', user: req.user });
58+
};
59+
60+
export default withRole(handler, 'admin');
61+
```
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"label": "Authentication and Authorization",
3+
"position": 2,
4+
"link": {
5+
"type": "generated-index",
6+
"description": "Learn Next.Js Authentication and Authorization."
7+
}
8+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
---
2+
id: lesson-4
3+
title: "Protecting Routes and API Endpoints"
4+
sidebar_label: Protecting Routes and API Endpoints
5+
sidebar_position: 4
6+
description: "Protecting Routes and API Endpoints"
7+
tags: [courses,intermediate-level,FramWorks,Introduction]
8+
---
9+
10+
11+
1. **Protecting Next.js Pages**:
12+
- Use the `getServerSideProps` function to protect pages:
13+
```javascript
14+
// src/pages/protected.js
15+
import { getSession } from 'next-auth/client';
16+
17+
export default function ProtectedPage({ session }) {
18+
if (!session) {
19+
return <p>Access Denied</p>;
20+
}
21+
22+
return <p>Welcome, {session.user.email}</p>;
23+
}
24+
25+
export async function getServerSideProps(context) {
26+
const session = await getSession(context);
27+
28+
if (!session) {
29+
return {
30+
redirect: {
31+
destination: '/api/auth/signin',
32+
permanent: false,
33+
},
34+
};
35+
}
36+
37+
return {
38+
props: { session },
39+
};
40+
}
41+
```
42+
43+
2. **Protecting API Endpoints with Middleware**:
44+
```javascript
45+
// src/utils/withAuth.js
46+
import { verifyToken } from './jwt';
47+
48+
export function withAuth(handler) {
49+
return async (req, res) => {
50+
const token = req.headers.authorization?.split(' ')[1];
51+
const user = verifyToken(token);
52+
53+
if (!user) {
54+
return res.status(401).json({ message: 'Unauthorized' });
55+
}
56+
57+
req.user = user;
58+
return handler(req, res);
59+
};
60+
}
61+
```
62+
63+
```javascript
64+
// src/pages/api/protected.js
65+
import { withAuth } from '../../utils/withAuth';
66+
67+
const handler = (req, res) => {
68+
res.status(200).json({ message: 'Protected route', user: req.user });
69+
};
70+
71+
export default withAuth(handler);
72+
```
73+
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
id: lesson-3
3+
title: "Using GraphQL with Next.js"
4+
sidebar_label: Data Fetching and Caching
5+
sidebar_position: 3
6+
description: "Using GraphQL with Next.js"
7+
tags: [courses,intermediate-level,FramWorks,Introduction]
8+
---
9+
10+
11+
You can use GraphQL with Next.js using Apollo Client or other GraphQL clients.
12+
13+
1. **Install Apollo Client**:
14+
```bash
15+
npm install @apollo/client graphql
16+
```
17+
18+
2. **Setup Apollo Client**:
19+
```javascript
20+
// src/lib/apolloClient.js
21+
import { ApolloClient, InMemoryCache } from '@apollo/client';
22+
23+
const client = new ApolloClient({
24+
uri: 'https://your-graphql-endpoint',
25+
cache: new InMemoryCache(),
26+
});
27+
28+
export default client;
29+
```
30+
31+
3. **Use Apollo Client in a Page**:
32+
```javascript
33+
// src/pages/index.js
34+
import { ApolloProvider, gql, useQuery } from '@apollo/client';
35+
import client from '../lib/apolloClient';
36+
37+
const GET_POSTS = gql`
38+
query GetPosts {
39+
posts {
40+
id
41+
title
42+
}
43+
}
44+
`;
45+
46+
function Posts() {
47+
const { loading, error, data } = useQuery(GET_POSTS);
48+
49+
if (loading) return <p>Loading...</p>;
50+
if (error) return <p>Error :(</p>;
51+
52+
return (
53+
<ul>
54+
{data.posts.map(post => (
55+
<li key={post.id}>{post.title}</li>
56+
))}
57+
</ul>
58+
);
59+
}
60+
61+
export default function Home() {
62+
return (
63+
<ApolloProvider client={client}>
64+
<h1>Posts</h1>
65+
<Posts />
66+
</ApolloProvider>
67+
);
68+
}
69+
```

0 commit comments

Comments
 (0)