-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
75 lines (65 loc) · 1.64 KB
/
app.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
const express = require("express");
const app = express();
app.use(express.json());
const {
models: { User, Note },
} = require("./db");
const path = require("path");
const jwt = require("jsonwebtoken");
const requireToken = async (req, res, next) => {
try {
const token = req.headers.authorization;
const id = jwt.verify(token, process.env.JWT);
const user = await User.byToken(id);
req.user = user;
next();
} catch (error) {
next(error);
}
};
app.get("/", (req, res) => res.sendFile(path.join(__dirname, "index.html")));
app.post("/api/auth", async (req, res, next) => {
try {
res.send({
token: await User.authenticate(req.body),
});
} catch (ex) {
next(ex);
}
});
app.get("/api/auth", async (req, res, next) => {
try {
// console.log('this is req.headers',req.headers)
// console.log('this is the request after auth', req)
res.send(
await User.byToken(jwt.verify(req.headers.authorization, process.env.JWT))
);
} catch (ex) {
next(ex);
}
});
app.delete("/api/auth", async (req, res, next) => {
try {
res.send();
} catch (ex) {
next(ex);
}
});
app.get("/api/users/:userId/notes", requireToken, async (req, res, next) => {
try {
const user = await Note.byUserId(parseInt(req.params.userId));
if (parseInt(req.params.id) !== user.id) {
const error = "Not allowed to access another user's notes";
error.status = 403;
throw error;
}
res.send(user);
} catch (error) {
next(error);
}
});
app.use((err, req, res, next) => {
console.log(err);
res.status(err.status || 500).send({ error: err.message });
});
module.exports = app;