-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
176 lines (158 loc) · 4.61 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
require('./config/config');
const express = require('express');
const fs = require('fs');
const cors = require('cors');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
const jwt = require('jsonwebtoken');
const morgan = require('morgan');
const logger = require('./logger');
const { mongoose } = require('./db/mongoose');
const { User } = require('./models/user');
const { Post } = require('./models/post');
const { Gallery } = require('./models/gallery');
const { authenticate } = require('./middleware/authenticate');
const { asyncErrorHandler } = require('./middleware/errorHandler');
const { upload } = require('./middleware/upload');
const app = express();
const port = process.env.PORT;
//middlewares
app.disable('x-powered-by');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
//combine morgan and winston loggers
app.use(morgan(("combined", { stream: logger.stream })));
//register new user
app.post('/register', async (req, res) => {
const body = _.pick(req.body, ['email', 'password', 'first_name', 'last_name', 'role']);
const user = new User(body);
try {
const savedUser = await user.save();
const token = await user.generateAuthToken(user._id);
res.header('Authorization', token).send(savedUser);
} catch (e) {
res.status(400).send(e);
}
});
// test authentication
app.get('/users/me', authenticate, (req, res) => {
res.send(req.user);
});
// login
app.post('/api-token-auth', async (req, res) => {
const body = _.pick(req.body, ['email', 'password']);
try {
const user = await User.findByCredentials(body.email, body.password);
const token = await user.generateAuthToken(user.id);
await User.removeExpiredTokens(user);
res.header('Authorization', token).send({ user, token });
} catch (e) {
res.status(400).send(e);
}
});
// logout
app.delete('/logout', authenticate, async (req, res) => {
try {
await req.user.removeToken(req.token);
res.status(200).send({ message: 'logged out' });
} catch (e) {
res.status(400).send(e);
}
});
//admin
app.get('/admin', authenticate, async (req, res) => {
const token = jwt.decode(req.token);
if (token.role !== 'admin')
return res.status(400).send({ message: 'Only admins allowed!' });
res.send({ message: 'You are allowed as admin' });
});
//posts
app.post('/post', authenticate, async (req, res) => {
// const body = _.pick(req.body, [])
const post = new Post({
post: req.body.post,
category: req.body.category,
author: req.user._id,
tags: req.body.tags
});
try {
const savedPost = await post.save();
res.send(savedPost);
} catch (e) {
res.status(400).send(e);
}
});
// get all posts regardless of category
app.get('/post', authenticate, async (req, res) => {
try {
const posts = await Post.find({});
res.send(posts);
} catch (e) {
res.status(400).send(e);
}
});
//save pics
app.post('/photos/upload', authenticate, upload.array('photos', 12), async (req, res, next) => {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
const galleryArr = req.files.map(pic => ({
image: pic.path,
name: pic.filename,
contentType: pic.mimetype,
galleryName: req.body.galleryName
}));
const gallery = new Gallery({
gallery: galleryArr
});
try {
const savedGallery = await gallery.save();
res.send(savedGallery);
} catch (e) {
res.status(400).send(e);
}
});
//get galleries
app.get('/photos/:gallery', authenticate, async (req, res) => {
const galleryName = req.params.gallery;
try {
const photos = await Gallery.aggregate([
{ $unwind: '$gallery' },
{ $match: { 'gallery.galleryName': galleryName } },
]);
res.send(photos);
} catch (e) {
res.status(400).send(e);
}
});
//get pic
app.get('/photos/id/:id', authenticate, async (req, res) => {
const id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
const objectId = mongoose.Types.ObjectId(id);
try {
const photo = await Gallery.aggregate([
{ $unwind: '$gallery' },
{ $match: { 'gallery._id': objectId } },
]);
// const photo = await Gallery.find({
// 'gallery._id': id
// }, {
// 'gallery.$': 1
// // 'gallery': { $elemMatch: { _id: id } }
// });
res.send(photo);
} catch (e) {
res.status(400).send(e);
}
});
// Gets called because of `asyncErrorHandler()` middleware
app.use(function (error, req, res, next) {
res.json({ message: error.message });
});
app.listen(port, () => {
logger.info(`Server started at port ${port}`);
});
module.exports = { app }