-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
150 lines (130 loc) · 3.85 KB
/
index.js
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
143
144
145
146
147
148
149
150
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');
require ('dotenv').config();
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://tharinduchaturanga432:tharuu@cluster0.rq4mgxz.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});
if (!userDoc) {
// user not found
return res.status(400).json('wrong credentials');
}
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 {
// wrong password
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 Post.findOneAndUpdate({_id: id}, {
title,
summary,
content,
cover: newPath ? newPath : postDoc.cover,
});
const updatedPostDoc = await Post.findById(id);
res.json(updatedPostDoc);
});
});
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(process.env.PORT || 4000, () => {
console.log('server started');
});
//