summaryrefslogtreecommitdiffstats
path: root/finished-application/backend/src/index.js
diff options
context:
space:
mode:
authorWes Bos <wesbos@gmail.com>2018-09-14 12:18:12 -0400
committerWes Bos <wesbos@gmail.com>2018-09-14 12:18:12 -0400
commit2d145b026cfdf54a63bef0b9d6324b6785390307 (patch)
treef6c1d8f987437803a5c026e70535bf9ff244e885 /finished-application/backend/src/index.js
parent8a5825d52271d712ec7c8348447d433067e13ef2 (diff)
move finished folder
Diffstat (limited to 'finished-application/backend/src/index.js')
-rw-r--r--finished-application/backend/src/index.js46
1 files changed, 46 insertions, 0 deletions
diff --git a/finished-application/backend/src/index.js b/finished-application/backend/src/index.js
new file mode 100644
index 0000000..804d6d6
--- /dev/null
+++ b/finished-application/backend/src/index.js
@@ -0,0 +1,46 @@
+const cookieParser = require('cookie-parser');
+const jwt = require('jsonwebtoken');
+
+require('dotenv').config({ path: 'variables.env' });
+const createServer = require('./createServer');
+const db = require('./db');
+
+const server = createServer();
+
+server.express.use(cookieParser());
+
+// decode the JWT so we can get the user Id on each request
+server.express.use((req, res, next) => {
+ const { token } = req.cookies;
+ if (token) {
+ const { userId } = jwt.verify(token, process.env.APP_SECRET);
+ // put the userId onto the req for future requests to access
+ req.userId = userId;
+ }
+ next();
+});
+
+// 2. Create a middleware that populates the user on each request
+
+server.express.use(async (req, res, next) => {
+ // if they aren't logged in, skip this
+ if (!req.userId) return next();
+ const user = await db.query.user(
+ { where: { id: req.userId } },
+ '{ id, permissions, email, name }'
+ );
+ req.user = user;
+ next();
+});
+
+server.start(
+ {
+ cors: {
+ credentials: true,
+ origin: process.env.FRONTEND_URL,
+ },
+ },
+ deets => {
+ console.log(`Server is now running on port http://localhost:${deets.port}`);
+ }
+);