-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
142 lines (124 loc) · 3.73 KB
/
Copy pathserver.js
File metadata and controls
142 lines (124 loc) · 3.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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';
const PORT = process.env.PORT || 400;
app.use(cors({credentials:true,origin:['http://localhost:3000',"https://mern-blog-app-6zzs.onrender.com"],}));
app.use(express.json());
app.use(cookieParser());
app.use('/uploads', express.static(__dirname + '/uploads'));
// mongoose.connect('mongodb+srv://blog-pages:X54D8pZFqTJnx6h4@cluster0.4dpwnxm.mongodb.net/?retryWrites=true&w=majority');
const PORT = process.env.PORT || 4000;
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');
}
postDoc.title = title;
postDoc.summary = summary;
postDoc.content = content;
if (newPath) {
postDoc.cover = newPath;
}
await postDoc.save();
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(PORT);