├── RestAPI
├── .gitignore
├── server.js
├── package.json
└── routers
│ └── users.js
├── movie-watchlist
├── src
│ ├── api
│ │ └── index.js
│ ├── App.css
│ ├── main.jsx
│ ├── index.css
│ ├── App.jsx
│ ├── pages
│ │ ├── List.jsx
│ │ └── Home.jsx
│ └── components
│ │ ├── Search
│ │ └── Search.jsx
│ │ ├── Header
│ │ └── Header.jsx
│ │ ├── Watched
│ │ ├── WatchedCard.jsx
│ │ └── GetMovieList.jsx
│ │ ├── Watchlist
│ │ └── WatchlistCard.jsx
│ │ └── Card
│ │ └── MovieCard.jsx
├── backend
│ ├── .env
│ ├── package.json
│ ├── models
│ │ └── Watchlist.js
│ ├── server.js
│ └── routes
│ │ └── watched.js
├── public
│ ├── assets
│ │ ├── favicon.jpg
│ │ ├── loading.gif
│ │ └── react.svg
│ └── vite.svg
├── postcss.config.cjs
├── vite.config.js
├── tailwind.config.cjs
├── .gitignore
├── index.html
└── package.json
├── realmate
├── .gitignore
├── .env
├── package.json
├── server.js
├── models
│ └── User.js
├── README.md
└── routes
│ └── user.js
├── task-manager
├── .gitignore
├── .env
├── routes
│ ├── tasks.js
│ ├── users.js
│ └── todos.js
├── models
│ ├── Task.js
│ ├── Todo.js
│ └── User.js
├── package.json
├── server.js
└── passport.js
├── UsersAPI with AUTH
├── .gitignore
├── .env
├── models
│ └── User.js
├── package.json
├── server.js
├── README.md
└── routes
│ └── users.js
├── Connect Local MongoDB
├── .gitignore
├── img
│ ├── copyurl.png
│ └── getData.png
├── package.json
├── server.js
└── README.md
├── blog-post-api-mongodb
├── .gitignore
├── .env
├── models
│ ├── Post.js
│ └── User.js
├── package.json
├── server.js
└── routes
│ ├── posts.js
│ └── users.js
├── blog-post-api-mongodb - Copy
├── .gitignore
├── .idea
│ ├── .gitignore
│ ├── vcs.xml
│ ├── modules.xml
│ └── blog-post-api-mongodb.iml
├── .env
├── routes
│ ├── category.js
│ ├── products.js
│ └── users.js
├── models
│ ├── Category.js
│ ├── User.js
│ └── Product.js
├── package.json
└── server.js
├── recipe ap with auth
├── backend
│ ├── .env
│ ├── .gitignore
│ ├── package.json
│ ├── models
│ │ ├── User.js
│ │ └── Recipes.js
│ ├── server.js
│ └── routes
│ │ ├── recipes.js
│ │ └── users.js
└── frontend
│ ├── src
│ ├── App.css
│ ├── hooks
│ │ └── useGetUserId.jsx
│ ├── pages
│ │ ├── NotFound.jsx
│ │ ├── SavedRecipes.jsx
│ │ ├── Auth.jsx
│ │ ├── Home.jsx
│ │ └── CreateRecipe.jsx
│ ├── main.jsx
│ ├── index.css
│ ├── components
│ │ ├── Cards.jsx
│ │ ├── Login.jsx
│ │ ├── Register.jsx
│ │ └── Header.jsx
│ ├── App.jsx
│ └── assets
│ │ └── react.svg
│ ├── postcss.config.cjs
│ ├── vite.config.js
│ ├── tailwind.config.cjs
│ ├── .gitignore
│ ├── index.html
│ ├── package.json
│ └── public
│ └── vite.svg
├── recipe-sharing-platform
├── backend
│ ├── .gitignore
│ ├── .env
│ ├── routes
│ │ ├── dashboard.js
│ │ ├── alluser.js
│ │ ├── logout.js
│ │ ├── user.js
│ │ ├── users.js
│ │ ├── getuser.js
│ │ ├── login.js
│ │ └── recipes.js
│ ├── package.json
│ ├── middleware
│ │ └── auth.js
│ ├── models
│ │ ├── user.js
│ │ └── recipe.js
│ └── server.js
└── frontend
│ ├── src
│ ├── index.css
│ ├── App.css
│ ├── components
│ │ ├── pages
│ │ │ ├── List.jsx
│ │ │ ├── Details.jsx
│ │ │ ├── Signup.jsx
│ │ │ ├── Login.jsx
│ │ │ ├── Dashboard.jsx
│ │ │ └── Home.jsx
│ │ ├── API
│ │ │ └── API.js
│ │ ├── UserDetails.jsx
│ │ ├── Cards
│ │ │ ├── ReciepeCard.jsx
│ │ │ └── Gallary.jsx
│ │ ├── Search
│ │ │ └── SearchInput.jsx
│ │ ├── Form
│ │ │ ├── SignupForm.jsx
│ │ │ └── LoginForm.jsx
│ │ └── Header
│ │ │ └── Header.jsx
│ ├── main.jsx
│ ├── image.json
│ ├── App.jsx
│ └── assets
│ │ └── react.svg
│ ├── postcss.config.cjs
│ ├── vite.config.js
│ ├── tailwind.config.cjs
│ ├── .gitignore
│ ├── index.html
│ ├── package.json
│ └── public
│ └── vite.svg
├── mongodb
├── img
│ ├── c1.png
│ ├── c2.png
│ ├── c3.png
│ ├── c4.png
│ ├── c5.png
│ ├── push.png
│ ├── findrow.png
│ ├── rename.png
│ ├── update.png
│ ├── upsert.png
│ ├── increament.png
│ └── insertManyRows.png
└── README.md
├── .gitignore
├── LICENSE
├── SECURITY.md
├── README.md
├── .github
└── workflows
│ └── codeql.yml
└── CODE_OF_CONDUCT.md
/RestAPI/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/movie-watchlist/src/api/index.js:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/realmate/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/task-manager/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/UsersAPI with AUTH/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/Connect Local MongoDB/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/blog-post-api-mongodb/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/recipe ap with auth/backend/.env:
--------------------------------------------------------------------------------
1 | MONGO_URI=Your db url
--------------------------------------------------------------------------------
/recipe ap with auth/backend/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/realmate/.env:
--------------------------------------------------------------------------------
1 | MONGO_URI="mongodb://localhost:27017/realmate"
--------------------------------------------------------------------------------
/UsersAPI with AUTH/.env:
--------------------------------------------------------------------------------
1 | PORT=5000
2 | MONGO_URI=mongodb://localhost:27017/users-api
--------------------------------------------------------------------------------
/blog-post-api-mongodb/.env:
--------------------------------------------------------------------------------
1 | MONGO_URI = "mongodb://localhost:27017/blog-posts"
2 | PORT = 5000
--------------------------------------------------------------------------------
/mongodb/img/c1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/c1.png
--------------------------------------------------------------------------------
/mongodb/img/c2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/c2.png
--------------------------------------------------------------------------------
/mongodb/img/c3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/c3.png
--------------------------------------------------------------------------------
/mongodb/img/c4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/c4.png
--------------------------------------------------------------------------------
/mongodb/img/c5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/c5.png
--------------------------------------------------------------------------------
/mongodb/img/push.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/push.png
--------------------------------------------------------------------------------
/movie-watchlist/backend/.env:
--------------------------------------------------------------------------------
1 | PORT = 5000
2 | MONGO_URI = 'mongodb://localhost:27017/movie-watchlist'
--------------------------------------------------------------------------------
/mongodb/img/findrow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/findrow.png
--------------------------------------------------------------------------------
/mongodb/img/rename.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/rename.png
--------------------------------------------------------------------------------
/mongodb/img/update.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/update.png
--------------------------------------------------------------------------------
/mongodb/img/upsert.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/upsert.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ai
2 | AIimgGen
3 | Mern-Course
4 | project1
5 | RealTimeChat
6 | tutMern
7 | Data Fetching using AXIOS
--------------------------------------------------------------------------------
/mongodb/img/increament.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/increament.png
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/index.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
--------------------------------------------------------------------------------
/movie-watchlist/src/App.css:
--------------------------------------------------------------------------------
1 | #root {
2 | max-width: 1280px;
3 | margin: 0 auto;
4 | text-align: center;
5 | }
6 |
--------------------------------------------------------------------------------
/mongodb/img/insertManyRows.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/mongodb/img/insertManyRows.png
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/App.css:
--------------------------------------------------------------------------------
1 | #root {
2 | max-width: 1280px;
3 | margin: 0 auto;
4 | text-align: center;
5 | }
--------------------------------------------------------------------------------
/Connect Local MongoDB/img/copyurl.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/Connect Local MongoDB/img/copyurl.png
--------------------------------------------------------------------------------
/Connect Local MongoDB/img/getData.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/Connect Local MongoDB/img/getData.png
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/App.css:
--------------------------------------------------------------------------------
1 | #root {
2 | max-width: 1280px;
3 | margin: 0 auto;
4 | text-align: center;
5 | }
6 |
7 |
--------------------------------------------------------------------------------
/movie-watchlist/public/assets/favicon.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/movie-watchlist/public/assets/favicon.jpg
--------------------------------------------------------------------------------
/movie-watchlist/public/assets/loading.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devvsakib/PreBackendCode/HEAD/movie-watchlist/public/assets/loading.gif
--------------------------------------------------------------------------------
/movie-watchlist/postcss.config.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | autoprefixer: {},
5 | }
6 | }
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/postcss.config.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | autoprefixer: {},
5 | }
6 | }
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/postcss.config.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | autoprefixer: {},
5 | },
6 | }
7 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/.env:
--------------------------------------------------------------------------------
1 | MONGO_URI = "mongodb+srv://devvsakib:A4ihcktRP3Tjh8S@cluster0.lsn2n3w.mongodb.net/fantasistore?retryWrites=true&w=majority"
2 | PORT = 5000
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/hooks/useGetUserId.jsx:
--------------------------------------------------------------------------------
1 | const useGetUserId = () => {
2 | return window.localStorage.getItem("userId")
3 |
4 | }
5 | export default useGetUserId
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/.env:
--------------------------------------------------------------------------------
1 | JWT_SECRET=1d522fb81512f05489d894eccfc0b99d1e7f0e47ba88913d622fdd0bc718db2aee00900a67c1206d797079d16ba4ecad521919d79c80fba1c879eebca27f371b
2 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/pages/List.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const List = () => {
4 | return (
5 |
List
6 | )
7 | }
8 |
9 | export default List
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/pages/NotFound.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const NotFound = () => {
4 | return (
5 | NotFound
6 | )
7 | }
8 |
9 | export default NotFound
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/routes/dashboard.js:
--------------------------------------------------------------------------------
1 | const auth = require('../middleware/auth');
2 |
3 | router.get('/dashboard', auth, (req, res) => {
4 | res.send('Welcome to your dashboard!');
5 | });
6 |
--------------------------------------------------------------------------------
/movie-watchlist/vite.config.js:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vite'
2 | import react from '@vitejs/plugin-react'
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | })
8 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/vite.config.js:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vite'
2 | import react from '@vitejs/plugin-react'
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | })
8 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/vite.config.js:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vite'
2 | import react from '@vitejs/plugin-react'
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | })
8 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/tailwind.config.cjs:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: [
4 | "./index.html",
5 | "./src/**/*.{js,ts,jsx,tsx}",
6 | ],
7 | theme: {
8 | extend: {},
9 | },
10 | plugins: [],
11 | }
12 |
--------------------------------------------------------------------------------
/movie-watchlist/tailwind.config.cjs:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: [
4 | "./index.html",
5 | "./src/**/*.{js,ts,jsx,tsx}",
6 | ],
7 | theme: {
8 | extend: {},
9 | },
10 | plugins: [require("daisyui")],
11 | }
12 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/pages/Details.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import LoginForm from '../Form/LoginForm'
3 |
4 | const Details = () => {
5 | return (
6 |
7 |
8 |
9 | )
10 | }
11 |
12 | export default Details
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/pages/Signup.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import SignupForm from '../Form/SignupForm'
3 |
4 | const Signup = () => {
5 | return (
6 |
7 |
8 |
9 | )
10 | }
11 |
12 | export default Signup
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/tailwind.config.cjs:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: [
4 | "./index.html",
5 | "./src/**/*.{js,ts,jsx,tsx}",
6 | ],
7 | theme: {
8 | extend: {},
9 | },
10 | plugins: [require("daisyui")],
11 | }
12 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/API/API.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 |
3 | const API_URL = 'https://www.themealdb.com/api/json/v1/1/search.php';
4 |
5 | export const searchRecipes = async (query) => {
6 | const response = await axios.get(API_URL+'?s='+query);
7 | return response.data;
8 | };
9 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/task-manager/.env:
--------------------------------------------------------------------------------
1 | MONGO_URI = 'mongodb://localhost:27017/task-manager'
2 | SESSION_SECRET = 'edc41be62815b35d63656585f991ee131c7fafda6c8d71d92c05e9f3cfde53e683db9b76169667e610ce9d204898a5adccf0a3c42f966ae36e1a5efb27969e41'
3 | JWT_SECRET = 'edc41be62815b35d63656585f991ee131c7fafda6c8d71d92c05e9f3cfde53e683db9b76169667e610ce9d204898a5adccf0a3c42f966ae36e1a3efb27969e41'
--------------------------------------------------------------------------------
/movie-watchlist/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | pnpm-debug.log*
8 | lerna-debug.log*
9 |
10 | node_modules
11 | dist
12 | dist-ssr
13 | *.local
14 |
15 | # Editor directories and files
16 | .vscode/*
17 | !.vscode/extensions.json
18 | .idea
19 | .DS_Store
20 | *.suo
21 | *.ntvs*
22 | *.njsproj
23 | *.sln
24 | *.sw?
25 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | pnpm-debug.log*
8 | lerna-debug.log*
9 |
10 | node_modules
11 | dist
12 | dist-ssr
13 | *.local
14 |
15 | # Editor directories and files
16 | .vscode/*
17 | !.vscode/extensions.json
18 | .idea
19 | .DS_Store
20 | *.suo
21 | *.ntvs*
22 | *.njsproj
23 | *.sln
24 | *.sw?
25 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/pages/Login.jsx:
--------------------------------------------------------------------------------
1 | import { Link } from "react-router-dom"
2 | import LoginForm from "../Form/LoginForm"
3 | const Login = ({ setIsAuthenticated }) => {
4 | return (
5 |
6 |
7 | Signup
8 |
9 | )
10 | }
11 |
12 | export default Login
--------------------------------------------------------------------------------
/movie-watchlist/src/main.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom/client'
3 | import App from './App'
4 | import './index.css'
5 | import { BrowserRouter } from 'react-router-dom'
6 |
7 | ReactDOM.createRoot(document.getElementById('root')).render(
8 |
9 |
10 |
11 |
12 |
13 | )
14 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | pnpm-debug.log*
8 | lerna-debug.log*
9 |
10 | node_modules
11 | dist
12 | dist-ssr
13 | *.local
14 |
15 | # Editor directories and files
16 | .vscode/*
17 | !.vscode/extensions.json
18 | .idea
19 | .DS_Store
20 | *.suo
21 | *.ntvs*
22 | *.njsproj
23 | *.sln
24 | *.sw?
25 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/main.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom/client'
3 | import App from './App'
4 | import './index.css'
5 | import { BrowserRouter } from 'react-router-dom'
6 |
7 | ReactDOM.createRoot(document.getElementById('root')).render(
8 |
9 |
10 |
11 |
12 |
13 | )
14 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/main.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom/client'
3 | import App from './App'
4 | import './index.css'
5 | import { BrowserRouter } from 'react-router-dom'
6 |
7 | ReactDOM.createRoot(document.getElementById('root')).render(
8 |
9 |
10 |
11 |
12 |
13 | )
14 |
--------------------------------------------------------------------------------
/Connect Local MongoDB/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "project1---connect-mongodb",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "server.js",
6 | "scripts": {
7 | "dev": "nodemon server.js"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.2",
14 | "mongoose": "^6.9.0",
15 | "nodemon": "^2.0.20"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/routes/alluser.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const User = require('../models/user');
4 |
5 | // Get a user
6 | router.get('/', async (req, res) => {
7 | try {
8 | const users = await User.find();
9 | res.json(users);
10 | } catch (err) {
11 | res.status(500).json({ message: err.message });
12 | }
13 | });
14 |
15 | module.exports = router;
--------------------------------------------------------------------------------
/RestAPI/server.js:
--------------------------------------------------------------------------------
1 | import express, { response } from "express";
2 | import bodyParser from "body-parser";
3 | import UserRouter from "./routers/users.js"
4 |
5 | const app = express();
6 | const PORT = 5500;
7 |
8 | app.use(bodyParser.json());
9 | app.use("/", UserRouter)
10 |
11 | app.get("/", (request, response) => {
12 | response.send("Hello RestAPI Home")
13 | })
14 |
15 | app.listen(PORT, () => {
16 | console.log(`Server running ${PORT}`);
17 | })
--------------------------------------------------------------------------------
/task-manager/routes/tasks.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const Task = require('../models/Task');
4 |
5 | // Route handler for GET /tasks
6 |
7 | router.get('/', async (req, res) => {
8 | try {
9 | const tasks = await Task.find({});
10 | res.json(tasks);
11 | } catch (err) {
12 | console.error(err);
13 | res.status(500).send('Server error');
14 | }
15 | });
16 |
17 | module.exports = router;
18 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/routes/category.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import Product from "../models/Product.js";
3 | import Category from "../models/Category.js";
4 |
5 |
6 | const router = express.Router();
7 |
8 | router.get("/", async (req, res)=> {
9 | const getCategories = await Category.find()
10 | getCategories.length > 0 ? res.json(getCategories) : res.json({mesage: "No Category Found"})
11 | })
12 |
13 | export {router as categoryRouter}
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Vite + React
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/movie-watchlist/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Favorite Drama List
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Recipe House
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/RestAPI/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "restapi",
3 | "version": "1.0.0",
4 | "description": "",
5 | "type": "module",
6 | "main": "server.js",
7 | "scripts": {
8 | "dev": "nodemon server.js",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "keywords": [],
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "body-parser": "^1.20.1",
16 | "express": "^4.18.2",
17 | "nodemon": "^2.0.20",
18 | "uuid": "^9.0.0"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/models/Category.js:
--------------------------------------------------------------------------------
1 | import mongoose from "mongoose";
2 |
3 | const category = {
4 | id: {
5 | type: Number,
6 | required: true
7 | },
8 | brand: {
9 | type: String,
10 | required: true
11 | },
12 | image: {
13 | type: String,
14 | required: true
15 | }
16 | }
17 |
18 | const CategorySchema = mongoose.Schema(category);
19 | const Category = mongoose.model("categories", CategorySchema);
20 |
21 | export default Category;
22 |
--------------------------------------------------------------------------------
/movie-watchlist/backend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "backend",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "server.js",
6 | "scripts": {
7 | "dev": "nodemon server.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "keywords": [],
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "body-parser": "^1.20.2",
15 | "cors": "^2.8.5",
16 | "dotenv": "^16.0.3",
17 | "express": "^4.18.2",
18 | "mongoose": "^7.0.0"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/task-manager/models/Task.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 | const Schema = mongoose.Schema;
3 |
4 | const taskSchema = new Schema({
5 | description: {
6 | type: String,
7 | required: true
8 | },
9 | completed: {
10 | type: Boolean,
11 | default: false
12 | },
13 | user: {
14 | type: Schema.Types.ObjectId,
15 | ref: 'User'
16 | }
17 | }, {
18 | timestamps: true
19 | });
20 |
21 | const Task = mongoose.model('Task', taskSchema); // task not Task
22 |
23 | module.exports = Task;
24 |
--------------------------------------------------------------------------------
/UsersAPI with AUTH/models/User.js:
--------------------------------------------------------------------------------
1 | import mongoose from "mongoose"
2 |
3 | const user = {
4 | name: {
5 | type: String,
6 | required: true
7 | },
8 | username: {
9 | type: String,
10 | unique: true,
11 | required: true
12 | },
13 | password: {
14 | type: String,
15 | required: true
16 | }
17 | };
18 | // You can add email too
19 |
20 | const UserModel = mongoose.Schema(user);
21 | const User = mongoose.model("users", UserModel);
22 |
23 | export default User;
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/routes/logout.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const auth = require('../middleware/auth');
4 | // Logout route
5 | router.post('/logout', auth, async (req, res) => {
6 | try {
7 | req.user.tokens = req.user.tokens.filter((token) => {
8 | return token.token !== req.token;
9 | });
10 | await req.user.save();
11 | res.send();
12 | } catch (e) {
13 | res.status(500).send();
14 | }
15 | });
16 |
17 |
18 | module.exports = router;
19 |
--------------------------------------------------------------------------------
/movie-watchlist/src/index.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 | :root {
5 | font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
6 | line-height: 1.5;
7 | font-weight: 400;
8 |
9 | color-scheme: light dark;
10 | color: rgba(255, 255, 255, 0.87);
11 | background-color: #242424;
12 |
13 | font-synthesis: none;
14 | text-rendering: optimizeLegibility;
15 | -webkit-font-smoothing: antialiased;
16 | -moz-osx-font-smoothing: grayscale;
17 | -webkit-text-size-adjust: 100%;
18 | }
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/.idea/blog-post-api-mongodb.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/movie-watchlist/src/App.jsx:
--------------------------------------------------------------------------------
1 | import { useState } from 'react'
2 | import { Routes, Route } from 'react-router-dom'
3 | import './App.css'
4 | import Header from './components/Header/Header'
5 | import Home from './pages/Home'
6 | import List from './pages/List'
7 |
8 | function App() {
9 | return (
10 |
11 |
12 |
13 | } />
14 | } />
15 |
16 |
17 | )
18 | }
19 |
20 | export default App
21 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb/models/Post.js:
--------------------------------------------------------------------------------
1 | import mongoose, { Schema, mongo } from "mongoose";
2 |
3 | // creating post schema, will change later for auth and username
4 | const schema = {
5 | title: {
6 | type: String,
7 | required: true
8 | },
9 | content: {
10 | type: String,
11 | required: true
12 | },
13 | username: {
14 | type: String,
15 | required: true
16 | }
17 | }
18 |
19 | const PostSchema = mongoose.Schema(schema);
20 | const Post = mongoose.model("posts", PostSchema);
21 |
22 | export default Post;
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/index.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
5 | :root {
6 | font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
7 | line-height: 1.5;
8 | font-weight: 400;
9 |
10 | color-scheme: light dark;
11 | color: rgba(255, 255, 255, 0.87);
12 | background-color: #242424;
13 |
14 | font-synthesis: none;
15 | text-rendering: optimizeLegibility;
16 | -webkit-font-smoothing: antialiased;
17 | -moz-osx-font-smoothing: grayscale;
18 | -webkit-text-size-adjust: 100%;
19 | }
20 | /* color: #646cff; */
21 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/routes/user.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const User = require('../models/user');
4 |
5 | // Get a user by id
6 | router.get('/:id', async (req, res) => {
7 | try {
8 | const user = await User.findById(req.params.id);
9 | if (!user) {
10 | return res.status(404).json({ error: 'User not found' });
11 | }
12 | res.json(user);
13 | } catch (err) {
14 | console.error(err.message);
15 | res.status(500).json({ error: 'Server error' });
16 | }
17 | });
18 |
19 | module.exports = router;
20 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/routes/users.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const User = require('../models/user');
4 |
5 | router.post('/signup', async (req, res) => {
6 | const user = new User({
7 | username: req.body.username,
8 | email: req.body.email,
9 | password: req.body.password
10 | });
11 |
12 | try {
13 | const savedUser = await user.save();
14 | res.status(201).json(savedUser);
15 | } catch (err) {
16 | res.status(400).json({ error: err.message });
17 | }
18 | });
19 |
20 | module.exports = router;
21 |
--------------------------------------------------------------------------------
/movie-watchlist/backend/models/Watchlist.js:
--------------------------------------------------------------------------------
1 | const mongoose = require("mongoose");
2 | const Schema = mongoose.Schema;
3 |
4 | const useSchema = new Schema({
5 | name: {
6 | type: String,
7 | required: true
8 | },
9 | thumbnail: {
10 | type: String,
11 | required: true
12 | },
13 |
14 | description: {
15 | type: String,
16 | required: true
17 | },
18 | watched: {
19 | type: Boolean,
20 | required: true
21 | }
22 |
23 | })
24 |
25 |
26 | const Watchlist = mongoose.model("Watchlist", useSchema);
27 |
28 | module.exports = Watchlist;
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "backend",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "server.js",
6 | "scripts": {
7 | "dev": "nodemon server.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "keywords": [],
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "bcrypt": "^5.1.0",
15 | "body-parser": "^1.20.2",
16 | "cors": "^2.8.5",
17 | "dotenv": "^16.0.3",
18 | "express": "^4.18.2",
19 | "jsonwebtoken": "^9.0.0",
20 | "mongoose": "^7.0.0",
21 | "nodemon": "^2.0.21"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/recipe ap with auth/backend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "backend",
3 | "version": "1.0.0",
4 | "description": "",
5 | "type": "module",
6 | "main": "server.js",
7 | "scripts": {
8 | "dev": "nodemon server.js",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "keywords": [],
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "bcrypt": "^5.1.0",
16 | "body-parser": "^1.20.2",
17 | "cors": "^2.8.5",
18 | "dotenv": "^16.0.3",
19 | "express": "^4.18.2",
20 | "jsonwebtoken": "^9.0.0",
21 | "mongoose": "^7.0.1",
22 | "nodemon": "^2.0.21"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/task-manager/models/Todo.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | const todoSchema = new mongoose.Schema({
4 | title: {
5 | type: String,
6 | required: true
7 | },
8 | description: {
9 | type: String,
10 | required: true
11 | },
12 | user: {
13 | type: mongoose.Schema.Types.ObjectId,
14 | ref: 'User',
15 | required: true
16 | },
17 | completed: {
18 | type: Boolean,
19 | default: false
20 | },
21 | created: {
22 | type: Date,
23 | default: Date.now
24 | }
25 | });
26 |
27 | const Todo = mongoose.model('Todo', todoSchema); // todo not Todo
28 |
29 | module.exports = Todo;
30 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb/models/User.js:
--------------------------------------------------------------------------------
1 | import mongoose from "mongoose";
2 |
3 | const user = {
4 | name: {
5 | type: String,
6 | required: true
7 | },
8 | username: {
9 | type: String,
10 | required: true,
11 | unique: true
12 | },
13 | email: {
14 | type: String,
15 | required: true
16 | },
17 | password: {
18 | type: String,
19 | required: true
20 | },
21 | post: {
22 | type: Array
23 | }
24 | }
25 |
26 | const UserSchema = mongoose.Schema(user);
27 | const User = mongoose.model("users", UserSchema);
28 |
29 | export default User;
30 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/models/User.js:
--------------------------------------------------------------------------------
1 | import mongoose from 'mongoose';
2 |
3 | const userSchema = new mongoose.Schema({
4 | name: {
5 | type: String,
6 | required: true
7 | },
8 | username: {
9 | type: String,
10 | required: true,
11 | unique: true
12 | },
13 | phoneNumber: {
14 | type: String,
15 | required: true,
16 | unique: true
17 | },
18 | password: {
19 | type: String,
20 | required: true
21 | },
22 | type: {
23 | type: String,
24 | enum: ['admin', 'user'],
25 | default: 'user'
26 | },
27 | });
28 |
29 | const User = mongoose.model('users', userSchema);
30 |
31 | export default User;
--------------------------------------------------------------------------------
/realmate/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "realmate",
3 | "version": "1.0.0",
4 | "description": "API for realmate web application",
5 | "main": "server.js",
6 | "author": "DevvSakib",
7 | "type": "module",
8 | "license": "MIT",
9 | "private": false,
10 | "scripts": {
11 | "start": "node server.js",
12 | "dev": "nodemon server.js"
13 | },
14 | "dependencies": {
15 | "bcrypt": "^5.1.0",
16 | "body-parser": "^1.20.2",
17 | "cors": "^2.8.5",
18 | "dotenv": "^16.3.1",
19 | "express": "^4.18.2",
20 | "jsonwebtoken": "^9.0.0",
21 | "mongoose": "^7.3.1",
22 | "nodemon": "^2.0.22",
23 | "short-uuid": "^4.2.2",
24 | "uuid": "^9.0.0"
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/recipe ap with auth/backend/models/User.js:
--------------------------------------------------------------------------------
1 | import mongoose from "mongoose";
2 |
3 | const user = {
4 | username: {
5 | type: String,
6 | require: true,
7 | unique: true
8 | },
9 | password: {
10 | type: String,
11 | require: true
12 | },
13 | email: {
14 | type: String,
15 | require: true,
16 | unique: true
17 | },
18 | savedRecipes: [
19 | {
20 | type: mongoose.Schema.Types.ObjectId,
21 | ref: "recipes"
22 | }
23 | ]
24 | }
25 |
26 | const UserSchema = new mongoose.Schema(user)
27 |
28 |
29 | const UserModel = mongoose.model("users", UserSchema)
30 |
31 | export default UserModel;
--------------------------------------------------------------------------------
/movie-watchlist/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "movie-watchlist",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite --open",
8 | "build": "vite build",
9 | "preview": "vite preview"
10 | },
11 | "dependencies": {
12 | "axios": "^1.3.4",
13 | "react": "^18.2.0",
14 | "react-dom": "^18.2.0",
15 | "react-router-dom": "^6.8.2"
16 | },
17 | "devDependencies": {
18 | "@types/react": "^18.0.27",
19 | "@types/react-dom": "^18.0.10",
20 | "@vitejs/plugin-react": "^3.1.0",
21 | "autoprefixer": "^10.4.13",
22 | "daisyui": "^2.51.0",
23 | "postcss": "^8.4.21",
24 | "tailwindcss": "^3.2.7",
25 | "vite": "^4.1.0"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "farming2.0",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "vite build",
9 | "preview": "vite preview"
10 | },
11 | "dependencies": {
12 | "axios": "^1.3.4",
13 | "react": "^18.2.0",
14 | "react-cookie": "^4.1.1",
15 | "react-dom": "^18.2.0",
16 | "react-router-dom": "^6.9.0"
17 | },
18 | "devDependencies": {
19 | "@types/react": "^18.0.27",
20 | "@types/react-dom": "^18.0.10",
21 | "@vitejs/plugin-react": "^3.1.0",
22 | "autoprefixer": "^10.4.14",
23 | "postcss": "^8.4.21",
24 | "tailwindcss": "^3.2.7",
25 | "vite": "^4.1.0"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/UserDetails.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import axios from 'axios';
3 |
4 | const UserDetails = () => {
5 | const [user, setUser] = useState(null);
6 |
7 | useEffect(() => {
8 | const fetchUser = async () => {
9 | try {
10 | const res = await axios.get('http://localhost:5000/users/user');
11 | setUser(res.data);
12 | } catch (err) {
13 | console.error(err);
14 | }
15 | };
16 |
17 | fetchUser();
18 | }, []);
19 |
20 | if (!user) {
21 | return null;
22 | }
23 |
24 | return (
25 |
26 | Welcome, {user.username}!
27 |
28 | );
29 | };
30 |
31 | export default UserDetails;
32 |
--------------------------------------------------------------------------------
/recipe ap with auth/backend/server.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import cors from "cors";
3 | import dotenv from "dotenv";
4 | import mongoose from "mongoose";
5 | import bodyPerser from "body-parser";
6 |
7 | import { userRouter } from "./routes/users.js"
8 | import { recipesRouter } from "./routes/recipes.js"
9 |
10 | const PORT = process.env.PORT || 5000
11 | dotenv.config();
12 |
13 | const app = express();
14 | app.use(bodyPerser.json())
15 | app.use(cors())
16 |
17 |
18 | app.use('/auth', userRouter)
19 | app.use('/recipes', recipesRouter)
20 |
21 |
22 | mongoose.connect(process.env.MONGO_URI, {
23 | useNewUrlParser: true,
24 | useUnifiedTopology: true,
25 | })
26 |
27 |
28 | app.listen(PORT, () => console.log(`Server running at ${PORT} dude...`))
--------------------------------------------------------------------------------
/blog-post-api-mongodb/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "blog-api-mongodb",
3 | "version": "0.0.1",
4 | "description": "API for blog, Database used MongoDB, Auth JWT",
5 | "main": "server.js",
6 | "type": "module",
7 | "scripts": {
8 | "dev": "nodemon server.js",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "keywords": [
12 | "blogapi",
13 | "blog",
14 | "jwt",
15 | "auth"
16 | ],
17 | "author": "DevvSakib",
18 | "license": "ISC",
19 | "dependencies": {
20 | "bcrypt": "^5.1.0",
21 | "body-parser": "^1.20.2",
22 | "cors": "^2.8.5",
23 | "dotenv": "^16.0.3",
24 | "express": "^4.18.2",
25 | "jsonwebtoken": "^9.0.0",
26 | "mongoose": "^7.0.3",
27 | "nodemon": "^2.0.22"
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/Cards/ReciepeCard.jsx:
--------------------------------------------------------------------------------
1 | const ReciepeCard = () => {
2 | return (
3 |
4 | Reciepe
5 |
6 | );
7 | }
8 |
9 | const itemData = [
10 | {
11 | img: 'https://images.unsplash.com/photo-1551963831-b3b1ca40c98e',
12 | title: 'Breakfast',
13 | author: '@bkristastucchio',
14 | },
15 | {
16 | img: 'https://images.unsplash.com/photo-1551782450-a2132b4ba21d',
17 | title: 'Burger',
18 | author: '@rollelflex_graphy726',
19 | },
20 | {
21 | img: 'https://images.unsplash.com/photo-1589118949245-7d38baf380d6',
22 | title: 'Bike',
23 | author: '@southside_customs',
24 | },
25 | ];
26 |
27 | export default ReciepeCard;
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "blog-api-mongodb",
3 | "version": "0.0.1",
4 | "description": "API for blog, Database used MongoDB, Auth JWT",
5 | "main": "server.js",
6 | "type": "module",
7 | "scripts": {
8 | "dev": "nodemon server.js",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "keywords": [
12 | "blogapi",
13 | "blog",
14 | "jwt",
15 | "auth"
16 | ],
17 | "author": "DevvSakib",
18 | "license": "ISC",
19 | "dependencies": {
20 | "bcrypt": "^5.1.0",
21 | "body-parser": "^1.20.2",
22 | "cors": "^2.8.5",
23 | "dotenv": "^16.0.3",
24 | "express": "^4.18.2",
25 | "jsonwebtoken": "^9.0.0",
26 | "mongoose": "^7.0.3",
27 | "nodemon": "^2.0.22"
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/task-manager/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "bcrypt": "^5.1.0",
4 | "cors": "^2.8.5",
5 | "dotenv": "^16.0.3",
6 | "express": "^4.18.2",
7 | "express-session": "^1.17.3",
8 | "jsonwebtoken": "^9.0.0",
9 | "mongoose": "^7.0.0",
10 | "nodemon": "^2.0.21",
11 | "passport": "^0.6.0",
12 | "passport-jwt": "^4.0.1",
13 | "passport-local": "^1.0.0",
14 | "passport-local-mongoose": "^7.1.2",
15 | "react": "^18.2.0"
16 | },
17 | "name": "backend",
18 | "version": "1.0.0",
19 | "main": "server.js",
20 | "scripts": {
21 | "dev": "nodemon server.js",
22 | "test": "echo \"Error: no test specified\" && exit 1"
23 | },
24 | "keywords": [],
25 | "author": "",
26 | "license": "ISC",
27 | "description": ""
28 | }
29 |
--------------------------------------------------------------------------------
/UsersAPI with AUTH/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "usersapi-with-auth",
3 | "version": "0.0.1",
4 | "description": "Users API. Create, delete, update, auth, get all user",
5 | "main": "server.js",
6 | "type": "module",
7 | "scripts": {
8 | "dev": "nodemon server.js",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "dependencies": {
12 | "bcrypt": "^5.1.0",
13 | "body-parser": "^1.20.2",
14 | "cors": "^2.8.5",
15 | "dotenv": "^16.0.3",
16 | "express": "^4.18.2",
17 | "jsonwebtoken": "^9.0.0",
18 | "mongoose": "^7.0.3"
19 | },
20 | "keywords": [
21 | "restapi",
22 | "auth",
23 | "expressjs"
24 | ],
25 | "author": "DevvSakib",
26 | "license": "ISC",
27 | "devDependencies": {
28 | "nodemon": "^2.0.22"
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Connect Local MongoDB/server.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const mongoose = require("mongoose");
3 |
4 | const mongoseUrl = "mongodb://localhost:27017/TUTORIAL"
5 | // base url - mongodb://localhost:27017
6 | // db name - TUTORIAL
7 |
8 | mongoose.connect(mongoseUrl, (error, db) => {
9 | // find one
10 | // db.collection("content").findOne({name: "0xDevvSakib"},(err, res)=>{
11 | // if(err) throw new Error(err);
12 | // console.log(res);
13 | // });
14 |
15 | // find all
16 | db.collection("content").find({}).toArray((err, res) => {
17 | if (err) throw new Error(err);
18 | console.log(res);
19 | db.close();
20 | });
21 | })
22 |
23 | const app = express();
24 |
25 | app.listen(5050, () => {
26 | console.log("Server running...");
27 | })
--------------------------------------------------------------------------------
/movie-watchlist/backend/server.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const mongoose = require("mongoose");
3 | const cors = require("cors");
4 | require("dotenv").config();
5 | const bodyParser = require("body-parser");
6 | const PORT = process.env.PORT || 3000
7 |
8 | const app = express();
9 | app.use(cors())
10 | app.use(bodyParser.json())
11 |
12 | mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
13 | .then(() => {
14 | console.log('Connected to MongoDB');
15 | })
16 | .catch((err) => {
17 | console.log('Error connecting to MongoDB', err);
18 | });
19 |
20 | // import routes
21 | const watchlistRoutes = require("./routes/watched")
22 |
23 | app.use("/", watchlistRoutes)
24 |
25 |
26 |
27 | app.listen(PORT, () => console.log("Server running at PORT: ", PORT))
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/models/Product.js:
--------------------------------------------------------------------------------
1 | import mongoose, { Schema, mongo } from "mongoose";
2 |
3 | // creating post schema, will change later for auth and username
4 | const schema = {
5 | brand: {
6 | type: String,
7 | required: true
8 | },
9 | model: {
10 | type: String,
11 | required: true
12 | },
13 | available: {
14 | type: Boolean,
15 | required: true
16 | },
17 | slug: {
18 | type: String,
19 | required: true
20 | },
21 | image: {
22 | type: String,
23 | required: true
24 | },
25 | price: {
26 | type: Number,
27 | required: true
28 | }
29 | }
30 |
31 | const ProductSchema = mongoose.Schema(schema);
32 | const Product = mongoose.model("products", ProductSchema);
33 |
34 | export default Product;
--------------------------------------------------------------------------------
/recipe ap with auth/backend/models/Recipes.js:
--------------------------------------------------------------------------------
1 | import mongoose from "mongoose";
2 |
3 |
4 | const user = {
5 | name: {
6 | type: String,
7 | require: true,
8 | },
9 | ingredients: [{
10 | type: String,
11 | require: true
12 | }],
13 | instructions: {
14 | type: String,
15 | require: true
16 | },
17 | imageUrl:{
18 | type: String,
19 | require: true
20 | },
21 | cookTime:{
22 | type: Number,
23 | require: true
24 | },
25 | owner:{
26 | type: mongoose.Schema.Types.ObjectId,
27 | ref: 'users',
28 | require: true
29 | },
30 | }
31 |
32 | const RecipesSchema = new mongoose.Schema(user)
33 |
34 |
35 | const RecipesModel = mongoose.model("recipes", RecipesSchema)
36 |
37 | export default RecipesModel;
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/routes/getuser.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const auth = require('../middleware/auth');
4 |
5 |
6 | // Logout route
7 |
8 | router.post('/', auth, async (req, res) => {
9 | try {
10 | // console.log(req.body);
11 | // const decoded = jwt.verify(req.token, process.env.JWT_SECRET);
12 | // const userId = decoded.userId;
13 | // const user = await User.findById(userId);
14 | // console.log(req.token);
15 | if (!user) {
16 | return res.status(404).json({ error: 'User not found' });
17 | }
18 | res.send("dsfsd");
19 | } catch (err) {
20 | console.error(err.message);
21 | res.status(500).json({ error: 'Server error' });
22 | }
23 | });
24 |
25 |
26 | module.exports = router;
27 |
--------------------------------------------------------------------------------
/UsersAPI with AUTH/server.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import dotenv from "dotenv"
3 | import mongoose from "mongoose"
4 | import cors from "cors"
5 | import bodyParser from "body-parser"
6 | import usersRoute from "./routes/users.js"
7 |
8 | const PORT = process.env.PORT || 5000
9 | const app = express()
10 |
11 | dotenv.config()
12 | app.use(bodyParser.json())
13 | app.use(cors())
14 |
15 | app.use("/", usersRoute)
16 |
17 | app.use("/", (req, res) => {
18 | res.json({
19 | status: "API working fine",
20 | code: 200
21 | })
22 | })
23 |
24 |
25 | mongoose.connect(process.env.MONGO_URI, {
26 | useNewUrlParser: true,
27 | useUnifiedTopology: true,
28 | })
29 | .then(() => app.listen(PORT, () => console.log(`DB Connected\nServer running on port: ${PORT}`)))
30 | .catch((error) => console.log(error.message))
31 |
32 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/components/Cards.jsx:
--------------------------------------------------------------------------------
1 | // import React from 'react'
2 |
3 | // const Cards = () => {
4 | // return (
5 | //
6 | //
7 | //
8 | //
9 | //
Shoes!
10 | //
If a dog chews shoes whose shoes does he choose?
11 | //
12 | // Buy Now
13 | //
14 | //
15 | //
16 | //
17 | // )
18 | // }
19 |
20 | // export default Cards
--------------------------------------------------------------------------------
/task-manager/models/User.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 | const Schema = mongoose.Schema;
3 | const bcrypt = require('bcrypt');
4 |
5 | const userSchema = new Schema({
6 | email: {
7 | type: String,
8 | required: true,
9 | unique: true,
10 | lowercase: true
11 | },
12 | password: {
13 | type: String,
14 | required: true
15 | }
16 | });
17 |
18 | // Hash the password before saving the user model
19 | userSchema.pre('save', async function(next) {
20 | const user = this;
21 | const hash = await bcrypt.hash(this.password, 10);
22 | this.password = hash;
23 | next();
24 | });
25 |
26 | // Compare password method for authenticating user
27 | userSchema.methods.comparePassword = async function(password) {
28 | return await bcrypt.compare(password, this.password);
29 | };
30 |
31 | module.exports = mongoose.model('User', userSchema);
32 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "recipe-sharing-platform",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "vite build",
9 | "preview": "vite preview"
10 | },
11 | "dependencies": {
12 | "@mui/icons-material": "^5.11.11",
13 | "axios": "^1.3.4",
14 | "daisyui": "^2.51.3",
15 | "jsonwebtoken": "^9.0.0",
16 | "jwt-decode": "^3.1.2",
17 | "react": "^18.2.0",
18 | "react-dom": "^18.2.0",
19 | "react-router": "^6.8.2",
20 | "react-router-dom": "^6.8.2"
21 | },
22 | "devDependencies": {
23 | "@types/react": "^18.0.27",
24 | "@types/react-dom": "^18.0.10",
25 | "@vitejs/plugin-react": "^3.1.0",
26 | "autoprefixer": "^10.4.13",
27 | "postcss": "^8.4.21",
28 | "tailwindcss": "^3.2.7",
29 | "vite": "^4.1.0"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/App.jsx:
--------------------------------------------------------------------------------
1 | import { useState } from 'react'
2 | import './App.css'
3 | import { Routes, Route } from 'react-router-dom'
4 | import Home from './pages/Home'
5 | import CreateRecipe from './pages/CreateRecipe'
6 | import SavedRecipes from './pages/SavedRecipes'
7 | import Auth from './pages/Auth'
8 | import NotFound from './pages/NotFound'
9 | import Header from './components/Header'
10 |
11 | function App() {
12 |
13 | return (
14 |
15 |
16 |
17 | } />
18 | } />
19 | } />
20 | } />
21 | } />
22 |
23 |
24 | )
25 | }
26 |
27 | export default App
28 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/middleware/auth.js:
--------------------------------------------------------------------------------
1 |
2 | const jwt = require('jsonwebtoken');
3 | const User = require('../models/user');
4 |
5 | const auth = async (req, res, next) => {
6 | try {
7 | // Check if the request contains an authorization header
8 | const token = req.header('Authorization').replace('Bearer ', '');
9 |
10 | // Verify the token
11 | const decoded = jwt.verify(token, process.env.JWT_SECRET);
12 |
13 | // Find the user associated with the token
14 | const user = await User.findOne({ _id: decoded.userId, 'tokens.token': token });
15 |
16 | if (!user) {
17 | throw new Error();
18 | }
19 |
20 | // Store the user and token on the request object
21 | req.user = user;
22 | req.token = token;
23 |
24 | next();
25 | } catch (error) {
26 | res.status(401).send({ error: 'Please authenticate.' });
27 | }
28 | };
29 |
30 | module.exports = auth;
31 |
--------------------------------------------------------------------------------
/movie-watchlist/src/pages/List.jsx:
--------------------------------------------------------------------------------
1 |
2 | import WatchedCard from '../components/Watched/WatchedCard'
3 | import WatchlistCard from '../components/Watchlist/WatchlistCard'
4 |
5 | const List = () => {
6 |
7 |
8 | return (
9 |
10 |
11 |
12 |
13 |
Watched
14 |
15 |
16 |
17 |
18 |
19 |
Watchlist
20 |
21 |
22 |
23 |
24 |
25 |
26 | )
27 | }
28 |
29 | export default List
--------------------------------------------------------------------------------
/RestAPI/routers/users.js:
--------------------------------------------------------------------------------
1 | import express, { request, response } from "express";
2 | import { v4 as uuidv4 } from "uuid";
3 |
4 | const router = express.Router();
5 |
6 | let users = [
7 | ]
8 |
9 | router.get("/user", (request, response) => {
10 | response.send(users)
11 | })
12 |
13 | router.post("/user", (request, response) => {
14 | const user = request.body;
15 | const userId = uuidv4();
16 | const addUserId = { ...user, id: userId }
17 | users.push(addUserId)
18 | response.send(user);
19 | })
20 |
21 | router.get("/user/:id", (request, response) => {
22 | const { id } = request.params;
23 | const userFound = users.find(user => user.id === id)
24 | response.send(userFound)
25 | })
26 |
27 | router.delete("/user/:id", (request, response) => {
28 | const { id } = request.params;
29 | users = users.filter(user => user.id !== id)
30 | response.send(`this ${id} user deleted.`)
31 | })
32 |
33 | export default router
--------------------------------------------------------------------------------
/Connect Local MongoDB/README.md:
--------------------------------------------------------------------------------
1 | # Connecting Local MongoDB
2 |
3 | #
4 |
5 | ## How to connect local MongoDB
6 |
7 | 1. First copy the connection string from MongoDB Compass
8 |
9 |
10 |
11 | 2. Then paste the connection string in the code
12 | ```bash
13 | mongodb://localhost:27017/{db name}
14 | ```
15 |
16 | 3. Then write the code to connect mongodb
17 |
18 | ```js
19 | const mongoseUrl = "mongodb://localhost:27017/{db name}";
20 | mongoose.connect(mongoseUrl, (error, db) => {
21 | db.collection("{collection name}").find({}).toArray((err, res) => {
22 | if (err) throw new Error(err);
23 | console.log(res);
24 | db.close();
25 | });
26 | })
27 | ```
28 |
29 | 4. Then run the code
30 |
31 | ## How to run the code
32 |
33 | 1. First install the dependencies
34 |
35 | ```bash
36 | npm install
37 | ```
38 |
39 | 2. Then run the code
40 |
41 | ```bash
42 | npm run dev
43 | ```
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/routes/login.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const jwt = require('jsonwebtoken');
4 | const User = require('../models/user');
5 | require('dotenv').config();
6 | const secretKey = process.env.JWT_SECRET;
7 |
8 | router.post('/login', async (req, res) => {
9 | const { email, password } = req.body;
10 |
11 | // Find user by email
12 | const user = await User.findOne({ email });
13 |
14 | if (!user) {
15 | return res.status(401).json({ error: 'Invalid email or password' });
16 | }
17 |
18 | // Compare password
19 | const isMatch = await user.comparePassword(password);
20 |
21 | if (!isMatch) {
22 | return res.status(401).json({ error: 'Invalid email or password' });
23 | }
24 |
25 | // User authenticated, generate token and return user object
26 |
27 | const token = jwt.sign({ userId: user._id }, secretKey);
28 | const { _id, username } = user;
29 | res.json({ token, user: { _id, username, email } });
30 | });
31 |
32 |
33 |
34 | module.exports = router;
35 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/Cards/Gallary.jsx:
--------------------------------------------------------------------------------
1 |
2 |
3 | export default function Gallary({ recipes }) {
4 | return (
5 |
6 | {recipes && recipes.map((recipe) =>
7 |
8 |
9 |
10 |
11 | {recipe.strMeal}
12 | NEW
13 |
14 |
15 |
Favorite
16 |
Reciepe
17 |
18 |
19 |
20 | )}
21 |
22 | );
23 | }
24 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb/server.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import mongoose from "mongoose";
3 | import bodyParser from "body-parser";
4 | import cors from "cors";
5 | import dotenv from "dotenv";
6 | import { postRouter } from "./routes/posts.js";
7 | import { userRouter } from "./routes/users.js";
8 | dotenv.config();
9 |
10 |
11 | const PORT = process.env.PORT || 5000;
12 | const app = express();
13 | app.use(cors())
14 | app.use(bodyParser.json())
15 |
16 |
17 | mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
18 | .then(() => {
19 | console.log('Connected to MongoDB');
20 | return mongoose.connection.db.listCollections().toArray();
21 | }
22 | )
23 | .then((collections) => {
24 | console.log(collections.map((c) => c.name));
25 | })
26 | .catch(err => console.error(err));
27 |
28 |
29 | app.use("/", postRouter)
30 | app.use("/users", userRouter)
31 |
32 | app.get("/*", (req, res) => res.json({ Message: "Hi, I'm working fine✅" }))
33 |
34 | app.listen(PORT, () => console.log(`Server running at ${PORT}`))
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/models/user.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 | const bcrypt = require('bcrypt');
3 |
4 | const userSchema = new mongoose.Schema({
5 | username: {
6 | type: String,
7 | required: true,
8 | unique: true,
9 | trim: true,
10 | minlength: 3
11 | },
12 | email: {
13 | type: String,
14 | required: true,
15 | unique: true,
16 | trim: true,
17 | lowercase: true
18 | },
19 | password: {
20 | type: String,
21 | required: true,
22 | trim: true,
23 | minlength: 6
24 | }
25 | });
26 |
27 | userSchema.pre('save', async function(next) {
28 | const user = this;
29 | if (!user.isModified('password')) {
30 | return next();
31 | }
32 | const salt = await bcrypt.genSalt();
33 | user.password = await bcrypt.hash(user.password, salt);
34 | next();
35 | });
36 |
37 | userSchema.methods.comparePassword = async function(password) {
38 | const user = this;
39 | return await bcrypt.compare(password, user.password);
40 | };
41 |
42 | const User = mongoose.model('User', userSchema);
43 |
44 | module.exports = User;
45 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/image.json:
--------------------------------------------------------------------------------
1 | const itemData = [
2 | {
3 | img: 'https://images.unsplash.com/photo-1518756131217-31eb79b20e8f',
4 | title: 'Fern',
5 | },
6 | {
7 | img: 'https://images.unsplash.com/photo-1597645587822-e99fa5d45d25',
8 | title: 'Mushrooms',
9 | },
10 | {
11 | img: 'https://images.unsplash.com/photo-1471357674240-e1a485acb3e1',
12 | title: 'Sea star',
13 | },
14 | {
15 | img: 'https://images.unsplash.com/photo-1558642452-9d2a7deb7f62',
16 | title: 'Honey',
17 | },
18 | {
19 | img: 'https://images.unsplash.com/photo-1551963831-b3b1ca40c98e',
20 | title: 'Breakfast',
21 | },
22 | {
23 | img: 'https://images.unsplash.com/photo-1551782450-a2132b4ba21d',
24 | title: 'Burger',
25 | },
26 | {
27 | img: 'https://images.unsplash.com/photo-1444418776041-9c7e33cc5a9c',
28 | title: 'Coffee',
29 | },
30 |
31 | {
32 | img: 'https://images.unsplash.com/photo-1567306301408-9b74779a11af',
33 | title: 'Tomato basil',
34 | }
35 | ];
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 DevvSakib
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/server.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import mongoose from "mongoose";
3 | import bodyParser from "body-parser";
4 | import cors from "cors";
5 | import dotenv from "dotenv";
6 | import { productRouter } from "./routes/products.js";
7 | import { categoryRouter } from "./routes/category.js";
8 | import { userRouter } from "./routes/users.js"
9 | dotenv.config();
10 |
11 |
12 | const PORT = process.env.PORT || 5000;
13 | const app = express();
14 | app.use(cors())
15 | app.use(bodyParser.json())
16 |
17 | mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
18 | .then(() => {
19 | console.log('Connected to MongoDB');
20 | return mongoose.connection.db.listCollections().toArray();
21 | }
22 | )
23 | .then((collections) => {
24 | console.log(collections.map((c) => c.name));
25 | })
26 | .catch(err => console.error(err));
27 |
28 |
29 | app.use("/", productRouter)
30 | app.use("/categories", categoryRouter)
31 | app.use("/user", userRouter)
32 |
33 | app.get("/*", (req, res) => res.json({ Message: "Hi, I'm working fine✅" }))
34 |
35 | app.listen(PORT, () => console.log(`Server running at ${PORT}`))
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/components/Login.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Link } from 'react-router-dom'
3 |
4 | const Login = ({ setUsername, setPassword, username, password, handleLogin }) => {
5 | return (
6 |
7 |
Login
8 |
23 |
24 | )
25 | }
26 |
27 | export default Login
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/Search/SearchInput.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import { searchRecipes } from '../API/API';
3 | import Gallary from '../Cards/Gallary';
4 |
5 | const SearchInput = ({ recipes, setRecipes }) => {
6 | const [searchQuery, setSearchQuery] = useState('');
7 | const [error, setError] = useState(null);
8 |
9 | async function handleInputChange(event) {
10 | const query = event.target.value;
11 | setSearchQuery(query);
12 | try {
13 | const response = await searchRecipes(query);
14 | setRecipes(response.meals || []);
15 | setError(null);
16 | } catch (error) {
17 | console.error(error);
18 | setRecipes([]);
19 | setError('Error searching for recipes');
20 | }
21 | }
22 |
23 | return (
24 |
25 |
32 |
33 | );
34 | };
35 |
36 | export default SearchInput;
37 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/App.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react'
2 | import { Routes, Route } from 'react-router-dom'
3 | import './App.css'
4 |
5 | import Home from './components/pages/Home'
6 | import List from './components/pages/List'
7 | import Details from './components/pages/Details'
8 | import Header from './components/Header/Header'
9 | import Login from './components/pages/Login'
10 | import Signup from './components/pages/Signup'
11 | import Dashboard from './components/pages/Dashboard'
12 | import UserDetails from './components/UserDetails'
13 |
14 | function App() {
15 | const [isAuthenticated, setIsAuthenticated] = useState(true);
16 | return (
17 |
18 |
19 | {isAuthenticated ? : null}
20 |
21 | } />
22 | } />
23 | } />
24 | } />
25 | } />
26 | } />
27 |
28 |
29 | )
30 | }
31 |
32 | export default App
33 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/models/recipe.js:
--------------------------------------------------------------------------------
1 | // const mongoose = require('mongoose');
2 |
3 | // const Schema = mongoose.Schema;
4 |
5 | // const recipeSchema = new Schema({
6 | // title: { type: String, required: true },
7 | // description: { type: String, required: true }
8 | // // ingredients: { type: [String], required: true },
9 | // // instructions: { type: [String], required: true },
10 | // // category: { type: String, required: true },
11 | // // image: { type: String },
12 | // // createdAt: { type: Date, default: Date.now },
13 | // // updatedAt: { type: Date, default: Date.now }
14 | // });
15 |
16 | // const userSchema = new Schema({
17 | // username: { type: String, required: true },
18 | // password: { type: String, required: true },
19 | // createdAt: { type: Date, default: Date.now }
20 | // });
21 |
22 | // const Recipe = mongoose.model('Recipe', recipeSchema);
23 | // const User = mongoose.model('User', userSchema);
24 |
25 | // module.exports = { Recipe, User };
26 | const mongoose = require('mongoose');
27 |
28 | const Schema = mongoose.Schema;
29 |
30 | const recipeSchema = new Schema({
31 | title: { type: String, required: true },
32 | description: { type: String, required: true }
33 | });
34 |
35 | const Recipe = mongoose.model('Recipe', recipeSchema);
36 |
37 | module.exports = Recipe;
38 |
--------------------------------------------------------------------------------
/task-manager/server.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const mongoose = require('mongoose');
3 | const session = require('express-session');
4 | const passport = require('passport');
5 | const LocalStrategy = require('passport-local').Strategy;
6 | const passportLocalMongoose = require('passport-local-mongoose');
7 | const cors = require('cors');
8 | require('dotenv').config();
9 | require('./passport');
10 |
11 | mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
12 | .then(() => {
13 | console.log('Connected to MongoDB');
14 | })
15 | .catch((err) => {
16 | console.log('Error connecting to MongoDB', err);
17 | });
18 |
19 |
20 | const app = express();
21 |
22 | app.use(express.json());
23 | app.use(express.urlencoded({ extended: true }));
24 | app.use(cors());
25 | app.use(session({
26 | secret: process.env.SESSION_SECRET,
27 | resave: false,
28 | saveUninitialized: false
29 | }));
30 |
31 | app.use(passport.initialize());
32 | app.use(passport.session());
33 |
34 |
35 | const tasksRouter = require('./routes/tasks');
36 | const todoRouter = require('./routes/todos');
37 | const usersRouter = require('./routes/users');
38 |
39 | app.use('/tasks', tasksRouter);
40 | app.use('/todos', todoRouter);
41 | app.use('/users', usersRouter);
42 |
43 |
44 |
45 | app.listen(5000, () => {
46 | console.log('Server started on port 5000');
47 | });
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/server.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const app = express();
3 | const jwt = require('jsonwebtoken');
4 | const mongoose = require('mongoose');
5 | const cors = require('cors');
6 | const PORT = 5000;
7 | const recipeRoutes = require('./routes/recipes');
8 | const userRoutes = require('./routes/users');
9 | const loginRoutes = require('./routes/login');
10 | const logoutRoutes = require('./routes/logout');
11 | const sUserRoutes = require('./routes/user');
12 | const alluserRoutes = require('./routes/alluser');
13 | const getuserRoutes = require('./routes/getuser');
14 |
15 | // dotenv
16 | require('dotenv').config();
17 |
18 | app.use(express.json());
19 | app.use(cors());
20 |
21 | // Connect to MongoDB
22 | mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true })
23 | .then(() => {
24 | console.log('Connected to MongoDB');
25 | })
26 | .catch((err) => {
27 | console.log('Error connecting to MongoDB', err);
28 | });
29 |
30 | // Routes
31 | app.use('/recipes', recipeRoutes);
32 | app.use('/users', userRoutes);
33 | app.use('/users', loginRoutes);
34 | app.use('/users', logoutRoutes);
35 | app.use('/users', sUserRoutes);
36 | app.use('/users', alluserRoutes);
37 | app.use('/users', getuserRoutes);
38 |
39 |
40 | // Start the server
41 | app.listen(PORT, () => {
42 | console.log(`Server started on port ${PORT}`);
43 | });
44 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/backend/routes/recipes.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const Recipe = require('../models/recipe');
4 |
5 | // Create a new recipe
6 | router.post('/', (req, res) => {
7 | const recipe = new Recipe(req.body);
8 |
9 | recipe.save()
10 | .then(() => res.json(recipe))
11 | .catch(err => res.status(400).json({ error: err.message }));
12 | });
13 |
14 | // Get all recipes
15 | router.get('/', (req, res) => {
16 | Recipe.find()
17 | .then(recipes => res.json(recipes))
18 | .catch(err => res.status(400).json({ error: err.message }));
19 | });
20 |
21 | // Get a single recipe by ID
22 | router.get('/:id', (req, res) => {
23 | Recipe.findById(req.params.id)
24 | .then(recipe => res.json(recipe))
25 | .catch(err => res.status(400).json({ error: err.message }));
26 | });
27 |
28 | // Update a recipe by ID
29 | router.put('/:id', (req, res) => {
30 | Recipe.findByIdAndUpdate(req.params.id, req.body, { new: true })
31 | .then(recipe => res.json(recipe))
32 | .catch(err => res.status(400).json({ error: err.message }));
33 | });
34 |
35 | // Delete a recipe by ID
36 | router.delete('/:id', (req, res) => {
37 | Recipe.findByIdAndDelete(req.params.id)
38 | .then(() => res.json({ message: 'Recipe deleted successfully' }))
39 | .catch(err => res.status(400).json({ error: err.message }));
40 | });
41 |
42 | module.exports = router;
43 |
44 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/Form/SignupForm.jsx:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import axios from 'axios';
3 |
4 | function SignupForm() {
5 | const [username, setUsername] = useState('');
6 | const [email, setEmail] = useState('');
7 | const [password, setPassword] = useState('');
8 |
9 | const handleSignup = async (e) => {
10 | e.preventDefault();
11 | try {
12 | const response = await axios.post('http://localhost:5000/users/signup', { username, email, password });
13 | window.location = '/login';
14 | console.log(response.data);
15 | // handle successful signup
16 | } catch (err) {
17 | console.error(err.response.data);
18 | // handle error
19 | }
20 | };
21 |
22 | return (
23 |
41 | );
42 | }
43 |
44 | export default SignupForm;
45 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/pages/Dashboard.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import axios from 'axios';
3 | function Dashboard(props) {
4 | const [user, setUser] = useState({});
5 | const [loading, setLoading] = useState(true);
6 | function onLogout() {
7 | localStorage.removeItem('user');
8 | window.location.href = '/';
9 | }
10 | useEffect(() => {
11 | async function fetchUser() {
12 | const user = localStorage.getItem('user');
13 | if (!user) {
14 | // Redirect to login page if token is not present
15 | props.history.push('/login');
16 | return;
17 | }
18 |
19 |
20 | try {
21 | // Send a request to the protected route
22 | const userData = JSON.parse(user);
23 |
24 | setUser(userData);
25 | setLoading(false);
26 | } catch (err) {
27 | // Redirect to login page if server responds with error
28 | props.history.push('/login');
29 | }
30 | }
31 | fetchUser();
32 | }, [props.history]);
33 |
34 | if (loading) {
35 | return Login first
;
36 | }
37 |
38 | return (
39 |
40 |
Username: {user.username}
41 | Email: {user.email}
42 |
43 | Logout
44 |
45 | );
46 | }
47 |
48 | export default Dashboard;
49 |
--------------------------------------------------------------------------------
/movie-watchlist/public/vite.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/realmate/server.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import dotenv from "dotenv";
3 | import bodyParser from "body-parser";
4 | import mongoose from "mongoose";
5 | import cors from "cors";
6 | import { usersRoute } from "./routes/user.js";
7 |
8 | const PORT = process.env.PORT || 5000
9 | const app = express();
10 | dotenv.config()
11 |
12 | // middleware
13 | app.use(cors())
14 | app.use(bodyParser.json());
15 |
16 | // connect mongoose
17 | const options = {
18 | useNewUrlParser: true,
19 | useUnifiedTopology: true
20 | }
21 | mongoose.connect(process.env.MONGO_URI, options)
22 | .then(() => {
23 | console.log('Connected to MongoDB');
24 | })
25 | .catch((err) => {
26 | console.log('Error connecting to MongoDB', err);
27 | });
28 |
29 |
30 | // Status
31 | app.get("/", (req, res) => res.status(200).json({
32 | message: "Running",
33 | server: "Alive",
34 | statusCode: 200
35 | }))
36 |
37 |
38 |
39 | // Users Route
40 | app.use("/api/users", usersRoute)
41 |
42 | // Incorrect route message
43 | app.get('*', (req, res) => {
44 | const { method, originalUrl, body } = req;
45 | const response = {
46 | method,
47 | url: originalUrl,
48 | data: {
49 | message: "Endpoint Not correct",
50 | server: "Alive",
51 | statusCode: 404
52 | },
53 | };
54 | res.json(response);
55 | });
56 |
57 |
58 | app.listen(PORT, () => console.log("Running at port ", PORT))
59 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/public/vite.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/public/vite.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/components/Register.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | const Register = ({ setUsername, setEmail, setPassword, username, email, password, handleSubmit }) => {
3 |
4 | return (
5 |
6 |
Register
7 |
26 |
27 | )
28 | }
29 |
30 | export default Register
--------------------------------------------------------------------------------
/task-manager/passport.js:
--------------------------------------------------------------------------------
1 | const passport = require('passport');
2 | const User = require('./models/User');
3 | const JwtStrategy = require('passport-jwt').Strategy;
4 | const ExtractJwt = require('passport-jwt').ExtractJwt;
5 | const LocalStrategy = require('passport-local').Strategy;
6 |
7 | // Use the LocalStrategy for authenticating users with a username and password
8 | passport.use(new LocalStrategy({
9 | usernameField: 'email',
10 | passwordField: 'password'
11 | },
12 | async (email, password, done) => {
13 | try {
14 | const user = await User.findOne({ email });
15 | if (!user) {
16 | return done(null, false, { message: 'Invalid credentials' });
17 | }
18 |
19 | const isMatch = await user.comparePassword(password);
20 | if (!isMatch) {
21 | return done(null, false, { message: 'Invalid credentials' });
22 | }
23 |
24 | return done(null, user);
25 | } catch (err) {
26 | return done(err);
27 | }
28 | }
29 | ));
30 |
31 | // Configure options for the JWT authentication strategy
32 | const options = {
33 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
34 | secretOrKey: process.env.JWT_SECRET
35 | };
36 |
37 | // Use the JWT authentication strategy
38 | passport.use(new JwtStrategy(options, async (payload, done) => {
39 | try {
40 | const user = await User.findById(payload.id);
41 | if (user) {
42 | return done(null, user);
43 | } else {
44 | return done(null, false);
45 | }
46 | } catch (err) {
47 | return done(err, false);
48 | }
49 | }));
50 |
51 | module.exports = passport;
52 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Use this section to tell people about which versions of your project are
6 | currently being supported with security updates.
7 |
8 | | Version | Supported |
9 | | ------- | ------------------ |
10 | | 5.1.x | :white_check_mark: |
11 | | 5.0.x | :x: |
12 | | 4.0.x | :white_check_mark: |
13 | | < 4.0 | :x: |
14 |
15 | ## Reporting a Vulnerability
16 |
17 | If you discover a security issue in this repository, please report it by sending an email to devvsakib@gmail.com. Please do not submit an issue on GitHub as it may contain sensitive information.
18 |
19 | We take all security issues seriously and will respond to your report within 24 hours. We will work with you to identify and remediate the issue as quickly as possible.
20 |
21 |
22 | ## Supported Versions
23 |
24 | This repository is under active development, and only the latest version is currently supported with security updates. We strongly recommend that you keep your copy of the repository up-to-date with the latest version to ensure that you have access to the latest security patches and fixes.
25 |
26 |
27 | ## Vulnerability Disclosure Policy
28 |
29 | Once we have received a report of a vulnerability, we will confirm the issue and investigate it thoroughly. If the vulnerability is verified, we will immediately work on a patch and release it as soon as possible.
30 |
31 | After we have resolved the issue, we will publish a security advisory on our website and/or GitHub repository. We will also inform affected users of the vulnerability and the steps they should take to update their software.
32 |
33 | We encourage all users to keep their software up-to-date with the latest security patches and fixes. Thank you for helping us keep our software secure!
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/pages/SavedRecipes.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react'
2 | import axios from 'axios'
3 | import useGetUserId from '../hooks/useGetUserId';
4 |
5 | const SavedRecipes = () => {
6 | const [savedRecipes, setSavedRecipes] = useState([]);
7 | const userId = useGetUserId();
8 |
9 | useEffect(() => {
10 | const fetchSavedRecipes = async () => {
11 | try {
12 | const res = await axios.get(`http://localhost:5000/recipes/savedRecipes/${userId}`)
13 | setSavedRecipes(res.data.savedRecipes)
14 | } catch (error) {
15 | console.log(error.message);
16 | }
17 | }
18 | fetchSavedRecipes()
19 | }, [])
20 |
21 |
22 | return (
23 |
24 |
Saved Recipes
25 |
26 | {
27 | !savedRecipes ? "Noting is here..." :
28 | savedRecipes?.map(({ imageUrl, cookTime, name, instructions, ingredients, _id }, unique) => (
29 |
30 |
31 |
32 |
Name: {name}
33 |
Ingredients: {ingredients.map((e, id) => (
34 |
{e}
35 | ))}
36 |
Instructions: {instructions.length > 100 ? instructions.slice(0, 70) + "..." : instructions}
37 |
Cookign Time: {cookTime}
38 |
39 |
40 | ))
41 | }
42 |
43 |
44 | )
45 | }
46 |
47 | export default SavedRecipes
--------------------------------------------------------------------------------
/movie-watchlist/src/components/Search/Search.jsx:
--------------------------------------------------------------------------------
1 | import { Link } from 'react-router-dom';
2 | const Search = ({ searchValue, setSearchValue, searchDrama, searchById, searchValueId, setSearchValueId }) => {
3 |
4 | const path = window.location.pathname.slice(1);
5 |
6 | return (
7 |
8 |
9 |
10 |
setSearchValue(e.target.value)} />
13 |
14 |
15 |
16 |
17 | {/* {
18 | path === "list" &&
19 |
setSearchValueId(e.target.value)} />
23 |
24 |
25 |
26 |
27 | } */}
28 |
29 |
30 | )
31 | }
32 |
33 | export default Search
--------------------------------------------------------------------------------
/recipe ap with auth/backend/routes/recipes.js:
--------------------------------------------------------------------------------
1 | import express from 'express';
2 | import RecipesModel from "../models/Recipes.js"
3 | import UserModel from '../models/User.js';
4 | import auth from './users.js';
5 |
6 | const router = express.Router();
7 |
8 | router.post('/', auth, async (req, res) => {
9 | const recipe = new RecipesModel(req.body)
10 | try {
11 | const response = await recipe.save()
12 | res.json(response)
13 | } catch (error) {
14 | res.json({ nessage: error.message })
15 | }
16 | })
17 | router.get('/', async (req, res) => {
18 | try {
19 | const response = await RecipesModel.find({})
20 |
21 | res.json(response)
22 |
23 | } catch (error) {
24 | res.json({ nessage: error.message })
25 | }
26 | })
27 |
28 | router.put('/', auth, async (req, res) => {
29 | try {
30 | const recipe = await RecipesModel.findById(req.body.recipeId)
31 | const user = await UserModel.findById(req.body.userId)
32 | user.savedRecipes.push(recipe);
33 | await user.save()
34 | res.json({ savedRecipes: user?.savedRecipes })
35 | } catch (error) {
36 | res.json({ nessage: error.message })
37 | }
38 | })
39 |
40 | router.get("/savedRecipes/id/:userId", async (req, res) => {
41 | try {
42 | const user = await UserModel.findById(req.params.userId)
43 | res.json({ savedRecipes: user.savedRecipes })
44 | } catch (error) {
45 | res.json({ nessage: error.message })
46 | }
47 | })
48 |
49 | router.get("/savedRecipes/:userId", async (req, res) => {
50 | try {
51 | const user = await UserModel.findById(req.params.userId)
52 | const savedRecipes = await RecipesModel.find({
53 | _id: { $in: user.savedRecipes }
54 | })
55 | res.json({ savedRecipes })
56 | } catch (error) {
57 | res.json({ nessage: error.message })
58 | }
59 | })
60 |
61 | export { router as recipesRouter }
--------------------------------------------------------------------------------
/movie-watchlist/src/components/Header/Header.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Link } from 'react-router-dom'
3 |
4 | const Header = () => {
5 | return (
6 |
7 |
8 |
9 |
KDRAMA Watch
10 |
11 |
12 |
13 | Home
14 |
15 |
16 |
17 | List
18 |
19 |
20 |
21 | {/*
22 |
23 |
*/}
24 |
25 |
26 |
27 |
28 |
29 |
30 |
40 |
41 |
42 |
43 | )
44 | }
45 |
46 | export default Header
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/Header/Header.jsx:
--------------------------------------------------------------------------------
1 | import { Link } from "react-router-dom";
2 | import axios from 'axios';
3 |
4 | const Header = ({ setIsAuthenticated }) => {
5 | const loggedIn = localStorage.getItem('token');
6 | function onLogout() {
7 | localStorage.removeItem('token');
8 | window.location.href = '/';
9 | }
10 | const handleLogout = async () => {
11 | try {
12 | await axios.post('http://localhost:5000/users/logout');
13 | if (response.status === 200) {
14 | localStorage.removeItem('token');
15 | setAuthenticated(false);
16 | history.push('/login');
17 | }
18 | } catch (error) {
19 | console.log(error);
20 | }
21 | };
22 | return (
23 |
24 |
29 |
32 |
33 | {loggedIn ? (
34 |
Login
35 | ) : (
36 |
Logout
37 | )}
38 |
39 |
40 |
41 |
42 |
43 |
44 | );
45 | }
46 | export default Header;
--------------------------------------------------------------------------------
/recipe ap with auth/backend/routes/users.js:
--------------------------------------------------------------------------------
1 | import express from 'express'
2 | import jwt from "jsonwebtoken"
3 | import bcrypt from "bcrypt"
4 | import UserModel from '../models/User.js';
5 |
6 | const router = express.Router();
7 |
8 | router.post('/register', async (req, res) => {
9 | const { username, password, email } = req.body;
10 | const user = await UserModel.findOne({ username });
11 | const useremail = await UserModel.findOne({ email });
12 |
13 | if (user || useremail) {
14 | return res.json({
15 | message: "User Already Exits"
16 | })
17 | }
18 | const hashP = await bcrypt.hash(password, 10);
19 |
20 | const newUser = await new UserModel({ username, password: hashP, email })
21 | newUser.save()
22 | res.json({
23 | message: "Register Success!",
24 | username: username
25 | })
26 |
27 | })
28 |
29 | router.post('/signin', async (req, res) => {
30 | const { username, password } = req.body;
31 |
32 | const user = await UserModel.findOne({ username });
33 |
34 | if (!user) {
35 | return res.json({
36 | message: "User Doesn't Exits"
37 | })
38 | }
39 |
40 | const isPasswordValid = await bcrypt.compare(password, user.password);
41 |
42 | if (!isPasswordValid) {
43 | return res.json({
44 | message: "Username or Password not currect!"
45 | })
46 | }
47 |
48 | const token = jwt.sign({ id: user._id }, "secret");
49 |
50 | res.json({ token, userId: user._id, username: user.username })
51 |
52 |
53 | })
54 |
55 | export { router as userRouter };
56 |
57 | const auth = async (req, res, next) => {
58 | const token = req.headers.authorization;
59 | if (token) {
60 |
61 | jwt.verify(token, "secret", (err) => {
62 | if(err) return res.json({
63 | message: "Please Login!"
64 | })
65 | next()
66 | })
67 | }else{
68 | res.sendStatus(401)
69 | }
70 |
71 | }
72 |
73 | export default auth;
--------------------------------------------------------------------------------
/movie-watchlist/src/components/Watched/WatchedCard.jsx:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 | import { useState } from "react";
3 | import GetMovieList from "./GetMovieList"
4 |
5 | const WatchedCard = () => {
6 | // const [name, setName] = useState('');
7 | const { watched, deleteAction } = GetMovieList();
8 |
9 | return (
10 | <>
11 | {
12 | watched.length == 0 ? No movies in watched list : watched && watched.map((movie, idx) => (
13 |
14 |
15 |
16 | {movie?.name}
17 |
18 |
19 |
20 |
21 |
22 |
{movie?.name}
23 |
{movie.description}
24 |
25 | Remove
28 |
29 |
30 |
31 |
32 |
33 | ))
34 | }
35 | >
36 | )
37 | }
38 |
39 | export default WatchedCard
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/pages/Auth.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react'
2 | import axios from 'axios'
3 | import Login from '../components/Login'
4 | import Register from '../components/Register'
5 | import { useCookies } from 'react-cookie'
6 | import { useNavigate } from "react-router-dom"
7 |
8 | const Auth = () => {
9 | const [isLogin, setIsLogin] = useState(false)
10 | const [username, setUsername] = useState('')
11 | const [email, setEmail] = useState('')
12 | const [password, setPassword] = useState('')
13 | const [_, setCookies] = useCookies(["access_token"])
14 |
15 |
16 | const navigate = useNavigate();
17 |
18 | const handleSubmit = async (e) => {
19 | e.preventDefault();
20 | try {
21 | await axios.post("http://localhost:5000/auth/register", { username, password, email })
22 | alert("Registrations Success! Please login")
23 | } catch (error) {
24 | console.log(error.message);
25 | }
26 | }
27 | const handleLogin = async (e) => {
28 | e.preventDefault();
29 | try {
30 | const response = await axios.post("http://localhost:5000/auth/signin", { username, password })
31 | setCookies("access_token", response.data.token)
32 | window.localStorage.setItem("userId", response.data.userId)
33 | window.localStorage.setItem("username", response.data.username)
34 | navigate('/')
35 | } catch (error) {
36 | console.log(error.message);
37 | }
38 | }
39 |
40 | return (
41 |
42 |
49 |
:
50 |
59 |
60 | )
61 | }
62 |
63 | export default Auth
--------------------------------------------------------------------------------
/task-manager/routes/users.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const User = require('../models/User');
4 | const passport = require('passport');
5 | const bcrypt = require('bcrypt');
6 | require('../passport');
7 | const jwt = require('jsonwebtoken');
8 |
9 | // Get all users
10 | router.get('/', async (req, res) => {
11 | try {
12 | const users = await User.find({});
13 | res.json(users);
14 | } catch (err) {
15 | console.error(err);
16 | res.status(500).json({ 'Server error': err.message });
17 | }
18 | });
19 |
20 | // Signup a new user
21 | router.post('/signup', (req, res) => {
22 | try {
23 | const { username, email, password } = req.body;
24 | const user = new User({ username, email, password });
25 | User.register(user, password.toString(), (err) => {
26 | if (err) {
27 | console.error(err);
28 | res.sendStatus(500);
29 | } else {
30 | passport.authenticate('local')(req, res, () => {
31 | res.sendStatus(200);
32 | });
33 | }
34 | });
35 | } catch (error) {
36 | res.status(400).json({ message: err.message });
37 | }
38 | });
39 |
40 | // Login
41 | // Login
42 | router.post('/login', async (req, res, next) => {
43 | passport.authenticate('local', { session: false }, async (err, user, info) => {
44 | if (err) return next(err);
45 | if (!user) return res.status(401).json({ message: 'Invalid credentials' });
46 |
47 | try {
48 | const match = await user.comparePassword(req.body.password);
49 |
50 | if (!match) {
51 | return res.status(401).json({ message: 'Invalid credentials' });
52 | }
53 |
54 | const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
55 | return res.json({ token });
56 | } catch (err) {
57 | return next(err);
58 | }
59 | })(req, res, next);
60 | });
61 |
62 |
63 | // Logout
64 | router.get('/logout', (req, res) => {
65 | req.logout();
66 | res.json({ message: 'Logout successful' });
67 | });
68 |
69 | module.exports = router;
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/components/Header.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { useState, useEffect } from 'react'
3 | import { Link } from 'react-router-dom'
4 | import { useCookies } from "react-cookie"
5 | import { useNavigate } from "react-router-dom"
6 |
7 | const Header = () => {
8 | const [cookie, setCookie] = useCookies(['access_token']);
9 | const navigate = useNavigate();
10 |
11 | const logOut = () => {
12 | setCookie("access_token", "")
13 | window.localStorage.removeItem("userId")
14 | window.localStorage.removeItem("username")
15 | navigate("/auth")
16 | }
17 | return (
18 |
43 | )
44 | }
45 |
46 | export default Header
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/pages/Home.jsx:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from 'react';
2 | import React from 'react'
3 | import Gallary from '../Cards/Gallary'
4 | import ReciepeCard from '../Cards/ReciepeCard'
5 | import SearchInput from '../Search/SearchInput'
6 | const Home = () => {
7 | const [recipes, setRecipes] = useState([]);
8 | return (
9 |
10 |
11 |
12 |
13 |
Hello there
14 |
18 |
19 |
20 |
21 |
22 |
Trending
23 |
26 |
27 |
28 |
29 | Category
30 | Vegetarian
31 | Gluten-free
32 | Desserts
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | Join
41 |
42 |
43 |
44 |
Add your reciepe
45 |
Rerum reiciendis beatae tenetur excepturi
46 |
47 |
48 |
49 |
50 |
51 | )
52 | }
53 |
54 | export default Home
--------------------------------------------------------------------------------
/movie-watchlist/src/components/Watched/GetMovieList.jsx:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from 'react';
2 | import axios from 'axios';
3 | const GetMovieList = () => {
4 | const [watched, setWatched] = useState([]);
5 | const [watchlist, setWatchlist] = useState([]);
6 | const [done, setDone] = useState(false);
7 | const [update, setUpdate] = useState('');
8 | console.log(update);
9 | useEffect(() => {
10 | fetch('http://localhost:5000/watched')
11 | .then(res => {
12 | if (!res.ok) {
13 | throw Error('Could not fetch the data for that resource');
14 | }
15 | return res.json();
16 | })
17 | .then(data => {
18 | setWatched(data);
19 | })
20 | .catch(err => {
21 | console.log(err.message);
22 | })
23 | }, [done]);
24 | useEffect(() => {
25 | fetch('http://localhost:5000/watchlist')
26 | .then(res => {
27 | if (!res.ok) {
28 | throw Error('Could not fetch the data for that resource');
29 | }
30 | return res.json();
31 | })
32 | .then(data => {
33 | setWatchlist(data);
34 | })
35 | .catch(err => {
36 | console.log(err.message);
37 | })
38 | }, [watched, done]);
39 |
40 | const deleteAction = (e) => {
41 | try {
42 | axios.delete(`http://localhost:5000/${e.target.value}`)
43 | .catch(err => console.log(err));
44 | // hide the card
45 | e.target.parentElement.parentElement.parentElement.parentElement.parentElement.style.display = 'none';
46 | } catch (error) {
47 | console.log(error);
48 | }
49 | }
50 |
51 | useEffect(() => {
52 | const updateAction = () => {
53 | try {
54 | axios.patch(`http://localhost:5000/update`, { name: update })
55 | .catch(err => console.log(err));
56 | setDone(false);
57 | }
58 | catch (err) {
59 | console.log(err);
60 | }
61 | }
62 | updateAction();
63 | }, [done]);
64 |
65 |
66 | return { watched, watchlist, setDone, setUpdate, deleteAction };
67 | }
68 |
69 | export default GetMovieList;
--------------------------------------------------------------------------------
/movie-watchlist/src/components/Watchlist/WatchlistCard.jsx:
--------------------------------------------------------------------------------
1 | import GetMovieList from "../Watched/GetMovieList"
2 | import { useState } from "react";
3 | const WatchlistCard = () => {
4 | const { watchlist, deleteAction, setDone, setUpdate } = GetMovieList();
5 | return (
6 | <>
7 | {
8 | watchlist.length < 1 ? No movies in watching list : watchlist && watchlist.map((movie, idx) => (
9 |
10 |
11 |
12 | {movie?.name}
13 |
14 |
15 |
16 |
17 |
18 |
{movie?.name}
19 |
{movie.description.length > 100 ? movie.description.slice(0, 120) : movie.description + "..."}
20 |
21 | Remove
24 |
25 | {setDone(true); setUpdate(movie.name)}}
26 | value={movie.name}
27 | >Watched
28 |
29 |
30 |
31 |
32 |
33 |
34 | ))
35 | }
36 | >
37 | )
38 | }
39 |
40 | export default WatchlistCard
--------------------------------------------------------------------------------
/movie-watchlist/backend/routes/watched.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const { send } = require("vite");
3 | const router = express.Router();
4 | const Watchedlist = require("../models/Watchlist")
5 |
6 | router.get("/", async (req, res) => {
7 | const movie = await Watchedlist.find({})
8 | try {
9 | res.json(movie)
10 | console.log(movie);
11 | } catch (error) {
12 | console.log(error);
13 | }
14 | })
15 |
16 |
17 | router.post("/add", async (req, res) => {
18 | const { name, watched, thumbnail, description } = req.body
19 |
20 | try {
21 | const data = new Watchedlist({ name, thumbnail, description, watched })
22 | const newMovie = await data.save();
23 | res.json(newMovie)
24 | } catch (error) {
25 | console.log("Something is wrong. Please try again");
26 | res.status(401).json(error.message)
27 | }
28 |
29 | })
30 |
31 | router.get("/watched", async (req, res) => {
32 | const movie = await Watchedlist.find({ watched: true })
33 | try {
34 | res.json(movie)
35 | console.log(movie);
36 | } catch (error) {
37 | console.log(error);
38 | }
39 | })
40 |
41 | router.get("/watchlist", async (req, res) => {
42 | const movie = await Watchedlist.find({ watched: false })
43 | try {
44 | res.json(movie)
45 | console.log(movie);
46 | } catch (error) {
47 | console.log(error);
48 | }
49 | })
50 |
51 |
52 | router.get("/:name", async (req, res) => {
53 | const movie = await Watchedlist.findOne({ name: req.params.name })
54 | try {
55 | movie ? res.json(movie) : res.json({ message: "Movie not found" })
56 |
57 | } catch (error) {
58 | res.json({ message: error })
59 | }
60 |
61 | })
62 |
63 | router.delete("/:name", async (req, res) => {
64 | const movie = await Watchedlist.findOneAndDelete({ name: req.params.name })
65 | try {
66 | // delete movie
67 |
68 | movie ? res.json(movie) : res.json({ message: "Movie not found" })
69 |
70 | } catch (error) {
71 | res.json({ message: error })
72 | }
73 |
74 | })
75 |
76 | router.patch("/update", async (req, res) => {
77 | const watched = req.body.watched
78 | try {
79 | const movie = await Watchedlist.findOneAndUpdate({ name: req.body.name }, { watched: true })
80 | const newMovie = await movie.save();
81 | res.json(newMovie)
82 | } catch (error) {
83 | res.json({ message: error })
84 | }
85 | })
86 |
87 |
88 | module.exports = router
--------------------------------------------------------------------------------
/task-manager/routes/todos.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const Todo = require('../models/Todo');
4 | // add user authentication
5 | const passport = require('passport')
6 | require('../passport');
7 |
8 |
9 |
10 | async function getTodo(req, res, next) {
11 | let todo;
12 | try {
13 | todo = await Todo.findById(req.params.id);
14 | if (todo == null) {
15 | return res.status(404).json({ message: 'Cannot find todo' });
16 | }
17 | } catch (err) {
18 | return res.status(500).json({ message: err.message });
19 | }
20 |
21 | res.todo = todo;
22 | next();
23 | }
24 |
25 | router.get('/todos', passport.authenticate('jwt', { session: false }), async (req, res) => {
26 | try {
27 | const todos = await Todo.find({});
28 | res.json(todos);
29 | } catch (err) {
30 | console.error(err);
31 | res.status(500).json({ 'Server error': err.message });
32 | }
33 | });
34 |
35 | router.post('/add', passport.authenticate('jwt', { session: false }), async (req, res) => {
36 | try {
37 | const todo = new Todo({
38 | title: req.body.title,
39 | description: req.body.description,
40 | completed: req.body.completed,
41 | user: req.user._id // associate the todo with the logged-in user
42 | });
43 | const newTodo = await todo.save();
44 | res.status(201).json(newTodo);
45 | } catch (err) {
46 | res.status(400).json({ message: err.message });
47 | }
48 | });
49 |
50 | router.get('/:id', passport.authenticate('jwt', { session: false }), getTodo, (req, res) => {
51 | res.json(res.todo);
52 | });
53 |
54 | router.patch('/:id', passport.authenticate('jwt', { session: false }), getTodo, async (req, res) => {
55 | if (req.body.title != null) {
56 | res.todo.title = req.body.title;
57 | }
58 |
59 | if (req.body.description != null) {
60 | res.todo.description = req.body.description;
61 | }
62 |
63 | if (req.body.completed != null) {
64 | res.todo.completed = req.body.completed;
65 | }
66 |
67 | try {
68 | const updatedTodo = await res.todo.save();
69 | res.json(updatedTodo);
70 | } catch (err) {
71 | res.status(400).json({ message: err.message });
72 | }
73 | });
74 | router.delete('/:id', getTodo, async (req, res) => {
75 | try {
76 | await res.todo.remove();
77 | res.json({ message: 'Todo deleted' });
78 | } catch (err) {
79 | res.status(500).json({ message: err.message });
80 | }
81 | });
82 |
83 |
84 |
85 |
86 |
87 | module.exports = router;
88 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PreBackendCode
2 |
3 | PreBackendCode is a JavaScript repository that provides backend functionality for developers who want to focus on API development. It includes all necessary backend code, allowing developers to simply copy files from the repository and avoid writing any backend code themselves.
4 |
5 | ## Installation
6 | To use PreBackendCode, simply clone the repository to your local machine:
7 |
8 | ```bash
9 | git clone https://github.com/devvsakib/PreBackendCode.git
10 | ```
11 |
12 | ## Usage
13 |
14 | To use the backend code in this repository, simply clone or download the repository and copy the relevant files into your own project directory. You can then modify the code as needed to suit your application's requirements.
15 |
16 |
17 | ## Features
18 |
19 | This repository contains backend code for the following features:
20 |
21 | - API development
22 | - Authentication
23 | - Database integration
24 |
25 |
26 | ## Technologies Used
27 |
28 | The following technologies were used in the development of this backend code:
29 |
30 | - Node.js
31 | - Express.js
32 | - MongoDB
33 |
34 |
35 | ## Getting Started
36 |
37 | To get started with this repository, you will need to have Node.js and MongoDB installed on your machine. Once you have those installed, follow these steps:
38 | 1. Clone or download the repository to your local machine.
39 | 2. Run `npm install` to install the required dependencies.
40 | 3. Configure the `.env` file with your database connection details and any other required configuration variables.
41 | 4. Run `npm run dev` to start the server.
42 |
43 | ## Getting Help
44 |
45 | If you encounter any issues while using PreBackendCode, please feel free to open an issue on the repository or contact the repository owner.
46 |
47 | ## Conclusion
48 |
49 | PreBackendCode is a useful repository for developers who want to focus on API development and avoid writing backend code themselves. With its pre-written backend code and helpful documentation, developers can easily use this repository to create powerful APIs.
50 |
51 |
52 | ## Contributing
53 |
54 | Contributions to this repository are welcome. If you would like to contribute, please follow these steps:
55 |
56 | 1. Fork the repository to your own GitHub account.
57 | 2. Clone the repository to your local machine.
58 | 3. Create a new branch for your changes.
59 | 4. Make your changes and test them thoroughly.
60 | 5. Commit your changes and push them to your forked repository.
61 | 6. Submit a pull request to have your changes reviewed and merged into the main branch.
62 |
63 |
64 | ## License
65 |
66 | This repository is licensed under the MIT License. You are free to use, modify, and distribute the code as you see fit. See the `LICENSE` file for more details.
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/pages/Home.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react'
2 | import axios from 'axios'
3 | import useGetUserId from '../hooks/useGetUserId';
4 | import { useCookies } from 'react-cookie'
5 |
6 | const Home = () => {
7 | const [recipes, setRecipes] = useState([]);
8 | const [savedRecipes, setSavedRecipes] = useState([]);
9 | const userId = useGetUserId();
10 | const [cookies, _] = useCookies(["access_token"])
11 |
12 | useEffect(() => {
13 |
14 | const fetchRecipes = async () => {
15 | try {
16 | const res = await axios.get("http://localhost:5000/recipes")
17 | setRecipes(res.data)
18 | } catch (error) {
19 | console.log(error.message);
20 | }
21 | }
22 | const fetchSavedRecipes = async () => {
23 | try {
24 | const res = await axios.get(`http://localhost:5000/recipes/savedRecipes/id/${userId}`)
25 | setSavedRecipes(res.data.savedRecipes)
26 | } catch (error) {
27 | console.log(error.message);
28 | }
29 | }
30 | fetchRecipes();
31 | fetchSavedRecipes()
32 | }, [])
33 |
34 | const saveRecipe = async (recipeId) => {
35 | try {
36 | const res = await axios.put("http://localhost:5000/recipes", {
37 | recipeId,
38 | userId
39 | }, {
40 | headers: { authorization: cookies.access_token }
41 | })
42 | setSavedRecipes(res.data.savedRecipes)
43 | } catch (error) {
44 | console.log(error.message);
45 | }
46 | }
47 |
48 |
49 | const isRecipeSaved = (id) => savedRecipes.includes(id);
50 |
51 | return (
52 |
53 |
54 | {
55 | recipes?.map(({ imageUrl, cookTime, name, instructions, ingredients, _id }, unique) => (
56 |
57 |
58 |
59 |
Name: {name}
60 |
Ingredients: {ingredients.map((e, id) => (
61 |
{e}
62 | ))}
63 |
Instructions: {instructions.length > 100 ? instructions.slice(0, 70) + "..." : instructions}
64 |
Cookign Time: {cookTime}
65 | {
66 | userId ?
67 | (
68 |
saveRecipe(_id)}>
69 | {savedRecipes && isRecipeSaved(_id) ? "Saved" : "Save"}
70 |
71 | ) : "Login To Save"
72 | }
73 |
74 |
75 |
76 | ))
77 | }
78 |
79 |
80 | )
81 | }
82 |
83 | export default Home
--------------------------------------------------------------------------------
/movie-watchlist/src/pages/Home.jsx:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from 'react'
2 | import MovieCard from '../components/Card/MovieCard'
3 | import Search from '../components/Search/Search'
4 |
5 | const Home = () => {
6 | const [dramas, setDramas] = useState([])
7 | const [loading, setLoading] = useState(true)
8 | const [addDrama, setAddDrama] = useState([])
9 | const [searchValue, setSearchValue] = useState('')
10 | const [dramaById, setDramaById] = useState([])
11 | const [searchValueId, setSearchValueId] = useState('')
12 |
13 |
14 | // searchValue ? searchValueId('') : searchValueId(searchValue)
15 | useEffect(() => {
16 | setSearchValueId('')
17 | }, [searchValue])
18 |
19 | const searchDrama = () => {
20 | setLoading(true)
21 | const apiUrl = `https://mydramalist-scrape-api.vercel.app/search/q/${searchValue === '' ? 'goblin' : searchValue}`
22 | fetch(apiUrl)
23 | .then(res => res.json())
24 | .then(data => {
25 | setDramas(data.results.dramas)
26 | setLoading(false)
27 |
28 | })
29 | setDramas([])
30 | }
31 |
32 | useEffect(() => {
33 | searchDrama()
34 | }, [searchValue])
35 |
36 | const addDramas = () => {
37 | setAddDrama([...addDrama, dramas])
38 | localStorage.setItem('drama', JSON.stringify(addDrama))
39 |
40 | }
41 |
42 | const searchById = () => {
43 | fetch(`http://localhost:5000/${searchValueId}`)
44 | .then(res => res.json())
45 | .then(data => {
46 | setDramaById(data)
47 | })
48 | }
49 | return (
50 |
51 |
59 |
60 | {
61 | loading ?
62 |
63 |
: (dramas && !searchValueId ? dramas.map((drama, idx) => (
64 | drama.title !== undefined ?
65 |
: "No Drama"
71 | )) : dramaById && searchValueId ?
{dramaById.name} : "No Drama")
72 | }
73 |
74 |
75 | )
76 | }
77 |
78 | export default Home
--------------------------------------------------------------------------------
/.github/workflows/codeql.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ "main" ]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [ "main" ]
20 | schedule:
21 | - cron: '20 3 * * 5'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: [ 'javascript' ]
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37 | # Use only 'java' to analyze code written in Java, Kotlin or both
38 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
39 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
40 |
41 | steps:
42 | - name: Checkout repository
43 | uses: actions/checkout@v3
44 |
45 | # Initializes the CodeQL tools for scanning.
46 | - name: Initialize CodeQL
47 | uses: github/codeql-action/init@v2
48 | with:
49 | languages: ${{ matrix.language }}
50 | # If you wish to specify custom queries, you can do so here or in a config file.
51 | # By default, queries listed here will override any specified in a config file.
52 | # Prefix the list here with "+" to use these queries and those in the config file.
53 |
54 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
55 | # queries: security-extended,security-and-quality
56 |
57 |
58 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
59 | # If this step fails, then you should remove it and run the build manually (see below)
60 | - name: Autobuild
61 | uses: github/codeql-action/autobuild@v2
62 |
63 | # ℹ️ Command-line programs to run using the OS shell.
64 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
65 |
66 | # If the Autobuild fails above, remove it and uncomment the following three lines.
67 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
68 |
69 | # - run: |
70 | # echo "Run, Build Application using script"
71 | # ./location_of_script_within_repo/buildscript.sh
72 |
73 | - name: Perform CodeQL Analysis
74 | uses: github/codeql-action/analyze@v2
75 | with:
76 | category: "/language:${{matrix.language}}"
77 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/pages/CreateRecipe.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react'
2 | import axios from "axios"
3 | import useGetUserId from "../hooks/useGetUserId"
4 | import { useNavigate } from 'react-router-dom'
5 | import { useCookies } from 'react-cookie'
6 |
7 | const CreateRecipe = () => {
8 | const user = useGetUserId();
9 | const navigate = useNavigate();
10 | const [cookies, _] = useCookies(["access_token"])
11 | const [recipe, setRecipe] = useState({
12 | name: '',
13 | ingredients: [],
14 | instructions: '',
15 | imageUrl: '',
16 | cookTime: 0,
17 | owner: user
18 | })
19 | const handleChange = e => {
20 | const { name, value } = e.target;
21 | setRecipe({ ...recipe, [name]: value })
22 | }
23 | const handleIngd = (e, idx) => {
24 | const { value } = e.target;
25 | const ingredients = recipe.ingredients;
26 | ingredients[idx] = value
27 | setRecipe({ ...recipe, ingredients })
28 | }
29 |
30 | const addIngedient = () => {
31 | setRecipe({ ...recipe, ingredients: [...recipe.ingredients, ""] })
32 | }
33 |
34 | const onCreateRecipe = async (e) => {
35 | e.preventDefault();
36 | try {
37 | await axios.post("http://localhost:5000/recipes", recipe, {
38 | headers: { authorization: cookies.access_token }
39 | })
40 | console.log("Success!");
41 | navigate("/")
42 | } catch (error) {
43 | console.log(error.message);
44 | }
45 | }
46 |
47 | return (
48 |
49 |
Create Recipe
50 |
85 |
86 | )
87 | }
88 |
89 | export default CreateRecipe
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/components/Form/LoginForm.jsx:
--------------------------------------------------------------------------------
1 | import { Link } from 'react-router-dom';
2 | import { useState } from 'react';
3 | import axios from 'axios';
4 |
5 | function LoginForm() {
6 | const [email, setEmail] = useState('');
7 | const [password, setPassword] = useState('');
8 | const handleSubmit = async (e) => {
9 | e.preventDefault();
10 |
11 | try {
12 | // Send a request to the login endpoint with the email and password
13 | const res = await axios.post('http://localhost:5000/users/login', {
14 | email,
15 | password,
16 | });
17 |
18 | // Store the JWT token in local storage
19 | localStorage.setItem('token', res.data.token);
20 | console.log('Token set:', res.data.token);
21 |
22 | // Redirect the user to the home page
23 | if (res.status === 200) {
24 | console.log('Login successful');
25 | const response = await axios.get(`http://localhost:5000/users/`);
26 | // const userData = await response.json();
27 | // console.log(userData);
28 | response.data.map((user) => {
29 | if (user.email === email) {
30 | localStorage.setItem('user', JSON.stringify(user));
31 | console.log('User set:', user);
32 | }
33 | });
34 | window.location = '/dashboard';
35 | }
36 | } catch (err) {
37 | console.error(err);
38 | }
39 | };
40 |
41 | console.log(email, password)
42 | return (
43 |
44 |
45 |
73 |
74 | ©2020 Acme Corp. All rights reserved.
75 |
76 |
77 |
78 | );
79 | }
80 |
81 | export default LoginForm;
82 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb/routes/posts.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import Post from "../models/Post.js";
3 | import jwt from "jsonwebtoken"
4 |
5 | const router = express.Router();
6 |
7 | // get all blogs
8 | router.get("/", async (req, res) => {
9 | const allPosts = await Post.find();
10 | allPosts.length ? res.status(200).json(allPosts) : res.status(404).json({ message: "No posts found" });
11 | })
12 |
13 | // get single post by id
14 | router.get("/post/:id", async (req, res) => {
15 | try {
16 | const { id } = req.params;
17 | const findPost = await Post.findById(id);
18 | return res.status(200).json(findPost);
19 | } catch (error) {
20 | return res.status(404).json({
21 | Message: "Post Not found"
22 | });
23 | }
24 | });
25 |
26 | // post new blog
27 | router.post("/", async (req, res) => {
28 | const { content } = req.body
29 | const post = req.body
30 | const findPost = await Post.findOne({ content: content })
31 |
32 | if (findPost) return res.status(404).json({
33 | Message: "Post Already Exits"
34 | })
35 |
36 | const newPost = await new Post(post);
37 | const savedPost = newPost.save();
38 | if (savedPost) {
39 | return res.status(200).json({
40 | isSaved: true
41 | })
42 | }
43 | res.status(500).json({
44 | isSaved: false,
45 | Error: "Something happend with server"
46 | })
47 | })
48 |
49 | // edit post, if user authenticated, then edit or show auth required
50 | router.patch("/post/:id", async (req, res) => {
51 | try {
52 | const { id } = req.params;
53 | const newPost = req.body;
54 | const findPost = await Post.findById(id);
55 |
56 | if (findPost) {
57 | const updatePost = await Post.updateOne(newPost)
58 | if (updatePost) {
59 | return res.json({
60 | Msg: "updated"
61 | })
62 | }
63 | else {
64 | return res.json({
65 | Msg: "not updated"
66 | })
67 |
68 | }
69 | }
70 | } catch (error) {
71 | return res.status(404).json({
72 | Message: "Something happend,Please try again!"
73 | });
74 | }
75 | })
76 |
77 | // delete post, if user authenticated
78 | router.delete("/post/:id", async (req, res) => {
79 | try {
80 | const { id } = req.params;
81 | const findPost = await Post.deleteOne({ _id: id })
82 |
83 | if (findPost.deletedCount === 0) {
84 | return res.status(404).json({
85 | Message: "Post Not Found!"
86 | });
87 | }
88 | return res.status(200).json({
89 | Message: "Post Deleted Successfully!"
90 | });
91 | } catch (error) {
92 | return res.status(404).json({
93 | Message: "Server issue!"
94 | });
95 |
96 | }
97 | })
98 |
99 | // Generate token for auth
100 | // router.get("/auth", async (req, res) => {
101 | // const { username } = req.body
102 | // const token = jwt.sign({ username: username }, "secrete-" + username, { expiresIn: "2h" });
103 | // return res.json({
104 | // token: token,
105 | // })
106 | // })
107 |
108 | export { router as postRouter }
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/routes/products.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import Product from "../models/Product.js";
3 | import jwt from "jsonwebtoken"
4 |
5 | const router = express.Router();
6 |
7 | // get all blogs
8 | router.get("/", async (req, res) => {
9 | const allProduct = await Product.find();
10 | allProduct.length ? res.status(200).json(allProduct) : res.status(404).json({ message: "No posts found" });
11 | })
12 |
13 | // get single post by id
14 | router.get("/product/:id", async (req, res) => {
15 | try {
16 | const { id } = req.params;
17 | const findProduct = await Product.findById(id);
18 | return res.status(200).json(findProduct);
19 | } catch (error) {
20 | return res.status(404).json({
21 | Message: "Product Not found"
22 | });
23 | }
24 | });
25 |
26 | // post new blog
27 | router.post("/", async (req, res) => {
28 | const { content } = req.body
29 | const product = req.body
30 | const findProduct = await Product.findOne({ content: content })
31 |
32 | if (findProduct) return res.status(404).json({
33 | Message: "Product Already Exits"
34 | })
35 |
36 | const newProduct = await new Product(post);
37 | const savedProduct = newProduct.save();
38 | if (savedProduct) {
39 | return res.status(200).json({
40 | isSaved: true
41 | })
42 | }
43 | res.status(500).json({
44 | isSaved: false,
45 | Error: "Something happend with server"
46 | })
47 | })
48 |
49 | // edit post, if user authenticated, then edit or show auth required
50 | router.patch("/product/:id", async (req, res) => {
51 | try {
52 | const { id } = req.params;
53 | const newPost = req.body;
54 | const findPost = await Post.findById(id);
55 |
56 | if (findPost) {
57 | const updatePost = await Post.updateOne(newPost)
58 | if (updatePost) {
59 | return res.json({
60 | Msg: "updated"
61 | })
62 | }
63 | else {
64 | return res.json({
65 | Msg: "not updated"
66 | })
67 |
68 | }
69 | }
70 | } catch (error) {
71 | return res.status(404).json({
72 | Message: "Something happend,Please try again!"
73 | });
74 | }
75 | })
76 |
77 | // delete post, if user authenticated
78 | router.delete("/product/:id", async (req, res) => {
79 | try {
80 | const { id } = req.params;
81 | const findPost = await Product.deleteOne({ _id: id })
82 |
83 | if (findPost.deletedCount === 0) {
84 | return res.status(404).json({
85 | Message: "Post Not Found!"
86 | });
87 | }
88 | return res.status(200).json({
89 | Message: "Post Deleted Successfully!"
90 | });
91 | } catch (error) {
92 | return res.status(404).json({
93 | Message: "Server issue!"
94 | });
95 |
96 | }
97 | })
98 |
99 | // Generate token for auth
100 | // router.get("/auth", async (req, res) => {
101 | // const { username } = req.body
102 | // const token = jwt.sign({ username: username }, "secrete-" + username, { expiresIn: "2h" });
103 | // return res.json({
104 | // token: token,
105 | // })
106 | // })
107 |
108 | export { router as productRouter }
--------------------------------------------------------------------------------
/UsersAPI with AUTH/README.md:
--------------------------------------------------------------------------------
1 | ## UsersAPI with AUTH
2 |
3 | ## This API is made with NodeJS, Express, MongoDB and JWT
4 |
5 | #### To run this API you need to have NodeJS and MongoDB installed
6 |
7 | ### MongoDB - Compass
8 | You need MongoDB Compass to connect or see the database. Install MongoDB and MongoDB Compass and then run the API.
9 |
10 | - #### To install MongoDB go to the [MongoDB](https://www.mongodb.com/try/download/community) website and download the version for your OS
11 | - #### To install MongoDB Compass go to the [MongoDB Compass](https://www.mongodb.com/products/compass) website and download the version for your OS
12 | - #### After installing MongoDB and MongoDB Compass, open MongoDB Compass and connect to the database
13 |
14 | ### Default MongoDB Connection String - localhost
15 |
16 | ```bash
17 | mongodb://localhost:27017
18 | ```
19 |
20 | add the database name to the connection string
21 |
22 | ```bash
23 | mongodb://localhost:27017/users-api
24 | ```
25 |
26 | ### Create a .env file in the root directory and add the following:
27 |
28 | ```bash
29 | PORT=3000
30 | MONGO_URI=mongodb://localhost:27017/users
31 | ```
32 | > In case, I added the .env file to this repository, but it is not recommended to do so. So I recommend you to modify the .env file according to your need. You can change port, url whatever you want. I don't have any sensitive data in this file. It is just for the sake of simplicity.
33 |
34 |
35 | ### Install dependencies:
36 |
37 | ```bash
38 | npm install
39 | ```
40 |
41 | ### To run the API run the command:
42 |
43 | ```bash
44 | npm run dev
45 | ```
46 |
47 | ### API Testing - Tools
48 | You can test the API using Postman or Insomnia or any other API testing tool.
49 |
50 | - #### Postman
51 |
52 | - ###### Download Postman from the [Postman](https://www.postman.com/downloads/) website
53 |
54 | - #### Insomnia
55 |
56 | - ###### Download Insomnia from the [Insomnia](https://insomnia.rest/download/) website
57 |
58 |
59 |
60 | ## API Routes - Endpoints
61 |
62 | Base URL: http://localhost:5000 or your custom port
63 |
64 | - ### Users
65 |
66 | - #### GET /users
67 |
68 | - ##### Get all users
69 |
70 |
71 | - ### Auth
72 |
73 | - #### GET /auth/:username
74 |
75 | - ##### Get a user
76 | - ##### Request Body
77 |
78 | ```ternimal
79 | url: /auth/devvsakib
80 | ```
81 |
82 | - #### POST /auth
83 |
84 | - ##### Login a user
85 | - ##### Request Body
86 |
87 | ```json
88 | {
89 | "username": "",
90 | "password": ""
91 | }
92 | ```
93 |
94 |
95 | - #### POST /auth/register
96 |
97 | - ##### Register a user
98 | - ##### Request Body
99 |
100 | ```json
101 | {
102 | "name": "",
103 | "username": "",
104 | "password": ""
105 | }
106 | ```
107 |
108 | - #### POST /auth/:username
109 |
110 | - ##### Update a user
111 | - ##### Request Body
112 |
113 | ```json
114 | {
115 | "name": "",
116 | "username": ""
117 | }
118 | ```
119 |
120 | - #### POST /auth/logout
121 |
122 | - ##### Logout a user
123 | - ##### Request Header
124 |
125 | ```json
126 | {
127 | "x-auth-token": ""
128 | }
129 | ```
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 |
4 | ## Our Pledge
5 |
6 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
7 |
8 | ## Our Standards
9 |
10 | Examples of behavior that contributes to creating a positive environment include:
11 |
12 | * Using welcoming and inclusive language
13 | * Being respectful of differing viewpoints and experiences
14 | * Gracefully accepting constructive criticism
15 | * Focusing on what is best for the community
16 | * Showing empathy towards other community members
17 |
18 | Examples of unacceptable behavior by participants include:
19 |
20 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
21 | * Trolling, insulting/derogatory comments, and personal or political attacks
22 | * Public or private harassment
23 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
24 | * Other conduct which could reasonably be considered inappropriate in a professional setting
25 |
26 | ## Our Responsibilities
27 |
28 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
29 |
30 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
31 |
32 | ## Scope
33 |
34 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
35 |
36 | ## Enforcement
37 |
38 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
39 |
40 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
41 |
42 | ## Attribution
43 |
44 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
45 |
46 | [homepage]: http://contributor-covenant.org
47 | [version]: http://contributor-covenant.org/version/1/4/
48 |
49 | #### Path: CONTRIBUTING.md
50 | #### Path: SECURITY.md
51 | #### Path: .github/ISSUE_TEMPLATE/bug_report.md
52 | #### Path: .github/ISSUE_TEMPLATE/feature_request.md
53 | #### Path: .github/ISSUE_TEMPLATE/config.yml
54 | #### Path: .github/PULL_REQUEST_TEMPLATE.md
55 | #### Path: .github/workflows/main.yml
--------------------------------------------------------------------------------
/blog-post-api-mongodb/routes/users.js:
--------------------------------------------------------------------------------
1 | import expres from "express";
2 | import User from "../models/User.js";
3 | import bcrypt from "bcrypt"
4 | import jwt from "jsonwebtoken"
5 |
6 | const router = expres.Router();
7 |
8 | const auth = async (req, res, next) => {
9 | const token = req.headers.authorization;
10 | if (token) {
11 | jwt.verify(token, "secret", (err) => {
12 | if (err) return res.json({
13 | message: "Please Login!"
14 | })
15 | next()
16 | })
17 | } else {
18 | res.json({
19 | message: "Please Login!",
20 | statusCode: 401
21 | })
22 | }
23 |
24 | }
25 |
26 | router.get("/", async (req, res) => {
27 | const users = await User.find().select(["-password", "-email", "-_id"]);
28 | res.json(users);
29 | })
30 |
31 | router.get("/:username", async (req, res) => {
32 | const { username } = req.params
33 | const findUser = await User.findOne({ username: username }).select("-password")
34 | if (!findUser) return res.status(404).json({ message: "No user found" })
35 |
36 | res.json(findUser)
37 | })
38 |
39 | router.post("/register", async (req, res) => {
40 | const user = req.body
41 | const findUser = await User.findOne({ username: user.username })
42 | if (findUser) return res.status(400).json({ message: "Username already taken!" })
43 |
44 |
45 | const hashP = await bcrypt.hash(user.password, 10);
46 |
47 | const newUser = await new User({ ...user, password: hashP })
48 | newUser.save()
49 | res.status(201).json({ message: "Account Created Successfully!" })
50 | })
51 |
52 | router.post("/login", async (req, res) => {
53 | const { password, username } = req.body
54 | const user = await User.findOne({ username: username })
55 | if (!user) return res.status(400).json({ message: "User doesn't exist!" })
56 | const isPasswordValid = await bcrypt.compare(password, user.password);
57 |
58 | if (!isPasswordValid) {
59 | return res.status(403).json({
60 | message: "Username or Password not currect!"
61 | })
62 | }
63 |
64 | const token = jwt.sign({ id: user._id }, "secret");
65 |
66 | res.status(200).json(
67 | {
68 | token,
69 | userId: user._id,
70 | username: user.username,
71 | message: "Login Successfully!"
72 | }
73 | )
74 | })
75 |
76 | router.patch("/:username", auth, async (req, res) => {
77 | const user = req.body;
78 | const { username } = req.params;
79 | if (user.username !== username) return res.status(400).json({
80 | message: "Username can't be changed"
81 | });
82 | try {
83 | if (user.password) {
84 | const hashP = await bcrypt.hash(user.password, 10);
85 | user.password = hashP
86 | }
87 |
88 | const updatedUser = await User.updateOne(
89 | { username: username },
90 | { ...user }
91 | );
92 |
93 | if (updatedUser.n === 0) {
94 | return res.status(404).json({ message: "User not found" });
95 | }
96 |
97 | res.status(200).json({ message: "User updated successfully" });
98 | } catch (err) {
99 | console.error(err.message);
100 | res.status(500).send("Server Error");
101 | }
102 | });
103 |
104 | router.delete("/:username", async (req, res) => {
105 | const { username } = req.params;
106 | const user = await User.deleteOne({ username: username })
107 | if (!user) return res.status(400).json({ message: "User password not matched!" })
108 | else return res.status(200).json({ message: "User deleted!" })
109 | })
110 |
111 | export default auth;
112 | export { router as userRouter }
--------------------------------------------------------------------------------
/movie-watchlist/public/assets/react.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/recipe ap with auth/frontend/src/assets/react.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/recipe-sharing-platform/frontend/src/assets/react.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/blog-post-api-mongodb - Copy/routes/users.js:
--------------------------------------------------------------------------------
1 | import expres from "express";
2 | import bcrypt from "bcrypt"
3 | import jwt from "jsonwebtoken"
4 | import User from "../models/User.js";
5 |
6 |
7 | const router = expres.Router();
8 |
9 | const auth = async (req, res, next) => {
10 | const token = req.headers.authorization;
11 | if (token) {
12 | jwt.verify(token, "secret", (err) => {
13 | if (err) return res.json({
14 | message: "Please Login!"
15 | })
16 | next()
17 | })
18 | } else {
19 | res.json({
20 | message: "Please Login!",
21 | statusCode: 401
22 | })
23 | }
24 |
25 | }
26 |
27 | router.get("/", async (req, res) => {
28 | const users = await User.find().select(["-password", "-_id"]);
29 | res.json(users);
30 | })
31 |
32 | router.get("/:username", async (req, res) => {
33 | const { username } = req.params
34 | const findUser = await User.findOne({ username: username }).select("-password")
35 | if (!findUser) return res.status(404).json({ message: "No user found" })
36 |
37 | res.json(findUser)
38 | })
39 |
40 | router.post("/register", async (req, res) => {
41 | const user = req.body
42 | const findUserByUsername = await User.findOne({ username: user.username });
43 | const findUserByPhoneNumber = await User.findOne({ phoneNumber: user.phoneNumber });
44 |
45 | if (findUserByUsername) {
46 | return res.status(400).json({ message: "Username already taken!" });
47 | }
48 |
49 | if (findUserByPhoneNumber) {
50 | return res.status(400).json({ message: "Phone number already taken!" });
51 | }
52 |
53 | const hashP = await bcrypt.hash(user.password, 10);
54 |
55 | const newUser = new User({ ...user, password: hashP })
56 | newUser.save()
57 | res.status(201).json({ message: "Account Created Successfully!" })
58 | })
59 |
60 |
61 | router.post("/login", async (req, res) => {
62 | const { password, username } = req.body
63 | const user = await User.findOne({ username: username })
64 | if (!user) return res.status(400).json({ message: "User doesn't exist!" })
65 | const isPasswordValid = await bcrypt.compare(password, user.password);
66 |
67 | if (!isPasswordValid) {
68 | return res.status(403).json({
69 | message: "Username or Password not currect!"
70 | })
71 | }
72 |
73 | const token = jwt.sign({ id: user.type }, "secret");
74 |
75 | res.status(200).json(
76 | {
77 | token,
78 | userId: user._id,
79 | username: user.username,
80 | message: "Login Successfully!"
81 | }
82 | )
83 | })
84 |
85 | router.patch("/:username", auth, async (req, res) => {
86 | const user = req.body;
87 | const { username } = req.params;
88 | if (user.username !== username) return res.status(400).json({
89 | message: "Username can't be changed"
90 | });
91 | try {
92 | if (user.password) {
93 | const hashP = await bcrypt.hash(user.password, 10);
94 | user.password = hashP
95 | }
96 |
97 | const updatedUser = await User.updateOne(
98 | { username: username },
99 | { ...user }
100 | );
101 |
102 | if (updatedUser.n === 0) {
103 | return res.status(404).json({ message: "User not found" });
104 | }
105 |
106 | res.status(200).json({ message: "User updated successfully" });
107 | } catch (err) {
108 | console.error(err.message);
109 | res.status(500).send("Server Error");
110 | }
111 | });
112 |
113 | router.delete("/:username", async (req, res) => {
114 | const { username } = req.params;
115 | const user = await User.deleteOne({ username: username })
116 | if (!user) return res.status(400).json({ message: "User password not matched!" })
117 | else return res.status(200).json({ message: "User deleted!" })
118 | })
119 |
120 | export default auth;
121 | export { router as userRouter }
--------------------------------------------------------------------------------
/realmate/models/User.js:
--------------------------------------------------------------------------------
1 | import mongoose from "mongoose";
2 |
3 | const userSchema = new mongoose.Schema({
4 | userID: {
5 | type: String,
6 | required: true,
7 | unique: true
8 | },
9 | // done
10 | basicInformation: {
11 | firstName: String,
12 | lastName: String,
13 | gender: String,
14 | dob: Date,
15 | createProfileFor: String,
16 | numberOfChildren: Number,
17 | photo: String,
18 | introduction: String,
19 | firstLanguage: String,
20 | email: {
21 | type: String,
22 | required: true
23 | },
24 | phone: {
25 | type: String,
26 | required: true,
27 | unique: true
28 | },
29 | age: Number,
30 | maritalStatus: String,
31 | religion: String,
32 | caste: String
33 | },
34 | // done
35 | permanentAddress: {
36 | sameAsPresentAddress: Boolean,
37 | country: String,
38 | state: String,
39 | postalCode: String,
40 | city: String,
41 | },
42 | presentAddress: {
43 | country: String,
44 | state: String,
45 | postalCode: String,
46 | city: String,
47 | },
48 | // done
49 | education: [
50 | {
51 | degree: String,
52 | institution: String,
53 | start: Date,
54 | end: Date,
55 | status: String
56 | }
57 | ],
58 | career: [
59 | {
60 | designation: String,
61 | company: String,
62 | start: Date,
63 | end: Date,
64 | status: String
65 | }
66 | ],
67 | physicalAttributes: {
68 | height: String,
69 | weight: String,
70 | eyeColor: String,
71 | hairColor: String,
72 | complexion: String,
73 | bloodGroup: String,
74 | disability: String
75 | },
76 | languages: {
77 | motherTongue: String,
78 | knownLanguages: [String]
79 | },
80 | // done
81 | familyInformation: {
82 | father: Boolean,
83 | mother: Boolean,
84 | siblings: Boolean
85 | },
86 | hobbies: {
87 | hobbies: [String],
88 | interests: [String],
89 | music: [String],
90 | books: [String],
91 | movies: [String],
92 | tvShows: [String],
93 | sports: [String],
94 | fitnessActivities: [String],
95 | cuisines: [String],
96 | dressStyles: [String]
97 | },
98 | lifestyle: {
99 | diet: String,
100 | drink: String,
101 | smoke: String,
102 | livingWith: String
103 | },
104 | personalAttitude: {
105 | politicalViews: String,
106 | religiousService: String
107 | },
108 | spiritualSocialBg: {
109 | religion: String,
110 | caste: String,
111 | ethnicity: String,
112 | familyValue: String
113 | },
114 | // done
115 | partnerExpectation: {
116 | generalRequirements: String,
117 | residenceCountry: String,
118 | minHeight: Number,
119 | maxWeight: Number,
120 | maritalStatus: String,
121 | childrenAcceptable: Boolean,
122 | religion: String,
123 | caste: String,
124 | language: String,
125 | education: String,
126 | profession: String,
127 | smokingAcceptable: Boolean,
128 | drinkingAcceptable: Boolean,
129 | dietAcceptable: Boolean,
130 | preferredCountry: String,
131 | preferredState: String,
132 | complexion: String
133 | },
134 | shortlist: {
135 | type: Array,
136 | default: []
137 | },
138 | myInterest: {
139 | type: Array,
140 | default: []
141 | },
142 | interestedMembers: {
143 | type: Array,
144 | default: []
145 | },
146 | isPremium: {
147 | type: Boolean,
148 | default: false
149 | },
150 | password: {
151 | type: String,
152 | required: true
153 | },
154 | createdAt: {
155 | type: Date,
156 | default: Date.now()
157 | }
158 | });
159 |
160 | export default mongoose.model('Users', userSchema);
161 |
--------------------------------------------------------------------------------
/mongodb/README.md:
--------------------------------------------------------------------------------
1 | # Cheatsheet for MongoDB
2 | For better use, create a collection name **content**
3 | In this cheatsheet, ***content*** is a collection name.
4 | > db.content.drop(); content is collection name
5 |
6 |
7 | 1. Show All DataBase
8 | ```shell
9 | show dbs
10 | ```
11 |
12 | 2. Create new/switch DataBase
13 | ```shell
14 | use DBNAME
15 | ```
16 |
17 | 3. Show current DataBase
18 | ```shell
19 | db
20 | ```
21 |
22 | 4. Delete DataBase
23 | ```shell
24 | db.dropDatabase()
25 | ```
26 |
27 | 5. Show DataBase Collection
28 | ```shell
29 | show collections
30 | ```
31 |
32 | 6. Create new Collection
33 | ```shell
34 | db.createCollection("content")
35 | ```
36 |
37 | 7. Delete Collection
38 | ```shell
39 | db.content.drop()
40 | ```
41 |
42 | 8. Insert rows in Collection
43 | ```shell
44 | db.content.insert({
45 | name: "DevvSakib",
46 | role: "Frontend Developer",
47 | fvstack: "React",
48 | tool: "vscode"
49 | })
50 | ```
51 |
52 | 9. Insert multiple rows in Collection
53 | ```shell
54 | db.content.insertMany([
55 | {
56 | name: "DevvSakib",
57 | role: "Frontend Developer",
58 | fvstack: "React",
59 | tool: "vscode"
60 | },
61 | {
62 | name: "Unknown",
63 | role: "Frontend Developer",
64 | fvstack: "React",
65 | tool: "figma"
66 | }
67 | ])
68 | ```
69 |
70 |
71 | 10. Find all rows in Collection
72 | ```shell
73 | db.content.find()
74 | db.content.find().pretty()
75 | ```
76 | > pretty() for better view
77 |
78 | 11. Find specific rows in Collection
79 | ```shell
80 | db.content.find({name: "DevvSakib"})
81 | db.content.find({role: "Frontend Developer", name: "DevvSakib"})
82 | ```
83 |
84 |
85 | 12. Find rows with limit
86 | ```shell
87 | db.content.find().limit(1)
88 | ```
89 |
90 | 13. Count rows in Collection
91 | ```shell
92 | db.content.find().count()
93 | db.content.find({name: "DevvSakib"}).count()
94 | ```
95 |
96 | ```shell
97 | db.content.find().sort({name: 1})
98 | db.content.find().sort({id: 1})
99 | ```
100 | > 1 for ascending order and -1 for descending order
101 |
102 | 15. Update row
103 | ```shell
104 | db.content.update({name: "DevvSakib"}, {$set: {name: "0xDevvSakib"}})
105 | ```
106 |
107 |
108 | In case if there are no matching row then it will create a new row if you add upsert: true
109 | ```shell
110 | db.content.update({name: "NotInCollection"}, {$set: {name: "0xDevvSakib"}}. {upsert: true})
111 | ```
112 | > {name: "NotInCollection"} is the query and {$set: {name: "0xDevvSakib"}} is the update. {upsert: true} is the option. In case query doesn't match any row then it will create a new row.
113 |
114 |
115 | 16. Delete row in Collection
116 | ```shell
117 | db.content.remove({name: "0xDevvSakib"})
118 | ```
119 |
120 | 17. Delete all rows in Collection
121 | ```shell
122 | db.content.remove({})
123 | ```
124 |
125 | ### Update Operators
126 |
127 | 18. Increament operator
128 | ```shell
129 | db.content.update({name: "0xDevvSakib"}, {$inc: {age: 4}})
130 | ```
131 |
132 |
133 | 19. Rename operator
134 | ```shell
135 | db.content.update({name: "0xDevvSakib"}, {$rename: {age: "newAge"}})
136 | ```
137 |
138 | ```shell
139 | db.content.update({}, {$rename: {age: "newAge"}})
140 | ```
141 | > {} for all rows
142 |
143 | 20. Push operator
144 | ```shell
145 | db.content.update({name: "0xDevvSakib"}, {$push: {skills: "MongoDB"}})
146 | ```
147 |
148 |
149 | 21. Delete operator
150 | ```shell
151 | db.content.remove({name: "Unknown"})
152 | ```
153 |
154 | 22. Less than operator
155 | ```shell
156 | db.content.find({age: {$lt: 30}})
157 | ```
158 |
159 | 22. Greater than operator
160 | ```shell
161 | db.content.find({age: {$gt: 30}})
162 | ```
163 |
164 |
165 | ## Connecting online MongoDB Cluster
166 |
167 | 1. Create a account in [MongoDB Atlas](https://www.mongodb.com/cloud/atlas)
168 | 2. Create a new project
169 | 3. Create a new cluster
170 | 4. Create a new database user
171 |
172 |
173 |
174 |
175 | ### Copy this url and paste it in Compass
176 |
177 |
178 | ### Remove the < > from the connection string and replace the password with your password
179 |
180 |
181 | ### Here you will see your Database name
182 |
183 |
184 | **DONE! Now you can connect your MongoDB Cluster with Compass**
--------------------------------------------------------------------------------
/movie-watchlist/src/components/Card/MovieCard.jsx:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from "react"
2 | import axios from "axios"
3 |
4 | const MovieCard = ({ drama, idx, addDrama }) => {
5 | const [singleDrama, setSingleDrama] = useState('')
6 | const [synopsis, setSynopsis] = useState('')
7 | const [description, setDescription] = useState('')
8 | const [name, setName] = useState('')
9 | const [thumbnail, setThumbnail] = useState("")
10 | const [watched, setWatched] = useState(false)
11 | const [showCast, setShowCast] = useState(true)
12 | useEffect(() => {
13 | const api = `https://mydramalist-scrape-api.vercel.app/id/${drama.slug}`
14 | axios.get(api)
15 | .then(data => {
16 | setSingleDrama(data.data.data);
17 | setSynopsis(data.data.data.synopsis);
18 | })
19 |
20 | console.log(JSON.parse(localStorage.getItem('drama')));
21 | }, [drama])
22 |
23 | useEffect(()=>{
24 |
25 | axios.post('http://localhost:5000/add', {name, thumbnail, description, watched})
26 | .then(res => console.log(res.data))
27 | .catch(err => console.log(err))
28 | }, [name])
29 |
30 | return (
31 | singleDrama?.title ? (
32 |
33 |
34 |
35 |
36 |
37 |
{singleDrama?.title}
38 |
{synopsis.length > 50 ? synopsis.slice(0, 70) + "..." : "No Synopsis"}
39 |
Type: {singleDrama.details?.type}
40 |
Country: {singleDrama.details?.country}
41 |
Rating: {singleDrama.rating}
42 |
Episodes: {singleDrama.details?.episodes}
43 |
Ranked: {singleDrama.details?.ranked}
44 |
Genere:
45 | {
46 | singleDrama.others?.genres ?
47 | singleDrama.others?.genres.map((genre, id) => (
48 | {genre}{singleDrama.others?.genres.length - 1 !== id ? ", " : ""}
49 | )) : "No genre found"
50 | }
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 | {/* SHOW */}
61 |
setShowCast(!showCast)}>Show Cast
63 | {/* Watch */}
64 |
65 | Watch
66 |
67 | {/* Add */}
68 |
{setName(singleDrama.title); setDescription(synopsis); setThumbnail(singleDrama.poster);setWatched(false)}} className="my-2 btn-primary px-4 rounded-md uppercase font-semibold">Add
69 |
70 |
71 | {
72 | singleDrama?.casts?.map(cast => (
73 |
74 |
75 |
76 |
77 |
78 |
79 | ))
80 | }
81 |
82 |
83 |
84 | ) : undefined
85 | )
86 | }
87 |
88 | export default MovieCard
--------------------------------------------------------------------------------
/UsersAPI with AUTH/routes/users.js:
--------------------------------------------------------------------------------
1 | import express from "express"
2 | import bcrypt from "bcrypt"
3 | import User from "../models/User.js"
4 | import jwt from "jsonwebtoken";
5 |
6 | const router = express.Router();
7 |
8 | // Response JSON, will use to reduce code and DRY
9 | const resJson = (message, token, userId) => {
10 | if (userId && token) {
11 | const jsn = {
12 | message: message,
13 | token: token,
14 | userId: userId
15 | }
16 | return jsn
17 | }
18 | const jsn = {
19 | message: message
20 | }
21 | return jsn
22 | }
23 |
24 | // Authontication middleware
25 | const auth = (req, res, next) => {
26 | const token = req.headers.x_auth_token
27 | if (!token) return res.status(401).json(resJson("Please Login First!"))
28 |
29 | jwt.verify(token, "secret-" + (req.params.username || req.body.username), err => {
30 | if (err) return res.status(403).json(resJson("Unauthorized Access Attempted!"))
31 | next();
32 | })
33 | }
34 |
35 | // Get all users from database
36 | router.get("/users", async (req, res) => {
37 | const users = await User.find({})
38 | res.status(200).json(users)
39 | })
40 | // Create new user
41 | router.post("/auth/register", async (req, res) => {
42 | const user = req.body
43 | const findUser = await User.findOne({ username: user.username })
44 |
45 | if (findUser) {
46 | return res.status(401).json(resJson("Username Already Taken!"))
47 | }
48 |
49 | if (!user.password || !user.username || !user.name) {
50 | return res.status(401).json(resJson("All field Required"))
51 | }
52 |
53 | const hashedPassword = await bcrypt.hash(user.password, 10);
54 |
55 | const saveUser = await new User({ ...user, password: hashedPassword })
56 |
57 | saveUser.save();
58 | res.status(201).json(resJson("Registration Success!"))
59 |
60 | })
61 |
62 | // Login user
63 | router.post("/auth", async (req, res) => {
64 | const user = req.body
65 | const findUser = await User.findOne({ username: user.username })
66 |
67 | if (!findUser) {
68 | return res.status(404).json(resJson("User Not Found"))
69 | }
70 |
71 | if (!user.password || !user.username) {
72 | return res.status(422).json(resJson("All field Required"))
73 | }
74 |
75 | const comparePassword = bcrypt.compareSync(user.password, findUser.password);
76 |
77 | if (!comparePassword) {
78 | return res.status(401).json(resJson("Password is incorrect"))
79 | }
80 |
81 | // Generate token for login AUTH
82 | const token = jwt.sign({ id: findUser._id, username: findUser.username }, "secret-" + user.username, { expiresIn: "7d" })
83 | // const token = jwt.sign({ id: findUser._id, username: findUser.username }, "secret", { expiresIn: "7d" })
84 |
85 | // Send toking token to client to store in cookies
86 | return res.status(200).json(resJson("Password Matched", token, findUser._id))
87 | })
88 |
89 | // Update user information, auth middleware to check if usr logged in or not
90 | router.patch("/auth/:username", auth, async (req, res) => {
91 | const user = req.body;
92 | const { username } = req.params;
93 | const findUser = await User.findOne({ username: user.username })
94 |
95 | if (username !== user.username) return res.status(403).json(resJson("Username cannot be change"))
96 |
97 | if (!findUser) return res.status(404).json(resJson("User not found,Please your username"))
98 |
99 | const updatedUser = await User.updateOne({ username: username }, { ...user });
100 | if (updatedUser) {
101 | return res.status(200).json(resJson("Update Succesfull"))
102 | }
103 | return res.status(500).json(resJson("Server Error. Please try again"))
104 |
105 | })
106 |
107 | // Delete user, auth middleware to check if usr logged in or not
108 | router.delete("/auth/:username", auth, async (req, res) => {
109 | const username = req.params.username;
110 | const findUser = await User.findOne({ username })
111 |
112 | if (!findUser) {
113 | return res.status(404).json(resJson("User not found"))
114 | }
115 |
116 | const deleteUser = await User.deleteOne(findUser)
117 | if (deleteUser) {
118 | return res.status(200).json(resJson("User Deleted"))
119 | }
120 | res.status(500).json(resJson("Server Error, Please try again"))
121 | })
122 |
123 | // Logout user
124 | router.post("/auth/logout", auth, (req, res) => {
125 | const { username } = req.body
126 | res.status(200).json(resJson(`Logout Success ${username}`))
127 | })
128 |
129 |
130 |
131 | // Get a user by username
132 | router.get("/user/:username", async (req, res) => {
133 | const user = req.params
134 | const findUser = await User.findOne({ username: user.username }).select("-password -_id")
135 | findUser ? res.status(200).json(findUser) : res.status(201).json(resJson("not found"))
136 | })
137 |
138 |
139 |
140 | export default router;
--------------------------------------------------------------------------------
/realmate/README.md:
--------------------------------------------------------------------------------
1 | ## RealMate
2 |
3 | ## This API build with NodeJS, Express, MongoDB and JWT
4 |
5 | #### To run this API you need to have NodeJS and MongoDB installed
6 |
7 | ### MongoDB - Compass
8 | You need MongoDB Compass to connect or see the database. Install MongoDB and MongoDB Compass and then run the API.
9 |
10 | - #### To install MongoDB go to the [MongoDB](https://www.mongodb.com/try/download/community) website and download the version for your OS
11 | - #### To install MongoDB Compass go to the [MongoDB Compass](https://www.mongodb.com/products/compass) website and download the version for your OS
12 | - #### After installing MongoDB and MongoDB Compass, open MongoDB Compass and connect to the database
13 |
14 | ### Default MongoDB Connection String - localhost
15 |
16 | ```bash
17 | mongodb://localhost:27017
18 | ```
19 |
20 | add the database name to the connection string
21 |
22 | ```bash
23 | mongodb://localhost:27017/realmate
24 | ```
25 |
26 | ### Create a .env file in the root directory and add the following:
27 |
28 | ```bash
29 | PORT=5000
30 | MONGO_URI=mongodb://localhost:27017/realmate
31 | ```
32 | > In case, I added the .env file to this repository, but it is not recommended to do so. So I recommend you to modify the .env file according to your need. You can change port, url whatever you want. I don't have any sensitive data in this file. It is just for the sake of simplicity.
33 |
34 |
35 | ### Install dependencies:
36 |
37 | ```bash
38 | npm install
39 | or
40 | yarn install
41 | ```
42 |
43 | ### To run the API run the command:
44 |
45 | ```bash
46 | npm run dev
47 | or
48 | yarn dev
49 | ```
50 |
51 | ### API Testing - Tools
52 | You can test the API using Postman or Insomnia or any other API testing tool.
53 |
54 | - #### Postman
55 |
56 | - ###### Download Postman from the [Postman](https://www.postman.com/downloads/) website
57 |
58 | - #### Insomnia
59 |
60 | - ###### Download Insomnia from the [Insomnia](https://insomnia.rest/download/) website
61 |
62 |
63 |
64 | ## API Routes - Endpoints
65 |
66 | Base URL: http://localhost:5000/api/ or your custom port
67 |
68 | - ### Users
69 |
70 | - #### GET /users
71 |
72 | - ##### Get all users
73 |
74 |
75 | - ### Authenticated Required to access the following routes
76 |
77 | - #### GET /users/:userID
78 |
79 | - ##### Get a user by ID
80 |
81 | ```
82 | url: /356263
83 | ```
84 |
85 | - #### POST /auth
86 |
87 | - ##### Login a user [not implemented yet]
88 | - ##### Request Body
89 |
90 | ```json
91 | {
92 | "username": "",
93 | "password": ""
94 | }
95 | ```
96 |
97 |
98 | - #### POST /users
99 |
100 | - ##### Register a user
101 | - ##### Request Body
102 |
103 | ```json
104 | {
105 | "basicInformation": {
106 | "firstName": "John",
107 | "lastName": "Doe",
108 | "gender": "Male",
109 | "dob": "1990-01-01",
110 | "createProfileFor": "Self",
111 | "photo": "https://example.com/photo.jpg",
112 | "introduction": "I am a friendly and outgoing person.",
113 | "firstLanguage": "English",
114 | "email": "john.doe@example.com",
115 | "phone": "987654321"
116 | },
117 | "address": {
118 | "country": "Bangladesh"
119 | },
120 | "password": "0345f3"
121 | }
122 |
123 | ```
124 |
125 | - #### PATCH /:userID/ - Update information individually
126 |
127 | - ##### Update /basic-information
128 | - ##### Request Body
129 |
130 | ```json
131 | {
132 | "firstName": "Sakib",
133 | "lastName": "Ahmed",
134 | "gender": "Male",
135 | "dob": "1990-01-01T00:00:00.000Z",
136 | "createProfileFor": "Self",
137 | "photo": "https://example.com/photo.jpg",
138 | "introduction": "I am a friendly and outgoing person.",
139 | "firstLanguage": "English",
140 | "email": "john.doe@example.com",
141 | "phone": "987654321",
142 | "numberOfChildren": 0,
143 | "maritalStatus": "Single",
144 | "religion": "Islam",
145 | "caste": "Sunni"
146 | }
147 | ```
148 |
149 | - ##### Update /partner-expectation
150 | - ##### Request Body
151 |
152 | ```json
153 | {
154 | "generalRequirements": String,
155 | "residenceCountry": String,
156 | "minHeight": Number,
157 | "maxWeight": Number,
158 | "maritalStatus": String,
159 | "childrenAcceptable": Boolean,
160 | "religion": String,
161 | "caste": String,
162 | "language": String,
163 | "education": String,
164 | "profession": String,
165 | "smokingAcceptable": Boolean,
166 | "drinkingAcceptable": Boolean,
167 | "dietAcceptable": Boolean,
168 | "preferredCountry": String,
169 | "preferredState": String,
170 | "complexion": String
171 | }
172 | ```
173 |
174 | - ##### Update /family-information
175 | - ##### Request Body
176 |
177 | ```json
178 | {
179 | "father": Boolean,
180 | "mother": Boolean,
181 | "siblings": Boolean
182 | }
183 | ```
184 |
185 | - ##### Update /physical-attributes
186 | - ##### Request Body
187 |
188 | ```json
189 | {
190 | "height": String,
191 | "weight": String,
192 | "eyeColor": String,
193 | "hairColor": String,
194 | "complexion": String,
195 | "bloodGroup": String,
196 | "disability": String
197 | },
198 | ```
199 |
200 | - ##### Update /address
201 | - ##### Request Body
202 |
203 | ```json
204 | {
205 | "addressType": "permanentAddress/presentAddress",
206 | "updatedAddress": {
207 | "sameAsPresentAddress": false, // for permanent address only
208 | "country": "United States",
209 | "state": "California",
210 | "postalCode": "12345",
211 | "city": "Los Angeles"
212 | }
213 | }
214 | ```
215 |
--------------------------------------------------------------------------------
/realmate/routes/user.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import User from "../models/User.js";
3 | import shortUUID from "short-uuid";
4 | import bcrypt from "bcrypt"
5 | const router = express.Router()
6 |
7 |
8 | const responseMessage = (message, data) => {
9 | return {
10 | message,
11 | data
12 | }
13 | }
14 |
15 | router.get("/", async (req, res) => {
16 | try {
17 | const users = await User.find();
18 | res.status(200).json(users);
19 | } catch (error) {
20 | console.error(error);
21 | res.status(500).json({ error: "Internal server error" });
22 | }
23 | });
24 | // register user
25 | router.post("/", async (req, res) => {
26 | const user = req.body;
27 | if (!user.password || !user.basicInformation.email) return res.status(400).json({ error: "Missing required fields!" });
28 | try {
29 | const findUser = await User.findOne({ email: user.email })
30 | if (findUser) return res.status(400).json({ error: "Email already used!" });
31 |
32 | // Generate UUID
33 | const translator = shortUUID('0123456789');
34 | const shortID = translator.new().slice(0, 6);
35 | user.userID = shortID;
36 |
37 | // hash the password
38 | const hashedPassword = await bcrypt.hash(user.password, 10)
39 |
40 | const savedUser = await new User({ ...user, password: hashedPassword }).save();
41 | if (!savedUser) return res.status(400).json({ error: "User not Registered!" });
42 |
43 | res.status(201).json(responseMessage("User created successfully", savedUser));
44 |
45 | } catch (error) {
46 | console.error(error);
47 | res.status(500).json({ error: "Internal server error" });
48 | }
49 | });
50 |
51 | // Get all users
52 | router.get("/users", async (req, res) => {
53 | try {
54 | const users = await User.find();
55 | res.json(users);
56 | } catch (error) {
57 | res.status(500).json({ error: error.message });
58 | }
59 | });
60 |
61 | // Get a single user by userID
62 | router.get("/:userID", async (req, res) => {
63 | try {
64 | const user = await User.findOne({ userID: req.params.userID }).select("-password");
65 | if (!user) {
66 | return res.status(404).json({ message: "User not found" });
67 | }
68 | // remove the password from the response
69 | const { password, ...data } = user._doc;
70 | res.status(200).json(user);
71 |
72 | } catch (error) {
73 | res.status(500).json({ error: error.message });
74 | }
75 | });
76 |
77 |
78 | // Delete a user by userID
79 | router.delete("/:userID", async (req, res) => {
80 | try {
81 | const user = await User.findOneAndDelete({ userID: req.params.userID });
82 | if (!user) {
83 | return res.status(404).json({ message: "User not found" });
84 | }
85 | res.json({ message: "User deleted successfully" });
86 | } catch (error) {
87 | res.status(500).json({ error: error.message });
88 | }
89 | });
90 |
91 |
92 | // Update user's Basic Information
93 | router.patch("/:userID/basic-information", async (req, res) => {
94 | try {
95 | const updatedInfo = req.body;
96 |
97 | if (!updatedInfo) {
98 | return res.status(400).json({ error: "Missing required fields!" });
99 | }
100 |
101 | const user = await User.findOne({ userID: req.params.userID });
102 | if (!user) {
103 | return res.status(404).json({ error: "User not found" });
104 | }
105 |
106 | user.basicInformation = updatedInfo;
107 | await user.save();
108 |
109 | res.status(200).json(user.basicInformation);
110 |
111 | } catch (error) {
112 | res.status(500).json({ error: "Internal server error" });
113 | }
114 | });
115 |
116 | // Update user's Partner Expectation
117 | router.patch("/:userID/partner-expectation", async (req, res) => {
118 | try {
119 | const updatedInfo = req.body;
120 |
121 | if (!updatedInfo) {
122 | return res.status(400).json({ error: "Missing required fields!" });
123 | }
124 |
125 | const user = await User.findOne({ userID: req.params.userID });
126 | if (!user) {
127 | return res.status(404).json({ error: "User not found" });
128 | }
129 |
130 | user.partnerExpectation = updatedInfo;
131 | await user.save();
132 |
133 | res.status(200).json(user.partnerExpectation);
134 |
135 | } catch (error) {
136 | res.status(500).json({ error: "Internal server error" });
137 | }
138 | });
139 |
140 | // Update user's Family Information
141 | router.patch("/:userID/family-information", async (req, res) => {
142 | try {
143 | const updatedInfo = req.body;
144 |
145 | if (!updatedInfo) {
146 | return res.status(400).json({ error: "Missing required fields!" });
147 | }
148 |
149 | const user = await User.findOne({ userID: req.params.userID });
150 | if (!user) {
151 | return res.status(404).json({ error: "User not found" });
152 | }
153 |
154 | user.familyInformation = updatedInfo;
155 | await user.save();
156 |
157 | res.status(200).json(user.familyInformation);
158 |
159 | } catch (error) {
160 | res.status(500).json({ error: "Internal server error" });
161 | }
162 | });
163 |
164 | // Update user's Physical Attributes
165 | router.patch("/:userID/physical-attributes", async (req, res) => {
166 | try {
167 | const updatedInfo = req.body;
168 |
169 | if (!updatedInfo) {
170 | return res.status(400).json({ error: "Missing required fields!" });
171 | }
172 |
173 | const user = await User.findOne({ userID: req.params.userID });
174 | if (!user) {
175 | return res.status(404).json({ error: "User not found" });
176 | }
177 |
178 | user.physicalAttributes = updatedInfo;
179 | await user.save();
180 |
181 | res.status(200).json(user.physicalAttributes);
182 |
183 | } catch (error) {
184 | res.status(500).json({ error: "Internal server error" });
185 | }
186 | });
187 |
188 | // Update user's Address
189 | // Update user's address
190 | router.patch("/:userID/address", async (req, res) => {
191 | try {
192 | const { userID } = req.params;
193 | const { addressType, updatedAddress } = req.body;
194 |
195 | if (!addressType || !updatedAddress) {
196 | return res.status(400).json({ error: "Missing required fields!" });
197 | }
198 |
199 | const user = await User.findOne({ userID: userID });
200 |
201 | if (!user) {
202 | return res.status(404).json({ error: "User not found" });
203 | }
204 | if (addressType === "presentAddress") user.presentAddress = updatedAddress;
205 | else user.permanentAddress = updatedAddress;
206 |
207 | await user.save();
208 | res.status(200).json(user[addressType]);
209 |
210 | } catch (error) {
211 | res.status(500).json({ error: "Internal server error" });
212 | }
213 | });
214 |
215 |
216 |
217 |
218 | // Add education information
219 | router.post("/:userID/education", async (req, res) => {
220 | try {
221 | const { degree, institution, start, end, status } = req.body;
222 |
223 | if (!degree || !institution || !start || !end || !status) {
224 | return res.status(400).json({ error: "Missing required fields!" });
225 | }
226 |
227 | const user = await User.findOne({ userID: req.params.userID });
228 | if (!user) {
229 | return res.status(404).json({ error: "User not found" });
230 | }
231 |
232 | user.education.push({ degree, institution, start, end, status });
233 | await user.save();
234 |
235 | res.status(201).json(user.education);
236 |
237 | } catch (error) {
238 | res.status(500).json({ error: "Internal server error" });
239 | }
240 | });
241 |
242 | // Update education information
243 | router.patch("/:userID/education/:educationID", async (req, res) => {
244 | try {
245 | const { degree, institution, start, end, status } = req.body;
246 |
247 | if (!degree || !institution || !start || !end || !status) {
248 | return res.status(400).json({ error: "Missing required fields!" });
249 | }
250 |
251 | const user = await User.findOne({ userID: req.params.userID });
252 | if (!user) {
253 | return res.status(404).json({ error: "User not found" });
254 | }
255 |
256 | const educationIndex = user.education.findIndex(edu => edu._id.toString() === req.params.educationID);
257 | if (educationIndex === -1) {
258 | return res.status(404).json({ error: "Education not found" });
259 | }
260 |
261 | user.education[educationIndex] = { degree, institution, start, end, status };
262 | await user.save();
263 |
264 | res.status(200).json(user.education);
265 |
266 | } catch (error) {
267 | res.status(500).json({ error: "Internal server error" });
268 | }
269 | });
270 |
271 |
272 |
273 | export { router as usersRoute }
--------------------------------------------------------------------------------