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