Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Frame work change #1

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions coursera/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
MONGODB_URI='mongodb+srv://admin-akash:220104008@cluster0.kcycili.mongodb.net/'
SECRET='jdfkj'
3 changes: 3 additions & 0 deletions coursera/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
35 changes: 35 additions & 0 deletions coursera/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
38 changes: 38 additions & 0 deletions coursera/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.

[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.

The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
62 changes: 62 additions & 0 deletions coursera/components/InitUser.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { BASE_URL } from "@/config";
import axios from "axios";
import { GetServerSidePropsContext } from "next";
import cookie from 'cookie';
import { useSetRecoilState } from "recoil";
import { userState } from "@/store/atoms/user";
import { useEffect } from "react";

const InitUser: React.FC<{ username: string }> = ({ username }) => {
const setUser = useSetRecoilState(userState);

useEffect(() => {
if (username) {
setUser({
isLoading: false,
userEmail: username
});
}
})

return <></>
}

export async function getServerSideProps(context: GetServerSidePropsContext) {
try {
const cookies = context.req.headers.cookie;
const parsedCookie = cookie.parse(cookies || '');
const token = parsedCookie.jwtToken;

const response = await axios.get(`${BASE_URL}/api/admin/me`, {
headers: {
"Authorization": "Bearer " + token
}
})

if (!response.data.isAuth) {
return {
redirect: {
destination: '/signup' || '/signin', // Redirect to an unauthorized page
permanent: false,
},
};
}

return {
props: {
username: response.data.username
}
}

} catch (error) {
return {
redirect: {
destination: '/signin' || 'signup', // Redirect to login page on error or unauthorized access
permanent: false,
},
};

}
}

export default InitUser;
135 changes: 135 additions & 0 deletions coursera/components/Nav.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { userState } from '@/store/atoms/user';
import { isUserLoading } from '@/store/selector/isUserLoading';
import { userEmailState } from '@/store/selector/userEmail';
import { Button, Typography } from '@mui/material';
import { useRouter } from 'next/router';
import React, { useEffect } from 'react'
import { useRecoilValue, useSetRecoilState } from 'recoil';
import Cookies from 'js-cookie';
import { GetServerSidePropsContext } from 'next';
import cookie from 'cookie';
import axios from 'axios';

export const Nav: React.FC = () => {
const navigate = useRouter();
const userLoading = useRecoilValue(isUserLoading);
const userEmail = useRecoilValue(userEmailState);
const setUser = useSetRecoilState(userState);


if (userEmail) {
return <div className='sticky top-0 bg-white opacity-90 py-2' style={{
display: "flex",
justifyContent: "space-between",
padding: 4,
zIndex: 1
}}>
<div style={{marginLeft: 10, cursor: "pointer"}} onClick={() => {
navigate.push("/")
}}>
<Typography variant={"h6"}>Coursera</Typography>
</div>

<div style={{display: "flex"}}>
<div style={{marginRight: 10, display: "flex"}}>
<div style={{marginRight: 10}}>
<Button
onClick={() => {
navigate.push("/addcourse")
}}
>Add course</Button>
</div>

<div style={{marginRight: 10}}>
<Button
onClick={() => {
navigate.push("/courses")
}}
>Courses</Button>
</div>

<Button
className='bg-blue-500'
variant={"contained"}
onClick={() => {
// localStorage.setItem("token", null);
Cookies.remove('token');
setUser({
isLoading: false,
userEmail: ''
})
}}
>Logout</Button>
</div>
</div>
</div>
} else {
return <div style={{
display: "flex",
justifyContent: "space-between",
padding: 4,
zIndex: 1
}}>
<div style={{marginLeft: 10, cursor: "pointer"}} onClick={() => {
navigate.push("/")
}}>
<Typography variant={"h6"}>Coursera</Typography>
</div>

<div style={{display: "flex"}}>
<div style={{marginRight: 10}}>
<Button
className='bg-blue-500'
variant={"contained"}
onClick={() => {
navigate.push("/signup")
}}
>Signup</Button>
</div>
<div>
<Button
className='bg-blue-500'
variant={"contained"}
onClick={() => {
navigate.push("/signin")
}}
>Signin</Button>
</div>
</div>
</div>
}
}

export async function getServerSideProps(context: GetServerSidePropsContext) {
const cookies = context.req.headers.cookie;
const parsedCookie = cookie.parse(cookies || '');
const token = parsedCookie.jwtToken;

try {
const response = await axios.get('/api/user', {
headers: {
Authorization: `Bearer ${token}`,
},
});

if (!response.data.isAuthorized) {
return {
redirect: {
destination: '/unauthorized', // Redirect to an unauthorized page
permanent: false,
},
};
}

return {
props: {}, // User is authorized, continue rendering the protected page
};
} catch (error) {
return {
redirect: {
destination: '/login', // Redirect to login page on error or unauthorized access
permanent: false,
},
};
}
}
1 change: 1 addition & 0 deletions coursera/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const BASE_URL = 'http://localhost:3000';
71 changes: 71 additions & 0 deletions coursera/lib/db/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import mongoose from 'mongoose';
// Define mongoose schemas
const userSchema = new mongoose.Schema({
username: { type: String },
password: String,
purchasedCourses: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Course' }]
});

const adminSchema = new mongoose.Schema({
username: String,
password: String
});

export type adminType = {
username: string,
password: string,
_id?: string
}

const courseSchema = new mongoose.Schema({
title: String,
description: String,
price: Number,
imageLink: String,
published: Boolean
});

export type CourseType = {
title: string,
description: string,
price: number,
imageLink: string,
published: boolean,
_id?: string
}

const getModel = (modelName: any, schema: any) => {
try {
return mongoose.model(modelName);
} catch (error) {
// Model does not exist, define and return it
return mongoose.model(modelName, schema);
}
};
const User = getModel('User', userSchema);
const Admin = getModel('Admin', adminSchema);
const Course = getModel('Course', courseSchema);

const { MONGODB_URI } = process.env;


// Ensure that the MongoDB connection is established
async function dbConnect() {

if (!MONGODB_URI || MONGODB_URI.length == 0) {
throw new Error('Please define the MONGODB_URI environment variable');
}

if (mongoose.connection.readyState >= 1) {
return;
}

return mongoose.connect(MONGODB_URI, { dbName: 'cr' });
}

export {
User,
Admin,
Course,
dbConnect,
}
6 changes: 6 additions & 0 deletions coursera/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}

module.exports = nextConfig
Loading