[
  {
    "path": ".gitignore",
    "content": "dev.js\nnode_modules/"
  },
  {
    "path": "README.md",
    "content": "# Instagram-clone-MERN-Stack\n\nThis Repo has complete code of my MERN stack series on YouTube https://www.youtube.com/playlist?list=PLB97yPrFwo5g0FQr4rqImKa55F_aPiQWk\n"
  },
  {
    "path": "app.js",
    "content": "const express = require('express')\nconst app = express()\nconst mongoose  = require('mongoose')\nconst PORT = process.env.PORT || 5000\nconst {MONGOURI} = require('./config/keys')\n\n\nmongoose.connect(MONGOURI,{\n    useNewUrlParser:true,\n    useUnifiedTopology: true\n\n})\nmongoose.connection.on('connected',()=>{\n    console.log(\"conneted to mongo yeahh\")\n})\nmongoose.connection.on('error',(err)=>{\n    console.log(\"err connecting\",err)\n})\n\nrequire('./models/user')\nrequire('./models/post')\n\napp.use(express.json())\napp.use(require('./routes/auth'))\napp.use(require('./routes/post'))\napp.use(require('./routes/user'))\n\n\nif(process.env.NODE_ENV==\"production\"){\n    app.use(express.static('client/build'))\n    const path = require('path')\n    app.get(\"*\",(req,res)=>{\n        res.sendFile(path.resolve(__dirname,'client','build','index.html'))\n    })\n}\n\napp.listen(PORT,()=>{\n    console.log(\"server is running on\",PORT)\n})\n\n"
  },
  {
    "path": "client/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n"
  },
  {
    "path": "client/README.md",
    "content": "This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).\n\n## Available Scripts\n\nIn the project directory, you can run:\n\n### `npm start`\n\nRuns the app in the development mode.<br />\nOpen [http://localhost:3000](http://localhost:3000) to view it in the browser.\n\nThe page will reload if you make edits.<br />\nYou will also see any lint errors in the console.\n\n### `npm test`\n\nLaunches the test runner in the interactive watch mode.<br />\nSee the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.\n\n### `npm run build`\n\nBuilds the app for production to the `build` folder.<br />\nIt correctly bundles React in production mode and optimizes the build for the best performance.\n\nThe build is minified and the filenames include the hashes.<br />\nYour app is ready to be deployed!\n\nSee the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.\n\n### `npm run eject`\n\n**Note: this is a one-way operation. Once you `eject`, you can’t go back!**\n\nIf you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.\n\nInstead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.\n\nYou don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.\n\n## Learn More\n\nYou can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).\n\nTo learn React, check out the [React documentation](https://reactjs.org/).\n\n### Code Splitting\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting\n\n### Analyzing the Bundle Size\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size\n\n### Making a Progressive Web App\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app\n\n### Advanced Configuration\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration\n\n### Deployment\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/deployment\n\n### `npm run build` fails to minify\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify\n"
  },
  {
    "path": "client/package.json",
    "content": "{\n  \"name\": \"client\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"proxy\": \"http://localhost:5000\",\n  \"dependencies\": {\n    \"@testing-library/jest-dom\": \"^4.2.4\",\n    \"@testing-library/react\": \"^9.5.0\",\n    \"@testing-library/user-event\": \"^7.2.1\",\n    \"materialize-css\": \"^1.0.0-rc.2\",\n    \"react\": \"^16.13.1\",\n    \"react-dom\": \"^16.13.1\",\n    \"react-router-dom\": \"^5.1.2\",\n    \"react-scripts\": \"3.4.1\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test\",\n    \"eject\": \"react-scripts eject\"\n  },\n  \"eslintConfig\": {\n    \"extends\": \"react-app\"\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  }\n}\n"
  },
  {
    "path": "client/public/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n      <!-- Compiled and minified CSS -->\n      <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n      <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css\">\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "client/public/manifest.json",
    "content": "{\n  \"short_name\": \"React App\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n      \"sizes\": \"64x64 32x32 24x24 16x16\",\n      \"type\": \"image/x-icon\"\n    },\n    {\n      \"src\": \"logo192.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"192x192\"\n    },\n    {\n      \"src\": \"logo512.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"512x512\"\n    }\n  ],\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "client/public/robots.txt",
    "content": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\nDisallow:\n"
  },
  {
    "path": "client/src/App.css",
    "content": "@import url('https://fonts.googleapis.com/css2?family=Grand+Hotel&display=swap');\n\na{\n  color: black !important;\n}\n\n.brand-logo,h2{\n  font-family: 'Grand Hotel', cursive;\n}\n\n.mycard{\n  margin-top: 30px;\n}\n.auth-card{\n  padding: 20px;\n  text-align: center;\n  max-width: 400px;\n  margin: 10px auto;\n}\n\n.input-field input[type=text]:focus {\n  border-bottom: 1px solid rgb(8, 93, 252) !important;\n  box-shadow: 0 1px 0 0 rgb(8, 93, 252)  !important;\n}\n.input-field input[type=password]:focus {\n  border-bottom: 1px solid rgb(8, 93, 252) !important;\n  box-shadow: 0 1px 0 0 rgb(8, 93, 252)  !important;\n}\n\n.gallery{\n  display: flex;\n  flex-wrap: wrap;\n  justify-content: space-around;\n}\n\n.item{\n  width: 30%;\n}\n\n.home-card{\n  max-width: 500px;\n  height: max-content;\n  margin: 26px auto;\n  \n}\n.collection-item{\n  width: 100%;\n}\n\n\n#toast-container{\n  top:30px !important;\n  right: 20px !important;\n  left: auto !important;\n}\n\n\n.material-icons:hover{\n  cursor: pointer;\n}"
  },
  {
    "path": "client/src/App.js",
    "content": "import React,{useEffect,createContext,useReducer,useContext} from 'react';\nimport NavBar from './components/Navbar'\nimport \"./App.css\"\nimport {BrowserRouter,Route,Switch,useHistory} from 'react-router-dom'\nimport Home from './components/screens/Home'\nimport Signin from './components/screens/SignIn'\nimport Profile from './components/screens/Profile'\nimport Signup from './components/screens/Signup'\nimport CreatePost from './components/screens/CreatePost'\nimport {reducer,initialState} from './reducers/userReducer'\nimport UserProfile from './components/screens/UserProfile'\nimport SubscribedUserPosts from './components/screens/SubscribesUserPosts'\nimport Reset from './components/screens/Reset'\nimport NewPassword from './components/screens/Newpassword'\nexport const UserContext = createContext()\n\n\nconst Routing = ()=>{\n  const history = useHistory()\n  const {state,dispatch} = useContext(UserContext)\n  useEffect(()=>{\n    const user = JSON.parse(localStorage.getItem(\"user\"))\n    if(user){\n      dispatch({type:\"USER\",payload:user})\n    }else{\n      if(!history.location.pathname.startsWith('/reset'))\n           history.push('/signin')\n    }\n  },[])\n  return(\n    <Switch>\n      <Route exact path=\"/\" >\n      <Home />\n      </Route>\n      <Route path=\"/signin\">\n        <Signin />\n      </Route>\n      <Route path=\"/signup\">\n        <Signup />\n      </Route>\n      <Route exact path=\"/profile\">\n        <Profile />\n      </Route>\n      <Route path=\"/create\">\n        <CreatePost/>\n      </Route>\n      <Route path=\"/profile/:userid\">\n        <UserProfile />\n      </Route>\n      <Route path=\"/myfollowingpost\">\n        <SubscribedUserPosts />\n      </Route>\n      <Route exact path=\"/reset\">\n        <Reset/>\n      </Route>\n      <Route path=\"/reset/:token\">\n        <NewPassword />\n      </Route>\n      \n    </Switch>\n  )\n}\n\nfunction App() {\n  const [state,dispatch] = useReducer(reducer,initialState)\n  return (\n    <UserContext.Provider value={{state,dispatch}}>\n    <BrowserRouter>\n      <NavBar />\n      <Routing />\n      \n    </BrowserRouter>\n    </UserContext.Provider>\n  );\n}\n\nexport default App;\n"
  },
  {
    "path": "client/src/App.test.js",
    "content": "import React from 'react';\nimport { render } from '@testing-library/react';\nimport App from './App';\n\ntest('renders learn react link', () => {\n  const { getByText } = render(<App />);\n  const linkElement = getByText(/learn react/i);\n  expect(linkElement).toBeInTheDocument();\n});\n"
  },
  {
    "path": "client/src/components/Navbar.js",
    "content": "import React,{useContext,useRef,useEffect,useState} from 'react'\nimport {Link ,useHistory} from 'react-router-dom'\nimport {UserContext} from '../App'\nimport M from 'materialize-css'\nconst NavBar = ()=>{\n    const  searchModal = useRef(null)\n    const [search,setSearch] = useState('')\n    const [userDetails,setUserDetails] = useState([])\n     const {state,dispatch} = useContext(UserContext)\n     const history = useHistory()\n     useEffect(()=>{\n         M.Modal.init(searchModal.current)\n     },[])\n     const renderList = ()=>{\n       if(state){\n           return [\n            <li key=\"1\"><i  data-target=\"modal1\" className=\"large material-icons modal-trigger\" style={{color:\"black\"}}>search</i></li>,\n            <li key=\"2\"><Link to=\"/profile\">Profile</Link></li>,\n            <li key=\"3\"><Link to=\"/create\">Create Post</Link></li>,\n            <li key=\"4\"><Link to=\"/myfollowingpost\">My following Posts</Link></li>,\n            <li  key=\"5\">\n             <button className=\"btn #c62828 red darken-3\"\n            onClick={()=>{\n              localStorage.clear()\n              dispatch({type:\"CLEAR\"})\n              history.push('/signin')\n            }}\n            >\n                Logout\n            </button>\n            </li>\n         \n            \n           ]\n       }else{\n         return [\n          <li  key=\"6\"><Link to=\"/signin\">Signin</Link></li>,\n          <li  key=\"7\"><Link to=\"/signup\">Signup</Link></li>\n         \n         ]\n       }\n     }\n\n\n     const fetchUsers = (query)=>{\n        setSearch(query)\n        fetch('/search-users',{\n          method:\"post\",\n          headers:{\n            \"Content-Type\":\"application/json\"\n          },\n          body:JSON.stringify({\n            query\n          })\n        }).then(res=>res.json())\n        .then(results=>{\n          setUserDetails(results.user)\n        })\n     }\n    return(\n        <nav>\n        <div className=\"nav-wrapper white\">\n          <Link to={state?\"/\":\"/signin\"} className=\"brand-logo left\">Instagram</Link>\n          <ul id=\"nav-mobile\" className=\"right\">\n             {renderList()}\n  \n          </ul>\n        </div>\n        <div id=\"modal1\" class=\"modal\" ref={searchModal} style={{color:\"black\"}}>\n          <div className=\"modal-content\">\n          <input\n            type=\"text\"\n            placeholder=\"search users\"\n            value={search}\n            onChange={(e)=>fetchUsers(e.target.value)}\n            />\n             <ul className=\"collection\">\n               {userDetails.map(item=>{\n                 return <Link to={item._id !== state._id ? \"/profile/\"+item._id:'/profile'} onClick={()=>{\n                   M.Modal.getInstance(searchModal.current).close()\n                   setSearch('')\n                 }}><li className=\"collection-item\">{item.email}</li></Link> \n               })}\n               \n              </ul>\n          </div>\n          <div className=\"modal-footer\">\n            <button className=\"modal-close waves-effect waves-green btn-flat\" onClick={()=>setSearch('')}>close</button>\n          </div>\n        </div>\n      </nav>\n    )\n}\n\n\nexport default NavBar"
  },
  {
    "path": "client/src/components/screens/CreatePost.js",
    "content": "import React,{useState,useEffect} from 'react'\nimport M from 'materialize-css'\nimport {useHistory} from 'react-router-dom'\nconst CretePost = ()=>{\n    const history = useHistory()\n    const [title,setTitle] = useState(\"\")\n    const [body,setBody] = useState(\"\")\n    const [image,setImage] = useState(\"\")\n    const [url,setUrl] = useState(\"\")\n    useEffect(()=>{\n       if(url){\n        fetch(\"/createpost\",{\n            method:\"post\",\n            headers:{\n                \"Content-Type\":\"application/json\",\n                \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n            },\n            body:JSON.stringify({\n                title,\n                body,\n                pic:url\n            })\n        }).then(res=>res.json())\n        .then(data=>{\n    \n           if(data.error){\n              M.toast({html: data.error,classes:\"#c62828 red darken-3\"})\n           }\n           else{\n               M.toast({html:\"Created post Successfully\",classes:\"#43a047 green darken-1\"})\n               history.push('/')\n           }\n        }).catch(err=>{\n            console.log(err)\n        })\n    }\n    },[url])\n  \n   const postDetails = ()=>{\n       const data = new FormData()\n       data.append(\"file\",image)\n       data.append(\"upload_preset\",\"new-insta\")\n       data.append(\"cloud_name\",\"cnq\")\n       fetch(\"https://api.cloudinary.com/v1_1/cnq/image/upload\",{\n           method:\"post\",\n           body:data\n       })\n       .then(res=>res.json())\n       .then(data=>{\n          setUrl(data.url)\n       })\n       .catch(err=>{\n           console.log(err)\n       })\n\n    \n   }\n \n\n   return(\n       <div className=\"card input-filed\"\n       style={{\n           margin:\"30px auto\",\n           maxWidth:\"500px\",\n           padding:\"20px\",\n           textAlign:\"center\"\n       }}\n       >\n           <input \n           type=\"text\"\n            placeholder=\"title\"\n            value={title}\n            onChange={(e)=>setTitle(e.target.value)}\n            />\n           <input\n            type=\"text\"\n             placeholder=\"body\"\n             value={body}\n            onChange={(e)=>setBody(e.target.value)}\n             />\n           <div className=\"file-field input-field\">\n            <div className=\"btn #64b5f6 blue darken-1\">\n                <span>Uplaod Image</span>\n                <input type=\"file\" onChange={(e)=>setImage(e.target.files[0])} />\n            </div>\n            <div className=\"file-path-wrapper\">\n                <input className=\"file-path validate\" type=\"text\" />\n            </div>\n            </div>\n            <button className=\"btn waves-effect waves-light #64b5f6 blue darken-1\"\n            onClick={()=>postDetails()}\n            \n            >\n                Submit post\n            </button>\n\n       </div>\n   )\n}\n\n\nexport default CretePost"
  },
  {
    "path": "client/src/components/screens/Home.js",
    "content": "import React,{useState,useEffect,useContext} from 'react'\nimport {UserContext} from '../../App'\nimport {Link} from 'react-router-dom'\nconst Home  = ()=>{\n    const [data,setData] = useState([])\n    const {state,dispatch} = useContext(UserContext)\n    useEffect(()=>{\n       fetch('/allpost',{\n           headers:{\n               \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n           }\n       }).then(res=>res.json())\n       .then(result=>{\n           console.log(result)\n           setData(result.posts)\n       })\n    },[])\n\n    const likePost = (id)=>{\n          fetch('/like',{\n              method:\"put\",\n              headers:{\n                  \"Content-Type\":\"application/json\",\n                  \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n              },\n              body:JSON.stringify({\n                  postId:id\n              })\n          }).then(res=>res.json())\n          .then(result=>{\n                   //   console.log(result)\n            const newData = data.map(item=>{\n                if(item._id==result._id){\n                    return result\n                }else{\n                    return item\n                }\n            })\n            setData(newData)\n          }).catch(err=>{\n              console.log(err)\n          })\n    }\n    const unlikePost = (id)=>{\n          fetch('/unlike',{\n              method:\"put\",\n              headers:{\n                  \"Content-Type\":\"application/json\",\n                  \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n              },\n              body:JSON.stringify({\n                  postId:id\n              })\n          }).then(res=>res.json())\n          .then(result=>{\n            //   console.log(result)\n            const newData = data.map(item=>{\n                if(item._id==result._id){\n                    return result\n                }else{\n                    return item\n                }\n            })\n            setData(newData)\n          }).catch(err=>{\n            console.log(err)\n        })\n    }\n\n    const makeComment = (text,postId)=>{\n          fetch('/comment',{\n              method:\"put\",\n              headers:{\n                  \"Content-Type\":\"application/json\",\n                  \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n              },\n              body:JSON.stringify({\n                  postId,\n                  text\n              })\n          }).then(res=>res.json())\n          .then(result=>{\n              console.log(result)\n              const newData = data.map(item=>{\n                if(item._id==result._id){\n                    return result\n                }else{\n                    return item\n                }\n             })\n            setData(newData)\n          }).catch(err=>{\n              console.log(err)\n          })\n    }\n\n    const deletePost = (postid)=>{\n        fetch(`/deletepost/${postid}`,{\n            method:\"delete\",\n            headers:{\n                Authorization:\"Bearer \"+localStorage.getItem(\"jwt\")\n            }\n        }).then(res=>res.json())\n        .then(result=>{\n            console.log(result)\n            const newData = data.filter(item=>{\n                return item._id !== result._id\n            })\n            setData(newData)\n        })\n    }\n   return (\n       <div className=\"home\">\n           {\n               data.map(item=>{\n                   return(\n                       <div className=\"card home-card\" key={item._id}>\n                            <h5 style={{padding:\"5px\"}}><Link to={item.postedBy._id !== state._id?\"/profile/\"+item.postedBy._id :\"/profile\"  }>{item.postedBy.name}</Link> {item.postedBy._id == state._id \n                            && <i className=\"material-icons\" style={{\n                                float:\"right\"\n                            }} \n                            onClick={()=>deletePost(item._id)}\n                            >delete</i>\n\n                            }</h5>\n                            <div className=\"card-image\">\n                                <img src={item.photo}/>\n                            </div>\n                            <div className=\"card-content\">\n                            <i className=\"material-icons\" style={{color:\"red\"}}>favorite</i>\n                            {item.likes.includes(state._id)\n                            ? \n                             <i className=\"material-icons\"\n                                    onClick={()=>{unlikePost(item._id)}}\n                              >thumb_down</i>\n                            : \n                            <i className=\"material-icons\"\n                            onClick={()=>{likePost(item._id)}}\n                            >thumb_up</i>\n                            }\n                            \n                           \n                                <h6>{item.likes.length} likes</h6>\n                                <h6>{item.title}</h6>\n                                <p>{item.body}</p>\n                                {\n                                    item.comments.map(record=>{\n                                        return(\n                                        <h6 key={record._id}><span style={{fontWeight:\"500\"}}>{record.postedBy.name}</span> {record.text}</h6>\n                                        )\n                                    })\n                                }\n                                <form onSubmit={(e)=>{\n                                    e.preventDefault()\n                                    makeComment(e.target[0].value,item._id)\n                                }}>\n                                  <input type=\"text\" placeholder=\"add a comment\" />  \n                                </form>\n                                \n                            </div>\n                        </div> \n                   )\n               })\n           }\n          \n          \n       </div>\n   )\n}\n\n\nexport default Home"
  },
  {
    "path": "client/src/components/screens/Newpassword.js",
    "content": "import React,{useState,useContext,} from 'react'\nimport {Link,useHistory,useParams} from 'react-router-dom'\nimport M from 'materialize-css'\nconst SignIn  = ()=>{\n    const history = useHistory()\n    const [password,setPasword] = useState(\"\")\n    const {token} = useParams()\n    console.log(token)\n    const PostData = ()=>{\n        fetch(\"/new-password\",{\n            method:\"post\",\n            headers:{\n                \"Content-Type\":\"application/json\"\n            },\n            body:JSON.stringify({\n                password,\n                token\n            })\n        }).then(res=>res.json())\n        .then(data=>{\n            console.log(data)\n           if(data.error){\n              M.toast({html: data.error,classes:\"#c62828 red darken-3\"})\n           }\n           else{\n\n               M.toast({html:data.message,classes:\"#43a047 green darken-1\"})\n               history.push('/signin')\n           }\n        }).catch(err=>{\n            console.log(err)\n        })\n    }\n   return (\n      <div className=\"mycard\">\n          <div className=\"card auth-card input-field\">\n            <h2>Instagram</h2>\n        \n            <input\n            type=\"password\"\n            placeholder=\"enter a new password\"\n            value={password}\n            onChange={(e)=>setPasword(e.target.value)}\n            />\n            <button className=\"btn waves-effect waves-light #64b5f6 blue darken-1\"\n            onClick={()=>PostData()}\n            >\n               Update password\n            </button>\n    \n        </div>\n      </div>\n   )\n}\n\n\nexport default SignIn"
  },
  {
    "path": "client/src/components/screens/Profile.js",
    "content": "import React,{useEffect,useState,useContext} from 'react'\nimport {UserContext} from '../../App'\n\nconst Profile  = ()=>{\n    const [mypics,setPics] = useState([])\n    const {state,dispatch} = useContext(UserContext)\n    const [image,setImage] = useState(\"\")\n    useEffect(()=>{\n       fetch('/mypost',{\n           headers:{\n               \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n           }\n       }).then(res=>res.json())\n       .then(result=>{\n           console.log(result)\n           setPics(result.mypost)\n       })\n    },[])\n    useEffect(()=>{\n       if(image){\n        const data = new FormData()\n        data.append(\"file\",image)\n        data.append(\"upload_preset\",\"insta-clone\")\n        data.append(\"cloud_name\",\"cnq\")\n        fetch(\"https://api.cloudinary.com/v1_1/cnq/image/upload\",{\n            method:\"post\",\n            body:data\n        })\n        .then(res=>res.json())\n        .then(data=>{\n    \n       \n           fetch('/updatepic',{\n               method:\"put\",\n               headers:{\n                   \"Content-Type\":\"application/json\",\n                   \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n               },\n               body:JSON.stringify({\n                   pic:data.url\n               })\n           }).then(res=>res.json())\n           .then(result=>{\n               console.log(result)\n               localStorage.setItem(\"user\",JSON.stringify({...state,pic:result.pic}))\n               dispatch({type:\"UPDATEPIC\",payload:result.pic})\n               //window.location.reload()\n           })\n       \n        })\n        .catch(err=>{\n            console.log(err)\n        })\n       }\n    },[image])\n    const updatePhoto = (file)=>{\n        setImage(file)\n    }\n   return (\n       <div style={{maxWidth:\"550px\",margin:\"0px auto\"}}>\n           <div style={{\n              margin:\"18px 0px\",\n               borderBottom:\"1px solid grey\"\n           }}>\n\n         \n           <div style={{\n               display:\"flex\",\n               justifyContent:\"space-around\",\n              \n           }}>\n               <div>\n                   <img style={{width:\"160px\",height:\"160px\",borderRadius:\"80px\"}}\n                   src={state?state.pic:\"loading\"}\n                   />\n                 \n               </div>\n               <div>\n                   <h4>{state?state.name:\"loading\"}</h4>\n                   <h5>{state?state.email:\"loading\"}</h5>\n                   <div style={{display:\"flex\",justifyContent:\"space-between\",width:\"108%\"}}>\n                       <h6>{mypics.length} posts</h6>\n                       <h6>{state?state.followers.length:\"0\"} followers</h6>\n                       <h6>{state?state.following.length:\"0\"} following</h6>\n                   </div>\n\n               </div>\n           </div>\n        \n            <div className=\"file-field input-field\" style={{margin:\"10px\"}}>\n            <div className=\"btn #64b5f6 blue darken-1\">\n                <span>Update pic</span>\n                <input type=\"file\" onChange={(e)=>updatePhoto(e.target.files[0])} />\n            </div>\n            <div className=\"file-path-wrapper\">\n                <input className=\"file-path validate\" type=\"text\" />\n            </div>\n            </div>\n            </div>      \n           <div className=\"gallery\">\n               {\n                   mypics.map(item=>{\n                       return(\n                        <img key={item._id} className=\"item\" src={item.photo} alt={item.title}/>  \n                       )\n                   })\n               }\n\n           \n           </div>\n       </div>\n   )\n}\n\n\nexport default Profile"
  },
  {
    "path": "client/src/components/screens/Reset.js",
    "content": "import React,{useState,useContext,} from 'react'\nimport {Link,useHistory} from 'react-router-dom'\nimport M from 'materialize-css'\nconst Reset  = ()=>{\n    const history = useHistory()\n    const [email,setEmail] = useState(\"\")\n    const PostData = ()=>{\n        if(!/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test(email)){\n            M.toast({html: \"invalid email\",classes:\"#c62828 red darken-3\"})\n            return\n        }\n        fetch('/reset-password',{\n            method:\"post\",\n            headers:{\n                \"Content-Type\":\"application/json\"\n            },\n            body:JSON.stringify({\n                email\n            })\n        }).then(res=>res.json())\n        .then(data=>{\n           if(data.error){\n              M.toast({html: data.error,classes:\"#c62828 red darken-3\"})\n           }\n           else{\n               M.toast({html:data.message,classes:\"#43a047 green darken-1\"})\n               history.push('/signin')\n           }\n        }).catch(err=>{\n            console.log(err)\n        })\n    }\n   return (\n      <div className=\"mycard\">\n          <div className=\"card auth-card input-field\">\n            <h2>Instagram</h2>\n            <input\n            type=\"text\"\n            placeholder=\"email\"\n            value={email}\n            onChange={(e)=>setEmail(e.target.value)}\n            />\n            <button className=\"btn waves-effect waves-light #64b5f6 blue darken-1\"\n            onClick={()=>PostData()}\n            >\n               reset password\n            </button>\n            \n    \n        </div>\n      </div>\n   )\n}\n\n\nexport default Reset"
  },
  {
    "path": "client/src/components/screens/SignIn.js",
    "content": "import React,{useState,useContext,} from 'react'\nimport {Link,useHistory} from 'react-router-dom'\nimport {UserContext} from '../../App'\nimport M from 'materialize-css'\nconst SignIn  = ()=>{\n    const {state,dispatch} = useContext(UserContext)\n    const history = useHistory()\n    const [password,setPasword] = useState(\"\")\n    const [email,setEmail] = useState(\"\")\n    const PostData = ()=>{\n        if(!/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test(email)){\n            M.toast({html: \"invalid email\",classes:\"#c62828 red darken-3\"})\n            return\n        }\n        fetch(\"/signin\",{\n            method:\"post\",\n            headers:{\n                \"Content-Type\":\"application/json\"\n            },\n            body:JSON.stringify({\n                password,\n                email\n            })\n        }).then(res=>res.json())\n        .then(data=>{\n            console.log(data)\n           if(data.error){\n              M.toast({html: data.error,classes:\"#c62828 red darken-3\"})\n           }\n           else{\n               localStorage.setItem(\"jwt\",data.token)\n               localStorage.setItem(\"user\",JSON.stringify(data.user))\n               dispatch({type:\"USER\",payload:data.user})\n               M.toast({html:\"signedin success\",classes:\"#43a047 green darken-1\"})\n               history.push('/')\n           }\n        }).catch(err=>{\n            console.log(err)\n        })\n    }\n   return (\n      <div className=\"mycard\">\n          <div className=\"card auth-card input-field\">\n            <h2>Instagram</h2>\n            <input\n            type=\"text\"\n            placeholder=\"email\"\n            value={email}\n            onChange={(e)=>setEmail(e.target.value)}\n            />\n            <input\n            type=\"password\"\n            placeholder=\"password\"\n            value={password}\n            onChange={(e)=>setPasword(e.target.value)}\n            />\n            <button className=\"btn waves-effect waves-light #64b5f6 blue darken-1\"\n            onClick={()=>PostData()}\n            >\n                Login\n            </button>\n            <h5>\n                <Link to=\"/signup\">Dont have an account ?</Link>\n            </h5>\n            <h6>\n                <Link to=\"/reset\">Forgot password ?</Link>\n            </h6>\n    \n        </div>\n      </div>\n   )\n}\n\n\nexport default SignIn"
  },
  {
    "path": "client/src/components/screens/Signup.js",
    "content": "import React,{useState,useEffect} from 'react'\nimport {Link,useHistory} from 'react-router-dom'\nimport M from 'materialize-css'\nconst SignIn  = ()=>{\n    const history = useHistory()\n    const [name,setName] = useState(\"\")\n    const [password,setPasword] = useState(\"\")\n    const [email,setEmail] = useState(\"\")\n    const [image,setImage] = useState(\"\")\n    const [url,setUrl] = useState(undefined)\n    useEffect(()=>{\n        if(url){\n            uploadFields()\n        }\n    },[url])\n    const uploadPic = ()=>{\n        const data = new FormData()\n        data.append(\"file\",image)\n        data.append(\"upload_preset\",\"new-insta\")\n        data.append(\"cloud_name\",\"cnq\")\n        fetch(\"https://api.cloudinary.com/v1_1/cnq/image/upload\",{\n            method:\"post\",\n            body:data\n        })\n        .then(res=>res.json())\n        .then(data=>{\n           setUrl(data.url)\n        })\n        .catch(err=>{\n            console.log(err)\n        })\n    }\n    const uploadFields = ()=>{\n        if(!/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test(email)){\n            M.toast({html: \"invalid email\",classes:\"#c62828 red darken-3\"})\n            return\n        }\n        fetch(\"/signup\",{\n            method:\"post\",\n            headers:{\n                \"Content-Type\":\"application/json\"\n            },\n            body:JSON.stringify({\n                name,\n                password,\n                email,\n                pic:url\n            })\n        }).then(res=>res.json())\n        .then(data=>{\n           if(data.error){\n              M.toast({html: data.error,classes:\"#c62828 red darken-3\"})\n           }\n           else{\n               M.toast({html:data.message,classes:\"#43a047 green darken-1\"})\n               history.push('/signin')\n           }\n        }).catch(err=>{\n            console.log(err)\n        })\n    }\n    const PostData = ()=>{\n        if(image){\n            uploadPic()\n        }else{\n            uploadFields()\n        }\n       \n    }\n\n   return (\n      <div className=\"mycard\">\n          <div className=\"card auth-card input-field\">\n            <h2>Instagram</h2>\n            <input\n            type=\"text\"\n            placeholder=\"name\"\n            value={name}\n            onChange={(e)=>setName(e.target.value)}\n            />\n            <input\n            type=\"text\"\n            placeholder=\"email\"\n            value={email}\n            onChange={(e)=>setEmail(e.target.value)}\n            />\n            <input\n            type=\"password\"\n            placeholder=\"password\"\n            value={password}\n            onChange={(e)=>setPasword(e.target.value)}\n            />\n            <div className=\"file-field input-field\">\n            <div className=\"btn #64b5f6 blue darken-1\">\n                <span>Upload pic</span>\n                <input type=\"file\" onChange={(e)=>setImage(e.target.files[0])} />\n            </div>\n            <div className=\"file-path-wrapper\">\n                <input className=\"file-path validate\" type=\"text\" />\n            </div>\n            </div>\n            <button className=\"btn waves-effect waves-light #64b5f6 blue darken-1\"\n            onClick={()=>PostData()}\n            >\n                SignUP\n            </button>\n            <h5>\n                <Link to=\"/signin\">Already have an account ?</Link>\n            </h5>\n             \n               \n         \n            \n    \n        </div>\n      </div>\n   )\n}\n\n\nexport default SignIn"
  },
  {
    "path": "client/src/components/screens/SubscribesUserPosts.js",
    "content": "import React,{useState,useEffect,useContext} from 'react'\nimport {UserContext} from '../../App'\nimport {Link} from 'react-router-dom'\nconst Home  = ()=>{\n    const [data,setData] = useState([])\n    const {state,dispatch} = useContext(UserContext)\n    useEffect(()=>{\n       fetch('/getsubpost',{\n           headers:{\n               \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n           }\n       }).then(res=>res.json())\n       .then(result=>{\n           console.log(result)\n           setData(result.posts)\n       })\n    },[])\n\n    const likePost = (id)=>{\n          fetch('/like',{\n              method:\"put\",\n              headers:{\n                  \"Content-Type\":\"application/json\",\n                  \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n              },\n              body:JSON.stringify({\n                  postId:id\n              })\n          }).then(res=>res.json())\n          .then(result=>{\n                   //   console.log(result)\n            const newData = data.map(item=>{\n                if(item._id==result._id){\n                    return result\n                }else{\n                    return item\n                }\n            })\n            setData(newData)\n          }).catch(err=>{\n              console.log(err)\n          })\n    }\n    const unlikePost = (id)=>{\n          fetch('/unlike',{\n              method:\"put\",\n              headers:{\n                  \"Content-Type\":\"application/json\",\n                  \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n              },\n              body:JSON.stringify({\n                  postId:id\n              })\n          }).then(res=>res.json())\n          .then(result=>{\n            //   console.log(result)\n            const newData = data.map(item=>{\n                if(item._id==result._id){\n                    return result\n                }else{\n                    return item\n                }\n            })\n            setData(newData)\n          }).catch(err=>{\n            console.log(err)\n        })\n    }\n\n    const makeComment = (text,postId)=>{\n          fetch('/comment',{\n              method:\"put\",\n              headers:{\n                  \"Content-Type\":\"application/json\",\n                  \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n              },\n              body:JSON.stringify({\n                  postId,\n                  text\n              })\n          }).then(res=>res.json())\n          .then(result=>{\n              console.log(result)\n              const newData = data.map(item=>{\n                if(item._id==result._id){\n                    return result\n                }else{\n                    return item\n                }\n             })\n            setData(newData)\n          }).catch(err=>{\n              console.log(err)\n          })\n    }\n\n    const deletePost = (postid)=>{\n        fetch(`/deletepost/${postid}`,{\n            method:\"delete\",\n            headers:{\n                Authorization:\"Bearer \"+localStorage.getItem(\"jwt\")\n            }\n        }).then(res=>res.json())\n        .then(result=>{\n            console.log(result)\n            const newData = data.filter(item=>{\n                return item._id !== result._id\n            })\n            setData(newData)\n        })\n    }\n   return (\n       <div className=\"home\">\n           {\n               data.map(item=>{\n                   return(\n                       <div className=\"card home-card\" key={item._id}>\n                            <h5 style={{padding:\"5px\"}}><Link to={item.postedBy._id !== state._id?\"/profile/\"+item.postedBy._id :\"/profile\"  }>{item.postedBy.name}</Link> {item.postedBy._id == state._id \n                            && <i className=\"material-icons\" style={{\n                                float:\"right\"\n                            }} \n                            onClick={()=>deletePost(item._id)}\n                            >delete</i>\n\n                            }</h5>\n                            <div className=\"card-image\">\n                                <img src={item.photo}/>\n                            </div>\n                            <div className=\"card-content\">\n                            <i className=\"material-icons\" style={{color:\"red\"}}>favorite</i>\n                            {item.likes.includes(state._id)\n                            ? \n                             <i className=\"material-icons\"\n                                    onClick={()=>{unlikePost(item._id)}}\n                              >thumb_down</i>\n                            : \n                            <i className=\"material-icons\"\n                            onClick={()=>{likePost(item._id)}}\n                            >thumb_up</i>\n                            }\n                            \n                           \n                                <h6>{item.likes.length} likes</h6>\n                                <h6>{item.title}</h6>\n                                <p>{item.body}</p>\n                                {\n                                    item.comments.map(record=>{\n                                        return(\n                                        <h6 key={record._id}><span style={{fontWeight:\"500\"}}>{record.postedBy.name}</span> {record.text}</h6>\n                                        )\n                                    })\n                                }\n                                <form onSubmit={(e)=>{\n                                    e.preventDefault()\n                                    makeComment(e.target[0].value,item._id)\n                                }}>\n                                  <input type=\"text\" placeholder=\"add a comment\" />  \n                                </form>\n                                \n                            </div>\n                        </div> \n                   )\n               })\n           }\n          \n          \n       </div>\n   )\n}\n\n\nexport default Home"
  },
  {
    "path": "client/src/components/screens/UserProfile.js",
    "content": "import React,{useEffect,useState,useContext} from 'react'\nimport {UserContext} from '../../App'\nimport {useParams} from 'react-router-dom'\nconst Profile  = ()=>{\n    const [userProfile,setProfile] = useState(null)\n    \n    const {state,dispatch} = useContext(UserContext)\n    const {userid} = useParams()\n    const [showfollow,setShowFollow] = useState(state?!state.following.includes(userid):true)\n    useEffect(()=>{\n       fetch(`/user/${userid}`,{\n           headers:{\n               \"Authorization\":\"Bearer \"+localStorage.getItem(\"jwt\")\n           }\n       }).then(res=>res.json())\n       .then(result=>{\n           //console.log(result)\n         \n            setProfile(result)\n       })\n    },[])\n\n\n    const followUser = ()=>{\n        fetch('/follow',{\n            method:\"put\",\n            headers:{\n                \"Content-Type\":\"application/json\",\n                \"Authorization\":\"Bearer \"+localStorage.getItem('jwt')\n            },\n            body:JSON.stringify({\n                followId:userid\n            })\n        }).then(res=>res.json())\n        .then(data=>{\n        \n            dispatch({type:\"UPDATE\",payload:{following:data.following,followers:data.followers}})\n             localStorage.setItem(\"user\",JSON.stringify(data))\n             setProfile((prevState)=>{\n                 return {\n                     ...prevState,\n                     user:{\n                         ...prevState.user,\n                         followers:[...prevState.user.followers,data._id]\n                        }\n                 }\n             })\n             setShowFollow(false)\n        })\n    }\n    const unfollowUser = ()=>{\n        fetch('/unfollow',{\n            method:\"put\",\n            headers:{\n                \"Content-Type\":\"application/json\",\n                \"Authorization\":\"Bearer \"+localStorage.getItem('jwt')\n            },\n            body:JSON.stringify({\n                unfollowId:userid\n            })\n        }).then(res=>res.json())\n        .then(data=>{\n            \n            dispatch({type:\"UPDATE\",payload:{following:data.following,followers:data.followers}})\n             localStorage.setItem(\"user\",JSON.stringify(data))\n            \n             setProfile((prevState)=>{\n                const newFollower = prevState.user.followers.filter(item=>item != data._id )\n                 return {\n                     ...prevState,\n                     user:{\n                         ...prevState.user,\n                         followers:newFollower\n                        }\n                 }\n             })\n             setShowFollow(true)\n             \n        })\n    }\n   return (\n       <>\n       {userProfile ?\n       <div style={{maxWidth:\"550px\",margin:\"0px auto\"}}>\n           <div style={{\n               display:\"flex\",\n               justifyContent:\"space-around\",\n               margin:\"18px 0px\",\n               borderBottom:\"1px solid grey\"\n           }}>\n               <div>\n                   <img style={{width:\"160px\",height:\"160px\",borderRadius:\"80px\"}}\n                   src={userProfile.user.pic}\n                   />\n               </div>\n               <div>\n                   <h4>{userProfile.user.name}</h4>\n                   <h5>{userProfile.user.email}</h5>\n                   <div style={{display:\"flex\",justifyContent:\"space-between\",width:\"108%\"}}>\n                       <h6>{userProfile.posts.length} posts</h6>\n                       <h6>{userProfile.user.followers.length} followers</h6>\n                       <h6>{userProfile.user.following.length} following</h6>\n                   </div>\n                   {showfollow?\n                   <button style={{\n                       margin:\"10px\"\n                   }} className=\"btn waves-effect waves-light #64b5f6 blue darken-1\"\n                    onClick={()=>followUser()}\n                    >\n                        Follow\n                    </button>\n                    : \n                    <button\n                    style={{\n                        margin:\"10px\"\n                    }}\n                    className=\"btn waves-effect waves-light #64b5f6 blue darken-1\"\n                    onClick={()=>unfollowUser()}\n                    >\n                        UnFollow\n                    </button>\n                    }\n                   \n                  \n\n               </div>\n           </div>\n     \n           <div className=\"gallery\">\n               {\n                   userProfile.posts.map(item=>{\n                       return(\n                        <img key={item._id} className=\"item\" src={item.photo} alt={item.title}/>  \n                       )\n                   })\n               }\n\n           \n           </div>\n       </div>\n       \n       \n       : <h2>loading...!</h2>}\n       \n       </>\n   )\n}\n\n\nexport default Profile"
  },
  {
    "path": "client/src/index.css",
    "content": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n    monospace;\n}\n"
  },
  {
    "path": "client/src/index.js",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nReactDOM.render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>,\n  document.getElementById('root')\n);\n\n// If you want your app to work offline and load faster, you can change\n// unregister() to register() below. Note this comes with some pitfalls.\n// Learn more about service workers: https://bit.ly/CRA-PWA\nserviceWorker.unregister();\n"
  },
  {
    "path": "client/src/reducers/userReducer.js",
    "content": "export const initialState = null\n\nexport const reducer = (state,action)=>{\n    if(action.type==\"USER\"){\n        return action.payload\n    }\n    if(action.type==\"CLEAR\"){\n        return null\n    }\n    if(action.type==\"UPDATE\"){\n        return {\n            ...state,\n            followers:action.payload.followers,\n            following:action.payload.following\n        }\n    }\n    if(action.type==\"UPDATEPIC\"){\n        return {\n            ...state,\n            pic:action.payload\n        }\n    }\n    return state\n} "
  },
  {
    "path": "client/src/serviceWorker.js",
    "content": "// This optional code is used to register a service worker.\n// register() is not called by default.\n\n// This lets the app load faster on subsequent visits in production, and gives\n// it offline capabilities. However, it also means that developers (and users)\n// will only see deployed updates on subsequent visits to a page, after all the\n// existing tabs open on the page have been closed, since previously cached\n// resources are updated in the background.\n\n// To learn more about the benefits of this model and instructions on how to\n// opt-in, read https://bit.ly/CRA-PWA\n\nconst isLocalhost = Boolean(\n  window.location.hostname === 'localhost' ||\n    // [::1] is the IPv6 localhost address.\n    window.location.hostname === '[::1]' ||\n    // 127.0.0.0/8 are considered localhost for IPv4.\n    window.location.hostname.match(\n      /^127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/\n    )\n);\n\nexport function register(config) {\n  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {\n    // The URL constructor is available in all browsers that support SW.\n    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);\n    if (publicUrl.origin !== window.location.origin) {\n      // Our service worker won't work if PUBLIC_URL is on a different origin\n      // from what our page is served on. This might happen if a CDN is used to\n      // serve assets; see https://github.com/facebook/create-react-app/issues/2374\n      return;\n    }\n\n    window.addEventListener('load', () => {\n      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;\n\n      if (isLocalhost) {\n        // This is running on localhost. Let's check if a service worker still exists or not.\n        checkValidServiceWorker(swUrl, config);\n\n        // Add some additional logging to localhost, pointing developers to the\n        // service worker/PWA documentation.\n        navigator.serviceWorker.ready.then(() => {\n          console.log(\n            'This web app is being served cache-first by a service ' +\n              'worker. To learn more, visit https://bit.ly/CRA-PWA'\n          );\n        });\n      } else {\n        // Is not localhost. Just register service worker\n        registerValidSW(swUrl, config);\n      }\n    });\n  }\n}\n\nfunction registerValidSW(swUrl, config) {\n  navigator.serviceWorker\n    .register(swUrl)\n    .then(registration => {\n      registration.onupdatefound = () => {\n        const installingWorker = registration.installing;\n        if (installingWorker == null) {\n          return;\n        }\n        installingWorker.onstatechange = () => {\n          if (installingWorker.state === 'installed') {\n            if (navigator.serviceWorker.controller) {\n              // At this point, the updated precached content has been fetched,\n              // but the previous service worker will still serve the older\n              // content until all client tabs are closed.\n              console.log(\n                'New content is available and will be used when all ' +\n                  'tabs for this page are closed. See https://bit.ly/CRA-PWA.'\n              );\n\n              // Execute callback\n              if (config && config.onUpdate) {\n                config.onUpdate(registration);\n              }\n            } else {\n              // At this point, everything has been precached.\n              // It's the perfect time to display a\n              // \"Content is cached for offline use.\" message.\n              console.log('Content is cached for offline use.');\n\n              // Execute callback\n              if (config && config.onSuccess) {\n                config.onSuccess(registration);\n              }\n            }\n          }\n        };\n      };\n    })\n    .catch(error => {\n      console.error('Error during service worker registration:', error);\n    });\n}\n\nfunction checkValidServiceWorker(swUrl, config) {\n  // Check if the service worker can be found. If it can't reload the page.\n  fetch(swUrl, {\n    headers: { 'Service-Worker': 'script' },\n  })\n    .then(response => {\n      // Ensure service worker exists, and that we really are getting a JS file.\n      const contentType = response.headers.get('content-type');\n      if (\n        response.status === 404 ||\n        (contentType != null && contentType.indexOf('javascript') === -1)\n      ) {\n        // No service worker found. Probably a different app. Reload the page.\n        navigator.serviceWorker.ready.then(registration => {\n          registration.unregister().then(() => {\n            window.location.reload();\n          });\n        });\n      } else {\n        // Service worker found. Proceed as normal.\n        registerValidSW(swUrl, config);\n      }\n    })\n    .catch(() => {\n      console.log(\n        'No internet connection found. App is running in offline mode.'\n      );\n    });\n}\n\nexport function unregister() {\n  if ('serviceWorker' in navigator) {\n    navigator.serviceWorker.ready\n      .then(registration => {\n        registration.unregister();\n      })\n      .catch(error => {\n        console.error(error.message);\n      });\n  }\n}\n"
  },
  {
    "path": "client/src/setupTests.js",
    "content": "// jest-dom adds custom jest matchers for asserting on DOM nodes.\n// allows you to do things like:\n// expect(element).toHaveTextContent(/react/i)\n// learn more: https://github.com/testing-library/jest-dom\nimport '@testing-library/jest-dom/extend-expect';\n"
  },
  {
    "path": "config/keys.js",
    "content": "if(process.env.NODE_ENV==='production'){\n    module.exports = require('./prod')\n}else{\n    module.exports = require('./dev')\n}"
  },
  {
    "path": "config/prod.js",
    "content": "module.exports={\n    MONGOURI:process.env.MOGOURI,\n    JWT_SECRET:process.env.JWT_SEC,\n    SENDGRID_API:process.env.SENDGRID_API,\n    EMAIL:process.env.EMAIL\n}"
  },
  {
    "path": "middleware/requireLogin.js",
    "content": "const jwt = require('jsonwebtoken')\nconst {JWT_SECRET} = require('../config/keys')\nconst mongoose = require('mongoose')\nconst User = mongoose.model(\"User\")\nmodule.exports = (req,res,next)=>{\n    const {authorization} = req.headers\n    //authorization === Bearer ewefwegwrherhe\n    if(!authorization){\n       return res.status(401).json({error:\"you must be logged in\"})\n    }\n    const token = authorization.replace(\"Bearer \",\"\")\n    jwt.verify(token,JWT_SECRET,(err,payload)=>{\n        if(err){\n         return   res.status(401).json({error:\"you must be logged in\"})\n        }\n\n        const {_id} = payload\n        User.findById(_id).then(userdata=>{\n            req.user = userdata\n            next()\n        })\n        \n        \n    })\n}"
  },
  {
    "path": "models/post.js",
    "content": "const mongoose = require('mongoose')\nconst {ObjectId} = mongoose.Schema.Types\nconst postSchema = new mongoose.Schema({\n    title:{\n        type:String,\n        required:true\n    },\n    body:{\n        type:String,\n        required:true\n    },\n    photo:{\n        type:String,\n        required:true\n    },\n    likes:[{type:ObjectId,ref:\"User\"}],\n    comments:[{\n        text:String,\n        postedBy:{type:ObjectId,ref:\"User\"}\n    }],\n    postedBy:{\n       type:ObjectId,\n       ref:\"User\"\n    }\n},{timestamps:true})\n\nmongoose.model(\"Post\",postSchema)"
  },
  {
    "path": "models/user.js",
    "content": "const mongoose = require('mongoose')\nconst {ObjectId} = mongoose.Schema.Types\nconst userSchema = new mongoose.Schema({\n    name:{\n        type:String,\n        required:true\n    },\n    email:{\n        type:String,\n        required:true\n    },\n    password:{\n        type:String,\n        required:true\n    },\n    resetToken:String,\n    expireToken:Date,\n    pic:{\n     type:String,\n     default:\"https://res.cloudinary.com/cnq/image/upload/v1586197723/noimage_d4ipmd.png\"\n    },\n    followers:[{type:ObjectId,ref:\"User\"}],\n    following:[{type:ObjectId,ref:\"User\"}]\n})\n\nmongoose.model(\"User\",userSchema)"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"server\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"app.js\",\n  \"scripts\": {\n    \"start\": \"node app.js\",\n    \"heroku-postbuild\": \"NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"bcryptjs\": \"^2.4.3\",\n    \"express\": \"^4.17.1\",\n    \"jsonwebtoken\": \"^8.5.1\",\n    \"mongoose\": \"^5.9.7\",\n    \"nodemailer\": \"^6.4.6\",\n    \"nodemailer-sendgrid-transport\": \"^0.2.0\"\n  }\n}\n"
  },
  {
    "path": "routes/auth.js",
    "content": "const express = require('express')\nconst router = express.Router()\nconst mongoose = require('mongoose')\nconst User = mongoose.model(\"User\")\nconst crypto = require('crypto')\nconst bcrypt = require('bcryptjs')\nconst jwt = require('jsonwebtoken')\nconst {JWT_SECRET} = require('../config/keys')\nconst requireLogin = require('../middleware/requireLogin')\nconst nodemailer = require('nodemailer')\nconst sendgridTransport = require('nodemailer-sendgrid-transport')\nconst {SENDGRID_API,EMAIL} = require('../config/keys')\n//\n\n\nconst transporter = nodemailer.createTransport(sendgridTransport({\n    auth:{\n        api_key:SENDGRID_API\n    }\n}))\n\nrouter.post('/signup',(req,res)=>{\n  const {name,email,password,pic} = req.body \n  if(!email || !password || !name){\n     return res.status(422).json({error:\"please add all the fields\"})\n  }\n  User.findOne({email:email})\n  .then((savedUser)=>{\n      if(savedUser){\n        return res.status(422).json({error:\"user already exists with that email\"})\n      }\n      bcrypt.hash(password,12)\n      .then(hashedpassword=>{\n            const user = new User({\n                email,\n                password:hashedpassword,\n                name,\n                pic\n            })\n    \n            user.save()\n            .then(user=>{\n                // transporter.sendMail({\n                //     to:user.email,\n                //     from:\"no-reply@insta.com\",\n                //     subject:\"signup success\",\n                //     html:\"<h1>welcome to instagram</h1>\"\n                // })\n                res.json({message:\"saved successfully\"})\n            })\n            .catch(err=>{\n                console.log(err)\n            })\n      })\n     \n  })\n  .catch(err=>{\n    console.log(err)\n  })\n})\n\n\nrouter.post('/signin',(req,res)=>{\n    const {email,password} = req.body\n    if(!email || !password){\n       return res.status(422).json({error:\"please add email or password\"})\n    }\n    User.findOne({email:email})\n    .then(savedUser=>{\n        if(!savedUser){\n           return res.status(422).json({error:\"Invalid Email or password\"})\n        }\n        bcrypt.compare(password,savedUser.password)\n        .then(doMatch=>{\n            if(doMatch){\n                // res.json({message:\"successfully signed in\"})\n               const token = jwt.sign({_id:savedUser._id},JWT_SECRET)\n               const {_id,name,email,followers,following,pic} = savedUser\n               res.json({token,user:{_id,name,email,followers,following,pic}})\n            }\n            else{\n                return res.status(422).json({error:\"Invalid Email or password\"})\n            }\n        })\n        .catch(err=>{\n            console.log(err)\n        })\n    })\n})\n\n\nrouter.post('/reset-password',(req,res)=>{\n     crypto.randomBytes(32,(err,buffer)=>{\n         if(err){\n             console.log(err)\n         }\n         const token = buffer.toString(\"hex\")\n         User.findOne({email:req.body.email})\n         .then(user=>{\n             if(!user){\n                 return res.status(422).json({error:\"User dont exists with that email\"})\n             }\n             user.resetToken = token\n             user.expireToken = Date.now() + 3600000\n             user.save().then((result)=>{\n                 transporter.sendMail({\n                     to:user.email,\n                     from:\"no-replay@insta.com\",\n                     subject:\"password reset\",\n                     html:`\n                     <p>You requested for password reset</p>\n                     <h5>click in this <a href=\"${EMAIL}/reset/${token}\">link</a> to reset password</h5>\n                     `\n                 })\n                 res.json({message:\"check your email\"})\n             })\n\n         })\n     })\n})\n\n\nrouter.post('/new-password',(req,res)=>{\n    const newPassword = req.body.password\n    const sentToken = req.body.token\n    User.findOne({resetToken:sentToken,expireToken:{$gt:Date.now()}})\n    .then(user=>{\n        if(!user){\n            return res.status(422).json({error:\"Try again session expired\"})\n        }\n        bcrypt.hash(newPassword,12).then(hashedpassword=>{\n           user.password = hashedpassword\n           user.resetToken = undefined\n           user.expireToken = undefined\n           user.save().then((saveduser)=>{\n               res.json({message:\"password updated success\"})\n           })\n        })\n    }).catch(err=>{\n        console.log(err)\n    })\n})\n\n\nmodule.exports = router"
  },
  {
    "path": "routes/post.js",
    "content": "const express = require('express')\nconst router = express.Router()\nconst mongoose = require('mongoose')\nconst requireLogin  = require('../middleware/requireLogin')\nconst Post =  mongoose.model(\"Post\")\n\n\nrouter.get('/allpost',requireLogin,(req,res)=>{\n    Post.find()\n    .populate(\"postedBy\",\"_id name\")\n    .populate(\"comments.postedBy\",\"_id name\")\n    .sort('-createdAt')\n    .then((posts)=>{\n        res.json({posts})\n    }).catch(err=>{\n        console.log(err)\n    })\n    \n})\n\nrouter.get('/getsubpost',requireLogin,(req,res)=>{\n\n    // if postedBy in following\n    Post.find({postedBy:{$in:req.user.following}})\n    .populate(\"postedBy\",\"_id name\")\n    .populate(\"comments.postedBy\",\"_id name\")\n    .sort('-createdAt')\n    .then(posts=>{\n        res.json({posts})\n    })\n    .catch(err=>{\n        console.log(err)\n    })\n})\n\nrouter.post('/createpost',requireLogin,(req,res)=>{\n    const {title,body,pic} = req.body \n    if(!title || !body || !pic){\n      return  res.status(422).json({error:\"Plase add all the fields\"})\n    }\n    req.user.password = undefined\n    const post = new Post({\n        title,\n        body,\n        photo:pic,\n        postedBy:req.user\n    })\n    post.save().then(result=>{\n        res.json({post:result})\n    })\n    .catch(err=>{\n        console.log(err)\n    })\n})\n\nrouter.get('/mypost',requireLogin,(req,res)=>{\n    Post.find({postedBy:req.user._id})\n    .populate(\"PostedBy\",\"_id name\")\n    .then(mypost=>{\n        res.json({mypost})\n    })\n    .catch(err=>{\n        console.log(err)\n    })\n})\n\nrouter.put('/like',requireLogin,(req,res)=>{\n    Post.findByIdAndUpdate(req.body.postId,{\n        $push:{likes:req.user._id}\n    },{\n        new:true\n    }).exec((err,result)=>{\n        if(err){\n            return res.status(422).json({error:err})\n        }else{\n            res.json(result)\n        }\n    })\n})\nrouter.put('/unlike',requireLogin,(req,res)=>{\n    Post.findByIdAndUpdate(req.body.postId,{\n        $pull:{likes:req.user._id}\n    },{\n        new:true\n    }).exec((err,result)=>{\n        if(err){\n            return res.status(422).json({error:err})\n        }else{\n            res.json(result)\n        }\n    })\n})\n\n\nrouter.put('/comment',requireLogin,(req,res)=>{\n    const comment = {\n        text:req.body.text,\n        postedBy:req.user._id\n    }\n    Post.findByIdAndUpdate(req.body.postId,{\n        $push:{comments:comment}\n    },{\n        new:true\n    })\n    .populate(\"comments.postedBy\",\"_id name\")\n    .populate(\"postedBy\",\"_id name\")\n    .exec((err,result)=>{\n        if(err){\n            return res.status(422).json({error:err})\n        }else{\n            res.json(result)\n        }\n    })\n})\n\nrouter.delete('/deletepost/:postId',requireLogin,(req,res)=>{\n    Post.findOne({_id:req.params.postId})\n    .populate(\"postedBy\",\"_id\")\n    .exec((err,post)=>{\n        if(err || !post){\n            return res.status(422).json({error:err})\n        }\n        if(post.postedBy._id.toString() === req.user._id.toString()){\n              post.remove()\n              .then(result=>{\n                  res.json(result)\n              }).catch(err=>{\n                  console.log(err)\n              })\n        }\n    })\n})\n\nmodule.exports = router"
  },
  {
    "path": "routes/user.js",
    "content": "const express = require('express')\nconst router = express.Router()\nconst mongoose = require('mongoose')\nconst requireLogin  = require('../middleware/requireLogin')\nconst Post =  mongoose.model(\"Post\")\nconst User = mongoose.model(\"User\")\n\n\nrouter.get('/user/:id',requireLogin,(req,res)=>{\n    User.findOne({_id:req.params.id})\n    .select(\"-password\")\n    .then(user=>{\n         Post.find({postedBy:req.params.id})\n         .populate(\"postedBy\",\"_id name\")\n         .exec((err,posts)=>{\n             if(err){\n                 return res.status(422).json({error:err})\n             }\n             res.json({user,posts})\n         })\n    }).catch(err=>{\n        return res.status(404).json({error:\"User not found\"})\n    })\n})\n\n\nrouter.put('/follow',requireLogin,(req,res)=>{\n    User.findByIdAndUpdate(req.body.followId,{\n        $push:{followers:req.user._id}\n    },{\n        new:true\n    },(err,result)=>{\n        if(err){\n            return res.status(422).json({error:err})\n        }\n      User.findByIdAndUpdate(req.user._id,{\n          $push:{following:req.body.followId}\n          \n      },{new:true}).select(\"-password\").then(result=>{\n          res.json(result)\n      }).catch(err=>{\n          return res.status(422).json({error:err})\n      })\n\n    }\n    )\n})\nrouter.put('/unfollow',requireLogin,(req,res)=>{\n    User.findByIdAndUpdate(req.body.unfollowId,{\n        $pull:{followers:req.user._id}\n    },{\n        new:true\n    },(err,result)=>{\n        if(err){\n            return res.status(422).json({error:err})\n        }\n      User.findByIdAndUpdate(req.user._id,{\n          $pull:{following:req.body.unfollowId}\n          \n      },{new:true}).select(\"-password\").then(result=>{\n          res.json(result)\n      }).catch(err=>{\n          return res.status(422).json({error:err})\n      })\n\n    }\n    )\n})\n\n\nrouter.put('/updatepic',requireLogin,(req,res)=>{\n    User.findByIdAndUpdate(req.user._id,{$set:{pic:req.body.pic}},{new:true},\n        (err,result)=>{\n         if(err){\n             return res.status(422).json({error:\"pic canot post\"})\n         }\n         res.json(result)\n    })\n})\n\n\n\nrouter.post('/search-users',(req,res)=>{\n    let userPattern = new RegExp(\"^\"+req.body.query)\n    User.find({email:{$regex:userPattern}})\n    .select(\"_id email\")\n    .then(user=>{\n        res.json({user})\n    }).catch(err=>{\n        console.log(err)\n    })\n\n})\n\n\n\nmodule.exports = router"
  }
]