Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New branch #48

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"liveServer.settings.port": 5501
}
128 changes: 128 additions & 0 deletions API/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const multer = require('multer');
const uploadMiddleware = multer({ dest: 'uploads/' });
const app = express();
const User = require('./models/User');
const salt = bcrypt.genSaltSync(10);
const secret = process.env.JWT_SECRET || 'fgawdquygkj287763';
const fs = require('fs');
const Post = require('./models/post');

app.use(cors({ credentials: true, origin: 'http://localhost:3000' }));
app.use(express.json());
app.use(cookieParser());

mongoose.connect(process.env.MONGODB_URI || 'mongodb+srv://tzzkenz:[email protected]/test', {
useNewUrlParser: true,
useUnifiedTopology: true,
});

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.post('/signup', async (req, res) => {
const { username, password } = req.body;
try {
const userDoc = await User.create({
username,
password: bcrypt.hashSync(password, salt),
});
const token = jwt.sign({ username, id: userDoc._id }, secret, { expiresIn: '1h' });
res.cookie('token', token, { httpOnly: true }).json({ token });
} catch (e) {
console.error(e);
res.status(400).json({ error: 'registration failed' });
}
});

// app.post('/login', async (req, res) => {
// const { username, password } = req.body;
// try {
// const userDoc = await User.findOne({ username });

// if (!userDoc) {
// res.status(401).json({ error: 'User not found' });
// return;
// }

// const passOk = bcrypt.compareSync(password, userDoc.password);

// if (passOk) {
// const token = jwt.sign({ username, id: userDoc._id }, secret, { expiresIn: '1h' });
// res.cookie('token', token, { httpOnly: true }).json({ success: true });
// } else {
// res.status(401).json({ error: 'Invalid password' });
// }
// } catch (error) {
// console.error(error);
// res.status(500).json({ error: 'Internal server error' });
// }
// });

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, (err, info) => {
if (err) {
console.error(err);
return res.status(401).json({ error: 'Token verification failed' });
}

const { title, summary, content } = req.body;
const postDoc = await Post.create({
title,
summary,
content,
cover: newPath,
author: info.id,
});

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);
});

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
10 changes: 10 additions & 0 deletions API/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
username: {type: String, required: true, min: 4, unique:true},
password: {type: String, required: true},
})

const userModel = mongoose.model('User', userSchema);

module.exports = userModel;
16 changes: 16 additions & 0 deletions API/models/post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
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
82 changes: 82 additions & 0 deletions API/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// routes.js

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const fs = require('fs');
const User = require('./models/User');
const Post = require('./models/Post');

const saltRounds = 10;
const secret = process.env.JWT_SECRET || 'fgawdquygkj287763';
const uploadMiddleware = multer({ dest: 'uploads/' });

// Signup route
exports.signup = async (req, res, next) => {
const { username, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, saltRounds);
const userDoc = await User.create({ username, password: hashedPassword });
const token = jwt.sign({ username, id: userDoc._id }, secret, { expiresIn: '1h' });
res.cookie('token', token, { httpOnly: true }).json({ token });
} catch (e) {
next(e);
}
};

// Login route
exports.login = async (req, res, next) => {
const { username, password } = req.body;
try {
const userDoc = await User.findOne({ username });

if (!userDoc) {
res.status(401).json({ error: 'User not found' });
return;
}

const passOk = bcrypt.compareSync(password, userDoc.password);

if (passOk) {
const token = jwt.sign({ username, id: userDoc._id }, secret, { expiresIn: '1h' });
res.cookie('token', token, { httpOnly: true }).json(token);
} else {
res.status(401).json({ error: 'Invalid password' });
}
} catch (error) {
next(error);
}
};

// Create post route
exports.createPost = async (req, res, next) => {
try {
// ... (same as your original code)
} catch (error) {
next(error);
}
};

// Get all posts route
exports.getPosts = async (req, res, next) => {
try {
const posts = await Post.find()
.populate('author', ['username'])
.sort({ createdAt: -1 })
.limit(20);
res.json(posts);
} catch (error) {
next(error);
}
};

// Get post by ID route
exports.getPostById = async (req, res, next) => {
try {
const { id } = req.params;
const postDoc = await Post.findById(id).populate('author', ['username']);
res.json(postDoc);
} catch (error) {
next(error);
}
};
Binary file added API/uploads/06be84f28475fb2d9b07f83025b6bed6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/1901dfe870b4a486cd65644189e706d9.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/257e92fda1fc65f0aad23db6acb881b0.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/2c0044591cf4cf32a87f374f9e85d8bd.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/31439183149f303227f3f92030d5733a.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/3ae6a6e962fa4385244f9fe80ee7d5c6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/5d3d8b7a9f895017017b206c2db24e3f.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/97cce14a9135ed495c0def7ba89d63f1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/9970b299fe691b3f247f7890243e9296.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/a01bea55316875a3034d9468e2764b12.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/b4087e685fb39c368487889fabe057e0.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/c3721bc2e2db3cf740eafeb07d817701.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/ce877e88065675b4f6bf9cdb00279669.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/e052ee4484dd292469d8a19375ec61dc.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added API/uploads/e8d387006fabffe581ff943a63a9ed10.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions CLIENT/react-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 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*
70 changes: 70 additions & 0 deletions CLIENT/react-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# 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:

### `npm 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.

### `npm 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.

### `npm run 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.

### `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](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)

### `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](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Loading