[
  {
    "path": ".gitignore",
    "content": ".idea\nnode_modules\napi/uploads/*\n"
  },
  {
    "path": "api/index.js",
    "content": "const express = require('express');\nconst cors = require('cors');\nconst mongoose = require(\"mongoose\");\nconst User = require('./models/User');\nconst Post = require('./models/Post');\nconst bcrypt = require('bcryptjs');\nconst app = express();\nconst jwt = require('jsonwebtoken');\nconst cookieParser = require('cookie-parser');\nconst multer = require('multer');\nconst uploadMiddleware = multer({ dest: 'uploads/' });\nconst fs = require('fs');\n\nconst salt = bcrypt.genSaltSync(10);\nconst secret = 'asdfe45we45w345wegw345werjktjwertkj';\n\napp.use(cors({credentials:true,origin:'http://localhost:3000'}));\napp.use(express.json());\napp.use(cookieParser());\napp.use('/uploads', express.static(__dirname + '/uploads'));\n\nmongoose.connect('mongodb+srv://blog:RD8paskYC8Ayj09u@cluster0.pflplid.mongodb.net/?retryWrites=true&w=majority');\n\napp.post('/register', async (req,res) => {\n  const {username,password} = req.body;\n  try{\n    const userDoc = await User.create({\n      username,\n      password:bcrypt.hashSync(password,salt),\n    });\n    res.json(userDoc);\n  } catch(e) {\n    console.log(e);\n    res.status(400).json(e);\n  }\n});\n\napp.post('/login', async (req,res) => {\n  const {username,password} = req.body;\n  const userDoc = await User.findOne({username});\n  const passOk = bcrypt.compareSync(password, userDoc.password);\n  if (passOk) {\n    // logged in\n    jwt.sign({username,id:userDoc._id}, secret, {}, (err,token) => {\n      if (err) throw err;\n      res.cookie('token', token).json({\n        id:userDoc._id,\n        username,\n      });\n    });\n  } else {\n    res.status(400).json('wrong credentials');\n  }\n});\n\napp.get('/profile', (req,res) => {\n  const {token} = req.cookies;\n  jwt.verify(token, secret, {}, (err,info) => {\n    if (err) throw err;\n    res.json(info);\n  });\n});\n\napp.post('/logout', (req,res) => {\n  res.cookie('token', '').json('ok');\n});\n\napp.post('/post', uploadMiddleware.single('file'), async (req,res) => {\n  const {originalname,path} = req.file;\n  const parts = originalname.split('.');\n  const ext = parts[parts.length - 1];\n  const newPath = path+'.'+ext;\n  fs.renameSync(path, newPath);\n\n  const {token} = req.cookies;\n  jwt.verify(token, secret, {}, async (err,info) => {\n    if (err) throw err;\n    const {title,summary,content} = req.body;\n    const postDoc = await Post.create({\n      title,\n      summary,\n      content,\n      cover:newPath,\n      author:info.id,\n    });\n    res.json(postDoc);\n  });\n\n});\n\napp.put('/post',uploadMiddleware.single('file'), async (req,res) => {\n  let newPath = null;\n  if (req.file) {\n    const {originalname,path} = req.file;\n    const parts = originalname.split('.');\n    const ext = parts[parts.length - 1];\n    newPath = path+'.'+ext;\n    fs.renameSync(path, newPath);\n  }\n\n  const {token} = req.cookies;\n  jwt.verify(token, secret, {}, async (err,info) => {\n    if (err) throw err;\n    const {id,title,summary,content} = req.body;\n    const postDoc = await Post.findById(id);\n    const isAuthor = JSON.stringify(postDoc.author) === JSON.stringify(info.id);\n    if (!isAuthor) {\n      return res.status(400).json('you are not the author');\n    }\n    await postDoc.update({\n      title,\n      summary,\n      content,\n      cover: newPath ? newPath : postDoc.cover,\n    });\n\n    res.json(postDoc);\n  });\n\n});\n\napp.get('/post', async (req,res) => {\n  res.json(\n    await Post.find()\n      .populate('author', ['username'])\n      .sort({createdAt: -1})\n      .limit(20)\n  );\n});\n\napp.get('/post/:id', async (req, res) => {\n  const {id} = req.params;\n  const postDoc = await Post.findById(id).populate('author', ['username']);\n  res.json(postDoc);\n})\n\napp.listen(4000);\n//"
  },
  {
    "path": "api/models/Post.js",
    "content": "const mongoose = require('mongoose');\nconst {Schema,model} = mongoose;\n\nconst PostSchema = new Schema({\n  title:String,\n  summary:String,\n  content:String,\n  cover:String,\n  author:{type:Schema.Types.ObjectId, ref:'User'},\n}, {\n  timestamps: true,\n});\n\nconst PostModel = model('Post', PostSchema);\n\nmodule.exports = PostModel;"
  },
  {
    "path": "api/models/User.js",
    "content": "const mongoose = require('mongoose');\nconst {Schema, model} = mongoose;\n\nconst UserSchema = new Schema({\n  username: {type: String, required: true, min: 4, unique: true},\n  password: {type: String, required: true},\n});\n\nconst UserModel = model('User', UserSchema);\n\nmodule.exports = UserModel;"
  },
  {
    "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": "# Getting Started with Create React App\n\nThis 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### `yarn start`\n\nRuns the app in the development mode.\\\nOpen [http://localhost:3000](http://localhost:3000) to view it in your browser.\n\nThe page will reload when you make changes.\\\nYou may also see any lint errors in the console.\n\n### `yarn test`\n\nLaunches the test runner in the interactive watch mode.\\\nSee the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.\n\n### `yarn build`\n\nBuilds the app for production to the `build` folder.\\\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.\\\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### `yarn 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](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](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](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](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](https://facebook.github.io/create-react-app/docs/deployment)\n\n### `yarn 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](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  \"dependencies\": {\n    \"@testing-library/jest-dom\": \"^5.14.1\",\n    \"@testing-library/react\": \"^13.0.0\",\n    \"@testing-library/user-event\": \"^13.2.1\",\n    \"date-fns\": \"^2.29.3\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-quill\": \"^2.0.0\",\n    \"react-scripts\": \"5.0.1\",\n    \"web-vitals\": \"^2.1.0\"\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\": [\n      \"react-app\",\n      \"react-app/jest\"\n    ]\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    <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": "*{\n    box-sizing: border-box;\n}\na{\n    cursor: pointer;\n}\nbody{\n    color: #222;\n}\nimg{\n    max-width: 100%;\n}\nmain{\n    padding: 10px;\n    max-width: 960px;\n    margin: 0 auto;\n}\nheader{\n    display:flex;\n    justify-content:space-between;\n    margin-top: 20px;\n    margin-bottom: 50px;\n    align-items: center;\n}\nheader a{\n    text-decoration:none;\n    color: inherit;\n}\nheader a.logo{\n    font-weight: bold;\n    font-size: 1.5rem;\n}\nheader nav{\n    display:flex;\n    gap: 24px;\n}\n\ndiv.post{\n    display: grid;\n    grid-template-columns: 1fr;\n    gap: 20px;\n    margin-bottom: 30px;\n}\n@media screen and (min-width: 700px) {\n    div.post{\n        grid-template-columns: .9fr 1.1fr;\n    }\n}\n\ndiv.post div.texts h2{\n    margin:0;\n    font-size: 2rem;\n}\ndiv.post div.texts a{\n    text-decoration:none;\n    color: inherit;\n}\ndiv.post p.info{\n    margin:24px 0;\n    color: #888;\n    font-size:1rem;\n    font-weight: bold;\n    display: flex;\n    gap: 10px;\n}\ndiv.post p.info a.author{\n    color:#333;\n}\ndiv.post p.summary{\n    margin:10px 0;\n    line-height: 1.8rem;\n}\n\nform.login, form.register{\n    max-width: 400px;\n    margin: 0 auto;\n}\ninput{\n    display: block;\n    margin-bottom: 5px;\n    width: 100%;\n    padding: 5px 7px;\n    border: 2px solid #ddd;\n    border-radius: 5px;\n    background-color: #fff;\n}\nbutton{\n    cursor: pointer;\n    width: 100%;\n    display: block;\n    background-color: #555;\n    border:0;\n    color: #fff;\n    border-radius: 5px;\n    padding: 7px 0;\n}\nform.login h1, form.register h1{\n    text-align: center;\n}\n\ndiv.post-page div.image{\n    max-height:300px;\n    display: flex;\n    overflow:hidden;\n}\ndiv.post-page div.image img{\n    object-fit: cover;\n    object-position: center center;\n    width: 100%;\n}\ndiv.post-page a{\n    color:#333;\n    text-decoration: underline;\n}\ndiv.post-page h1{\n    text-align: center;\n    margin: 10px 0 5px;\n}\ndiv.post-page time{\n    text-align: center;\n    display: block;\n    font-size:1rem;\n    color:#aaa;\n    margin: 10px 0;\n}\ndiv.post-page div.author{\n    text-align: center;\n    margin-bottom: 20px;\n    font-size: .7rem;\n    font-weight: bold;\n}\ndiv.content p{\n    line-height: 1.7rem;\n    margin: 30px 0;\n}\ndiv.content li{\n    margin-bottom: 10px;\n}\ndiv.edit-row{\n    text-align: center;\n    margin-bottom: 20px;\n}\ndiv.post-page a.edit-btn{\n    background-color: #333;\n    display: inline-flex;\n    align-items: center;\n    gap: 5px;\n    color: #fff;\n    padding:15px 30px;\n    border-radius: 5px;\n    text-decoration: none;\n}\na svg{\n    height:20px;\n}\n"
  },
  {
    "path": "client/src/App.js",
    "content": "import './App.css';\nimport Post from \"./Post\";\nimport Header from \"./Header\";\nimport {Route, Routes} from \"react-router-dom\";\nimport Layout from \"./Layout\";\nimport IndexPage from \"./pages/IndexPage\";\nimport LoginPage from \"./pages/LoginPage\";\nimport RegisterPage from \"./pages/RegisterPage\";\nimport {UserContextProvider} from \"./UserContext\";\nimport CreatePost from \"./pages/CreatePost\";\nimport PostPage from \"./pages/PostPage\";\nimport EditPost from \"./pages/EditPost\";\n\nfunction App() {\n  return (\n    <UserContextProvider>\n      <Routes>\n        <Route path=\"/\" element={<Layout />}>\n          <Route index element={<IndexPage />} />\n          <Route path=\"/login\" element={<LoginPage />} />\n          <Route path=\"/register\" element={<RegisterPage />} />\n          <Route path=\"/create\" element={<CreatePost />} />\n          <Route path=\"/post/:id\" element={<PostPage />} />\n          <Route path=\"/edit/:id\" element={<EditPost />} />\n        </Route>\n      </Routes>\n    </UserContextProvider>\n  );\n}\n\nexport default App;\n"
  },
  {
    "path": "client/src/App.test.js",
    "content": "import { render, screen } from '@testing-library/react';\nimport App from './App';\n\ntest('renders learn react link', () => {\n  render(<App />);\n  const linkElement = screen.getByText(/learn react/i);\n  expect(linkElement).toBeInTheDocument();\n});\n"
  },
  {
    "path": "client/src/Editor.js",
    "content": "import ReactQuill from \"react-quill\";\n\nexport default function Editor({value,onChange}) {\n  const modules = {\n    toolbar: [\n      [{ header: [1, 2, false] }],\n      ['bold', 'italic', 'underline', 'strike', 'blockquote'],\n      [\n        { list: 'ordered' },\n        { list: 'bullet' },\n        { indent: '-1' },\n        { indent: '+1' },\n      ],\n      ['link', 'image'],\n      ['clean'],\n    ],\n  };\n  return (\n    <div className=\"content\">\n    <ReactQuill\n      value={value}\n      theme={'snow'}\n      onChange={onChange}\n      modules={modules} />\n    </div>\n  );\n}\n"
  },
  {
    "path": "client/src/Header.js",
    "content": "import {Link} from \"react-router-dom\";\nimport {useContext, useEffect, useState} from \"react\";\nimport {UserContext} from \"./UserContext\";\n\nexport default function Header() {\n  const {setUserInfo,userInfo} = useContext(UserContext);\n  useEffect(() => {\n    fetch('http://localhost:4000/profile', {\n      credentials: 'include',\n    }).then(response => {\n      response.json().then(userInfo => {\n        setUserInfo(userInfo);\n      });\n    });\n  }, []);\n\n  function logout() {\n    fetch('http://localhost:4000/logout', {\n      credentials: 'include',\n      method: 'POST',\n    });\n    setUserInfo(null);\n  }\n\n  const username = userInfo?.username;\n\n  return (\n    <header>\n      <Link to=\"/\" className=\"logo\">MyBlog</Link>\n      <nav>\n        {username && (\n          <>\n            <Link to=\"/create\">Create new post</Link>\n            <a onClick={logout}>Logout ({username})</a>\n          </>\n        )}\n        {!username && (\n          <>\n            <Link to=\"/login\">Login</Link>\n            <Link to=\"/register\">Register</Link>\n          </>\n        )}\n      </nav>\n    </header>\n  );\n}\n"
  },
  {
    "path": "client/src/Layout.js",
    "content": "import Header from \"./Header\";\nimport {Outlet} from \"react-router-dom\";\n\nexport default function Layout() {\n  return (\n    <main>\n      <Header />\n      <Outlet />\n    </main>\n  );\n}"
  },
  {
    "path": "client/src/Post.js",
    "content": "import {formatISO9075} from \"date-fns\";\nimport {Link} from \"react-router-dom\";\n\nexport default function Post({_id,title,summary,cover,content,createdAt,author}) {\n\n  return (\n    <div className=\"post\">\n      <div className=\"image\">\n        <Link to={`/post/${_id}`}>\n          <img src={'http://localhost:4000/'+cover} alt=\"\"/>\n        </Link>\n      </div>\n      <div className=\"texts\">\n        <Link to={`/post/${_id}`}>\n        <h2>{title}</h2>\n        </Link>\n        <p className=\"info\">\n          <a className=\"author\">{author.username}</a>\n          <time>{formatISO9075(new Date(createdAt))}</time>\n        </p>\n        <p className=\"summary\">{summary}</p>\n      </div>\n    </div>\n  );\n}"
  },
  {
    "path": "client/src/UserContext.js",
    "content": "import {createContext, useState} from \"react\";\n\nexport const UserContext = createContext({});\n\nexport function UserContextProvider({children}) {\n  const [userInfo,setUserInfo] = useState({});\n  return (\n    <UserContext.Provider value={{userInfo,setUserInfo}}>\n      {children}\n    </UserContext.Provider>\n  );\n}\n"
  },
  {
    "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/client';\nimport './index.css';\nimport App from './App';\nimport reportWebVitals from './reportWebVitals';\nimport {BrowserRouter} from \"react-router-dom\";\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n  <React.StrictMode>\n    <BrowserRouter>\n      <App />\n    </BrowserRouter>\n  </React.StrictMode>\n);\n\n// If you want to start measuring performance in your app, pass a function\n// to log results (for example: reportWebVitals(console.log))\n// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals\nreportWebVitals();\n"
  },
  {
    "path": "client/src/pages/CreatePost.js",
    "content": "import ReactQuill from \"react-quill\";\nimport 'react-quill/dist/quill.snow.css';\nimport {useState} from \"react\";\nimport {Navigate} from \"react-router-dom\";\nimport Editor from \"../Editor\";\n\nexport default function CreatePost() {\n  const [title,setTitle] = useState('');\n  const [summary,setSummary] = useState('');\n  const [content,setContent] = useState('');\n  const [files, setFiles] = useState('');\n  const [redirect, setRedirect] = useState(false);\n  async function createNewPost(ev) {\n    const data = new FormData();\n    data.set('title', title);\n    data.set('summary', summary);\n    data.set('content', content);\n    data.set('file', files[0]);\n    ev.preventDefault();\n    const response = await fetch('http://localhost:4000/post', {\n      method: 'POST',\n      body: data,\n      credentials: 'include',\n    });\n    if (response.ok) {\n      setRedirect(true);\n    }\n  }\n\n  if (redirect) {\n    return <Navigate to={'/'} />\n  }\n  return (\n    <form onSubmit={createNewPost}>\n      <input type=\"title\"\n             placeholder={'Title'}\n             value={title}\n             onChange={ev => setTitle(ev.target.value)} />\n      <input type=\"summary\"\n             placeholder={'Summary'}\n             value={summary}\n             onChange={ev => setSummary(ev.target.value)} />\n      <input type=\"file\"\n             onChange={ev => setFiles(ev.target.files)} />\n      <Editor value={content} onChange={setContent} />\n      <button style={{marginTop:'5px'}}>Create post</button>\n    </form>\n  );\n}"
  },
  {
    "path": "client/src/pages/EditPost.js",
    "content": "import {useEffect, useState} from \"react\";\nimport {Navigate, useParams} from \"react-router-dom\";\nimport Editor from \"../Editor\";\n\nexport default function EditPost() {\n  const {id} = useParams();\n  const [title,setTitle] = useState('');\n  const [summary,setSummary] = useState('');\n  const [content,setContent] = useState('');\n  const [files, setFiles] = useState('');\n  const [redirect,setRedirect] = useState(false);\n\n  useEffect(() => {\n    fetch('http://localhost:4000/post/'+id)\n      .then(response => {\n        response.json().then(postInfo => {\n          setTitle(postInfo.title);\n          setContent(postInfo.content);\n          setSummary(postInfo.summary);\n        });\n      });\n  }, []);\n\n  async function updatePost(ev) {\n    ev.preventDefault();\n    const data = new FormData();\n    data.set('title', title);\n    data.set('summary', summary);\n    data.set('content', content);\n    data.set('id', id);\n    if (files?.[0]) {\n      data.set('file', files?.[0]);\n    }\n    const response = await fetch('http://localhost:4000/post', {\n      method: 'PUT',\n      body: data,\n      credentials: 'include',\n    });\n    if (response.ok) {\n      setRedirect(true);\n    }\n  }\n\n  if (redirect) {\n    return <Navigate to={'/post/'+id} />\n  }\n\n  return (\n    <form onSubmit={updatePost}>\n      <input type=\"title\"\n             placeholder={'Title'}\n             value={title}\n             onChange={ev => setTitle(ev.target.value)} />\n      <input type=\"summary\"\n             placeholder={'Summary'}\n             value={summary}\n             onChange={ev => setSummary(ev.target.value)} />\n      <input type=\"file\"\n             onChange={ev => setFiles(ev.target.files)} />\n      <Editor onChange={setContent} value={content} />\n      <button style={{marginTop:'5px'}}>Update post</button>\n    </form>\n  );\n}"
  },
  {
    "path": "client/src/pages/IndexPage.js",
    "content": "import Post from \"../Post\";\nimport {useEffect, useState} from \"react\";\n\nexport default function IndexPage() {\n  const [posts,setPosts] = useState([]);\n  useEffect(() => {\n    fetch('http://localhost:4000/post').then(response => {\n      response.json().then(posts => {\n        setPosts(posts);\n      });\n    });\n  }, []);\n  return (\n    <>\n      {posts.length > 0 && posts.map(post => (\n        <Post {...post} />\n      ))}\n    </>\n  );\n}"
  },
  {
    "path": "client/src/pages/LoginPage.js",
    "content": "import {useContext, useState} from \"react\";\nimport {Navigate} from \"react-router-dom\";\nimport {UserContext} from \"../UserContext\";\n\nexport default function LoginPage() {\n  const [username,setUsername] = useState('');\n  const [password,setPassword] = useState('');\n  const [redirect,setRedirect] = useState(false);\n  const {setUserInfo} = useContext(UserContext);\n  async function login(ev) {\n    ev.preventDefault();\n    const response = await fetch('http://localhost:4000/login', {\n      method: 'POST',\n      body: JSON.stringify({username, password}),\n      headers: {'Content-Type':'application/json'},\n      credentials: 'include',\n    });\n    if (response.ok) {\n      response.json().then(userInfo => {\n        setUserInfo(userInfo);\n        setRedirect(true);\n      });\n    } else {\n      alert('wrong credentials');\n    }\n  }\n\n  if (redirect) {\n    return <Navigate to={'/'} />\n  }\n  return (\n    <form className=\"login\" onSubmit={login}>\n      <h1>Login</h1>\n      <input type=\"text\"\n             placeholder=\"username\"\n             value={username}\n             onChange={ev => setUsername(ev.target.value)}/>\n      <input type=\"password\"\n             placeholder=\"password\"\n             value={password}\n             onChange={ev => setPassword(ev.target.value)}/>\n      <button>Login</button>\n    </form>\n  );\n}"
  },
  {
    "path": "client/src/pages/PostPage.js",
    "content": "import {useContext, useEffect, useState} from \"react\";\nimport {useParams} from \"react-router-dom\";\nimport {formatISO9075} from \"date-fns\";\nimport {UserContext} from \"../UserContext\";\nimport {Link} from 'react-router-dom';\n\nexport default function PostPage() {\n  const [postInfo,setPostInfo] = useState(null);\n  const {userInfo} = useContext(UserContext);\n  const {id} = useParams();\n  useEffect(() => {\n    fetch(`http://localhost:4000/post/${id}`)\n      .then(response => {\n        response.json().then(postInfo => {\n          setPostInfo(postInfo);\n        });\n      });\n  }, []);\n\n  if (!postInfo) return '';\n\n  return (\n    <div className=\"post-page\">\n      <h1>{postInfo.title}</h1>\n      <time>{formatISO9075(new Date(postInfo.createdAt))}</time>\n      <div className=\"author\">by @{postInfo.author.username}</div>\n      {userInfo.id === postInfo.author._id && (\n        <div className=\"edit-row\">\n          <Link className=\"edit-btn\" to={`/edit/${postInfo._id}`}>\n            <svg xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" strokeWidth={1.5} stroke=\"currentColor\" className=\"w-6 h-6\">\n              <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10\" />\n            </svg>\n            Edit this post\n          </Link>\n        </div>\n      )}\n      <div className=\"image\">\n        <img src={`http://localhost:4000/${postInfo.cover}`} alt=\"\"/>\n      </div>\n      <div className=\"content\" dangerouslySetInnerHTML={{__html:postInfo.content}} />\n    </div>\n  );\n}"
  },
  {
    "path": "client/src/pages/RegisterPage.js",
    "content": "import {useState} from \"react\";\n\nexport default function RegisterPage() {\n  const [username, setUsername] = useState('');\n  const [password, setPassword] = useState('');\n  async function register(ev) {\n    ev.preventDefault();\n    const response = await fetch('http://localhost:4000/register', {\n      method: 'POST',\n      body: JSON.stringify({username,password}),\n      headers: {'Content-Type':'application/json'},\n    });\n    if (response.status === 200) {\n      alert('registration successful');\n    } else {\n      alert('registration failed');\n    }\n  }\n  return (\n    <form className=\"register\" onSubmit={register}>\n      <h1>Register</h1>\n      <input type=\"text\"\n             placeholder=\"username\"\n             value={username}\n             onChange={ev => setUsername(ev.target.value)}/>\n      <input type=\"password\"\n             placeholder=\"password\"\n             value={password}\n             onChange={ev => setPassword(ev.target.value)}/>\n      <button>Register</button>\n    </form>\n  );\n}"
  },
  {
    "path": "client/src/reportWebVitals.js",
    "content": "const reportWebVitals = onPerfEntry => {\n  if (onPerfEntry && onPerfEntry instanceof Function) {\n    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {\n      getCLS(onPerfEntry);\n      getFID(onPerfEntry);\n      getFCP(onPerfEntry);\n      getLCP(onPerfEntry);\n      getTTFB(onPerfEntry);\n    });\n  }\n};\n\nexport default reportWebVitals;\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';\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"dependencies\": {\n    \"bcryptjs\": \"^2.4.3\",\n    \"cookie-parser\": \"^1.4.6\",\n    \"cors\": \"^2.8.5\",\n    \"express\": \"^4.18.2\",\n    \"jsonwebtoken\": \"^9.0.0\",\n    \"mongoose\": \"^6.8.2\",\n    \"multer\": \"^1.4.5-lts.1\",\n    \"react-router-dom\": \"^6.6.1\"\n  }\n}\n"
  }
]