-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiServer.js
67 lines (56 loc) · 1.34 KB
/
apiServer.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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const db = require('./db');
const app = express();
const allowedOrigins = [
'http://localhost:3000',
'http://localhost:5000',
'https://twid.dev',
/https:\/\/.*--twid\.netlify\.app/,
];
app.use(
cors({
origin: allowedOrigins,
}),
);
app.use(express.json());
const PORT = 4000;
const authenticateToken = (req, res, next) => {
const authHeader = req.headers.authorization;
const token = authHeader?.split(' ')[1];
if (!token) {
return res.sendStatus(401);
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
res.sendStatus(403);
} else {
req.user = user;
next();
}
});
return undefined;
};
app.get('/api/content', authenticateToken, async (req, res) => {
res.send('Success!');
});
app.get('/api/me', authenticateToken, async (req, res) => {
try {
const { user_id: userId, username, email } = await db
.select()
.table('users')
.where('user_id', req.user.userId)
.first();
res.send({
userId,
username,
email,
});
} catch (error) {
res.sendStatus(500);
}
});
// eslint-disable-next-line no-console
app.listen(PORT, () => console.log(`Listening at http://localhost:${PORT}`));