-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
133 lines (117 loc) · 4.26 KB
/
server.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
const express = require("express");
const repo = require("./logs_repository.js");
const user = require("./user_repository.js");
const auth = require("./auth.js");
const http = require("http");
const cors = require("cors");
const bcrypt = require("bcryptjs") // using bcryptjs instead of bcrypt is bc laravel uses $y$ and bcrypt doesnt support it
const cookieParser = require("cookie-parser");
const {body, param} = require('express-validator');
const {errorHandler, validateRequest, NotFoundError} = require('./error.js');
const saltRounds = 10;
const app = express();
// adding middleware
app.use(express.json()); // parse json
app.use(cors()); //enable cors
app.use(express.urlencoded({extended: true})); // allow to parse forms
app.use(cookieParser()); // parses cookies
const router = express.Router();
app.use('/api', router);
app.use(errorHandler) // custom middleware that handles my custom errors
// adding routes + validation
router.post("/auth/register",
body("username").isString().custom(async v => {
if (await user.existUsername(v)) return Promise.reject(); // return rejection so validation fails
}),
body("password").isString().isLength({min: 5}),
validateRequest,
async (req, res) => {
await user.registerUser(req.body.username, await bcrypt.hash(req.body.password, saltRounds))
res.sendStatus(201);
}
)
router.post("/auth/login",
body("username").isString(),
body("password").isString(),
validateRequest,
async (req, res) => {
const result = await user.login(req.body.username);
if (result.length === 0 || !(await bcrypt.compare(req.body.password, result[0].password)))
return res.sendStatus(403);
const token = auth.generateAccessToken(result[0].id)
res
.cookie("access_token", token, {httpOnly: true}) // supports both httpOnly cookie and bearer token
.json({access_token: token})
}
)
router.get("/auth/authenticated", auth.verifyJWT, (req, res) => {
res.sendStatus(200);
});
router.get("/books", auth.verifyJWT, async (req, res) => {
res.json(await repo.getBooks(req.id));
})
router.post("/books", auth.verifyJWT,
body("name").isString().isLength({max: 100}),
validateRequest,
async (req, res) => {
await repo.addBook(req.body.name, req.id)
res.sendStatus(201);
}
)
router.get("/books/:bookId", auth.verifyJWT,
param("bookId").isNumeric().exists().toInt().custom(async v => {
if ((await repo.getBook(v)).length === 0) throw new NotFoundError;
}),
validateRequest,
async (req, res) => {
res.json(await repo.getBook(req.params.bookId));
}
)
router.delete("/books/:bookId", auth.verifyJWT,
param("bookId").isNumeric().exists().toInt().custom(async v => {
if ((await repo.getBook(v)).length === 0) throw new NotFoundError
}),
validateRequest,
async (req, res) => {
await repo.deleteBook(req.params.bookId)
res.sendStatus(200)
}
)
router.put("/books/:bookId", auth.verifyJWT,
param("bookId").isNumeric().exists().toInt().custom(async v => {
if ((await repo.getBook(v)).length === 0) throw new NotFoundError;
}),
body("name").isString().isLength({max: 100}),
validateRequest,
async (req, res) => {
await repo.updateBook(req.params.bookId, req.body.name)
res.sendStatus(200)
}
)
router.get("/books/:bookId/entries", auth.verifyJWT,
param("bookId").isNumeric().exists().toInt().custom(async v => {
if ((await repo.getBook(v)).length === 0) throw new NotFoundError;
}),
validateRequest,
async (req, res) => {
res.json(await repo.getEntries(req.params.bookId));
}
)
router.post("/books/:bookId/entries", auth.verifyJWT,
param("bookId").isNumeric().exists().toInt().custom(async v => {
if ((await repo.getBook(v)).length === 0) throw new NotFoundError;
}),
body("text").exists(),
body("when").exists(),
body("where").exists(),
validateRequest,
async (req, res) => {
await repo.addEntry(req.params.bookId, req.body.text, req.body.when, req.body.where)
res.sendStatus(201);
}
)
//Setting up the server
const server = http.createServer(app);
const port = process.env.PORT || 5000;
server.listen(port);
console.log(`server online on port: ${port}`)