Repository: dejwid/mern-blog
Branch: master
Commit: c09c8000dcda
Files: 29
Total size: 26.8 KB
Directory structure:
gitextract_qeewyc7n/
├── .gitignore
├── api/
│ ├── index.js
│ └── models/
│ ├── Post.js
│ └── User.js
├── client/
│ ├── .gitignore
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ └── src/
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── Editor.js
│ ├── Header.js
│ ├── Layout.js
│ ├── Post.js
│ ├── UserContext.js
│ ├── index.css
│ ├── index.js
│ ├── pages/
│ │ ├── CreatePost.js
│ │ ├── EditPost.js
│ │ ├── IndexPage.js
│ │ ├── LoginPage.js
│ │ ├── PostPage.js
│ │ └── RegisterPage.js
│ ├── reportWebVitals.js
│ └── setupTests.js
└── package.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.idea
node_modules
api/uploads/*
================================================
FILE: api/index.js
================================================
const express = require('express');
const cors = require('cors');
const mongoose = require("mongoose");
const User = require('./models/User');
const Post = require('./models/Post');
const bcrypt = require('bcryptjs');
const app = express();
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const multer = require('multer');
const uploadMiddleware = multer({ dest: 'uploads/' });
const fs = require('fs');
const salt = bcrypt.genSaltSync(10);
const secret = 'asdfe45we45w345wegw345werjktjwertkj';
app.use(cors({credentials:true,origin:'http://localhost:3000'}));
app.use(express.json());
app.use(cookieParser());
app.use('/uploads', express.static(__dirname + '/uploads'));
mongoose.connect('mongodb+srv://blog:RD8paskYC8Ayj09u@cluster0.pflplid.mongodb.net/?retryWrites=true&w=majority');
app.post('/register', async (req,res) => {
const {username,password} = req.body;
try{
const userDoc = await User.create({
username,
password:bcrypt.hashSync(password,salt),
});
res.json(userDoc);
} catch(e) {
console.log(e);
res.status(400).json(e);
}
});
app.post('/login', async (req,res) => {
const {username,password} = req.body;
const userDoc = await User.findOne({username});
const passOk = bcrypt.compareSync(password, userDoc.password);
if (passOk) {
// logged in
jwt.sign({username,id:userDoc._id}, secret, {}, (err,token) => {
if (err) throw err;
res.cookie('token', token).json({
id:userDoc._id,
username,
});
});
} else {
res.status(400).json('wrong credentials');
}
});
app.get('/profile', (req,res) => {
const {token} = req.cookies;
jwt.verify(token, secret, {}, (err,info) => {
if (err) throw err;
res.json(info);
});
});
app.post('/logout', (req,res) => {
res.cookie('token', '').json('ok');
});
app.post('/post', uploadMiddleware.single('file'), async (req,res) => {
const {originalname,path} = req.file;
const parts = originalname.split('.');
const ext = parts[parts.length - 1];
const newPath = path+'.'+ext;
fs.renameSync(path, newPath);
const {token} = req.cookies;
jwt.verify(token, secret, {}, async (err,info) => {
if (err) throw err;
const {title,summary,content} = req.body;
const postDoc = await Post.create({
title,
summary,
content,
cover:newPath,
author:info.id,
});
res.json(postDoc);
});
});
app.put('/post',uploadMiddleware.single('file'), async (req,res) => {
let newPath = null;
if (req.file) {
const {originalname,path} = req.file;
const parts = originalname.split('.');
const ext = parts[parts.length - 1];
newPath = path+'.'+ext;
fs.renameSync(path, newPath);
}
const {token} = req.cookies;
jwt.verify(token, secret, {}, async (err,info) => {
if (err) throw err;
const {id,title,summary,content} = req.body;
const postDoc = await Post.findById(id);
const isAuthor = JSON.stringify(postDoc.author) === JSON.stringify(info.id);
if (!isAuthor) {
return res.status(400).json('you are not the author');
}
await postDoc.update({
title,
summary,
content,
cover: newPath ? newPath : postDoc.cover,
});
res.json(postDoc);
});
});
app.get('/post', async (req,res) => {
res.json(
await Post.find()
.populate('author', ['username'])
.sort({createdAt: -1})
.limit(20)
);
});
app.get('/post/:id', async (req, res) => {
const {id} = req.params;
const postDoc = await Post.findById(id).populate('author', ['username']);
res.json(postDoc);
})
app.listen(4000);
//
================================================
FILE: api/models/Post.js
================================================
const mongoose = require('mongoose');
const {Schema,model} = mongoose;
const PostSchema = new Schema({
title:String,
summary:String,
content:String,
cover:String,
author:{type:Schema.Types.ObjectId, ref:'User'},
}, {
timestamps: true,
});
const PostModel = model('Post', PostSchema);
module.exports = PostModel;
================================================
FILE: api/models/User.js
================================================
const mongoose = require('mongoose');
const {Schema, model} = mongoose;
const UserSchema = new Schema({
username: {type: String, required: true, min: 4, unique: true},
password: {type: String, required: true},
});
const UserModel = model('User', UserSchema);
module.exports = UserModel;
================================================
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
================================================
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
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.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn 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](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](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](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](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](https://facebook.github.io/create-react-app/docs/deployment)
### `yarn build` fails to minify
This 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)
================================================
FILE: client/package.json
================================================
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"date-fns": "^2.29.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-quill": "^2.0.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"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
================================================
React App
================================================
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
================================================
*{
box-sizing: border-box;
}
a{
cursor: pointer;
}
body{
color: #222;
}
img{
max-width: 100%;
}
main{
padding: 10px;
max-width: 960px;
margin: 0 auto;
}
header{
display:flex;
justify-content:space-between;
margin-top: 20px;
margin-bottom: 50px;
align-items: center;
}
header a{
text-decoration:none;
color: inherit;
}
header a.logo{
font-weight: bold;
font-size: 1.5rem;
}
header nav{
display:flex;
gap: 24px;
}
div.post{
display: grid;
grid-template-columns: 1fr;
gap: 20px;
margin-bottom: 30px;
}
@media screen and (min-width: 700px) {
div.post{
grid-template-columns: .9fr 1.1fr;
}
}
div.post div.texts h2{
margin:0;
font-size: 2rem;
}
div.post div.texts a{
text-decoration:none;
color: inherit;
}
div.post p.info{
margin:24px 0;
color: #888;
font-size:1rem;
font-weight: bold;
display: flex;
gap: 10px;
}
div.post p.info a.author{
color:#333;
}
div.post p.summary{
margin:10px 0;
line-height: 1.8rem;
}
form.login, form.register{
max-width: 400px;
margin: 0 auto;
}
input{
display: block;
margin-bottom: 5px;
width: 100%;
padding: 5px 7px;
border: 2px solid #ddd;
border-radius: 5px;
background-color: #fff;
}
button{
cursor: pointer;
width: 100%;
display: block;
background-color: #555;
border:0;
color: #fff;
border-radius: 5px;
padding: 7px 0;
}
form.login h1, form.register h1{
text-align: center;
}
div.post-page div.image{
max-height:300px;
display: flex;
overflow:hidden;
}
div.post-page div.image img{
object-fit: cover;
object-position: center center;
width: 100%;
}
div.post-page a{
color:#333;
text-decoration: underline;
}
div.post-page h1{
text-align: center;
margin: 10px 0 5px;
}
div.post-page time{
text-align: center;
display: block;
font-size:1rem;
color:#aaa;
margin: 10px 0;
}
div.post-page div.author{
text-align: center;
margin-bottom: 20px;
font-size: .7rem;
font-weight: bold;
}
div.content p{
line-height: 1.7rem;
margin: 30px 0;
}
div.content li{
margin-bottom: 10px;
}
div.edit-row{
text-align: center;
margin-bottom: 20px;
}
div.post-page a.edit-btn{
background-color: #333;
display: inline-flex;
align-items: center;
gap: 5px;
color: #fff;
padding:15px 30px;
border-radius: 5px;
text-decoration: none;
}
a svg{
height:20px;
}
================================================
FILE: client/src/App.js
================================================
import './App.css';
import Post from "./Post";
import Header from "./Header";
import {Route, Routes} from "react-router-dom";
import Layout from "./Layout";
import IndexPage from "./pages/IndexPage";
import LoginPage from "./pages/LoginPage";
import RegisterPage from "./pages/RegisterPage";
import {UserContextProvider} from "./UserContext";
import CreatePost from "./pages/CreatePost";
import PostPage from "./pages/PostPage";
import EditPost from "./pages/EditPost";
function App() {
return (
}>
} />
} />
} />
} />
} />
} />
);
}
export default App;
================================================
FILE: client/src/App.test.js
================================================
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render();
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
================================================
FILE: client/src/Editor.js
================================================
import ReactQuill from "react-quill";
export default function Editor({value,onChange}) {
const modules = {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[
{ list: 'ordered' },
{ list: 'bullet' },
{ indent: '-1' },
{ indent: '+1' },
],
['link', 'image'],
['clean'],
],
};
return (
);
}
================================================
FILE: client/src/Header.js
================================================
import {Link} from "react-router-dom";
import {useContext, useEffect, useState} from "react";
import {UserContext} from "./UserContext";
export default function Header() {
const {setUserInfo,userInfo} = useContext(UserContext);
useEffect(() => {
fetch('http://localhost:4000/profile', {
credentials: 'include',
}).then(response => {
response.json().then(userInfo => {
setUserInfo(userInfo);
});
});
}, []);
function logout() {
fetch('http://localhost:4000/logout', {
credentials: 'include',
method: 'POST',
});
setUserInfo(null);
}
const username = userInfo?.username;
return (
MyBlog
);
}
================================================
FILE: client/src/Layout.js
================================================
import Header from "./Header";
import {Outlet} from "react-router-dom";
export default function Layout() {
return (
);
}
================================================
FILE: client/src/Post.js
================================================
import {formatISO9075} from "date-fns";
import {Link} from "react-router-dom";
export default function Post({_id,title,summary,cover,content,createdAt,author}) {
return (
);
}
================================================
FILE: client/src/UserContext.js
================================================
import {createContext, useState} from "react";
export const UserContext = createContext({});
export function UserContextProvider({children}) {
const [userInfo,setUserInfo] = useState({});
return (
{children}
);
}
================================================
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/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter} from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
================================================
FILE: client/src/pages/CreatePost.js
================================================
import ReactQuill from "react-quill";
import 'react-quill/dist/quill.snow.css';
import {useState} from "react";
import {Navigate} from "react-router-dom";
import Editor from "../Editor";
export default function CreatePost() {
const [title,setTitle] = useState('');
const [summary,setSummary] = useState('');
const [content,setContent] = useState('');
const [files, setFiles] = useState('');
const [redirect, setRedirect] = useState(false);
async function createNewPost(ev) {
const data = new FormData();
data.set('title', title);
data.set('summary', summary);
data.set('content', content);
data.set('file', files[0]);
ev.preventDefault();
const response = await fetch('http://localhost:4000/post', {
method: 'POST',
body: data,
credentials: 'include',
});
if (response.ok) {
setRedirect(true);
}
}
if (redirect) {
return
}
return (
);
}
================================================
FILE: client/src/pages/EditPost.js
================================================
import {useEffect, useState} from "react";
import {Navigate, useParams} from "react-router-dom";
import Editor from "../Editor";
export default function EditPost() {
const {id} = useParams();
const [title,setTitle] = useState('');
const [summary,setSummary] = useState('');
const [content,setContent] = useState('');
const [files, setFiles] = useState('');
const [redirect,setRedirect] = useState(false);
useEffect(() => {
fetch('http://localhost:4000/post/'+id)
.then(response => {
response.json().then(postInfo => {
setTitle(postInfo.title);
setContent(postInfo.content);
setSummary(postInfo.summary);
});
});
}, []);
async function updatePost(ev) {
ev.preventDefault();
const data = new FormData();
data.set('title', title);
data.set('summary', summary);
data.set('content', content);
data.set('id', id);
if (files?.[0]) {
data.set('file', files?.[0]);
}
const response = await fetch('http://localhost:4000/post', {
method: 'PUT',
body: data,
credentials: 'include',
});
if (response.ok) {
setRedirect(true);
}
}
if (redirect) {
return
}
return (
);
}
================================================
FILE: client/src/pages/IndexPage.js
================================================
import Post from "../Post";
import {useEffect, useState} from "react";
export default function IndexPage() {
const [posts,setPosts] = useState([]);
useEffect(() => {
fetch('http://localhost:4000/post').then(response => {
response.json().then(posts => {
setPosts(posts);
});
});
}, []);
return (
<>
{posts.length > 0 && posts.map(post => (
))}
>
);
}
================================================
FILE: client/src/pages/LoginPage.js
================================================
import {useContext, useState} from "react";
import {Navigate} from "react-router-dom";
import {UserContext} from "../UserContext";
export default function LoginPage() {
const [username,setUsername] = useState('');
const [password,setPassword] = useState('');
const [redirect,setRedirect] = useState(false);
const {setUserInfo} = useContext(UserContext);
async function login(ev) {
ev.preventDefault();
const response = await fetch('http://localhost:4000/login', {
method: 'POST',
body: JSON.stringify({username, password}),
headers: {'Content-Type':'application/json'},
credentials: 'include',
});
if (response.ok) {
response.json().then(userInfo => {
setUserInfo(userInfo);
setRedirect(true);
});
} else {
alert('wrong credentials');
}
}
if (redirect) {
return
}
return (
);
}
================================================
FILE: client/src/pages/PostPage.js
================================================
import {useContext, useEffect, useState} from "react";
import {useParams} from "react-router-dom";
import {formatISO9075} from "date-fns";
import {UserContext} from "../UserContext";
import {Link} from 'react-router-dom';
export default function PostPage() {
const [postInfo,setPostInfo] = useState(null);
const {userInfo} = useContext(UserContext);
const {id} = useParams();
useEffect(() => {
fetch(`http://localhost:4000/post/${id}`)
.then(response => {
response.json().then(postInfo => {
setPostInfo(postInfo);
});
});
}, []);
if (!postInfo) return '';
return (
{postInfo.title}
by @{postInfo.author.username}
{userInfo.id === postInfo.author._id && (
)}
);
}
================================================
FILE: client/src/pages/RegisterPage.js
================================================
import {useState} from "react";
export default function RegisterPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
async function register(ev) {
ev.preventDefault();
const response = await fetch('http://localhost:4000/register', {
method: 'POST',
body: JSON.stringify({username,password}),
headers: {'Content-Type':'application/json'},
});
if (response.status === 200) {
alert('registration successful');
} else {
alert('registration failed');
}
}
return (
);
}
================================================
FILE: client/src/reportWebVitals.js
================================================
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
================================================
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';
================================================
FILE: package.json
================================================
{
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.0",
"mongoose": "^6.8.2",
"multer": "^1.4.5-lts.1",
"react-router-dom": "^6.6.1"
}
}