get sessions to work, better middleware design pattern

This commit is contained in:
b1ek 2023-02-27 00:18:26 +10:00
parent 80c0a8be3e
commit 0843b798a4
Signed by: blek
GPG Key ID: 14546221E3595D0C
4 changed files with 35 additions and 25 deletions

View File

@ -11,27 +11,12 @@ if (process.env.APP_DEBUG == 'true') {
const express = require('express');
const app = express();
const session = require('express-session');
const cookie_parse = require('cookie-parser');
const cookie_encrypt = require('cookie-encrypter');
const Redis = require("ioredis");
const bodyparser = require('body-parser');
let redisClient = new Redis(process.env.REDIS_PORT, process.env.REDIS_HOST);
let RedisStore = require("connect-redis")(session)
const { APP_PORT, APP_KEY } = process.env;
const { APP_PORT } = process.env;
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
app.use(cookie_parse(APP_KEY))
app.use(cookie_encrypt(APP_KEY));
app.use(session({
secret: APP_KEY,
resave: false,
saveUninitialized: true,
cookie: { secure: true },
store: new RedisStore({ client: redisClient })
}));
app.use(require('./middleware'));
app.use(require('./routes'));

12
middleware/cookie.js Normal file
View File

@ -0,0 +1,12 @@
const express = require('express');
const router = express.Router();
const cookie_parse = require('cookie-parser');
const cookie_encrypt = require('cookie-encrypter');
const { APP_KEY } = process.env;
router.use(cookie_parse(APP_KEY))
router.use(cookie_encrypt(APP_KEY));
module.exports = router

View File

@ -2,6 +2,7 @@ const express = require('express');
const router = express.Router();
const glob = require('glob');
router.use(require('./cookie'));
router.use(require('./session'));
router.use(require('./session_back'));

View File

@ -1,16 +1,28 @@
const express = require('express');
const session = require('express-session');
const crypto = require('crypto');
const router = new express.Router();
const parser = require('cookie-parser');
const Redis = require("ioredis").Redis;
/** @type {import('ioredis').Redis} */
const redis = new Redis(process.env.REDIS_PORT, process.env.REDIS_HOST);
const ConnectRedis = require('connect-redis')(session);
const store = new ConnectRedis({client: redis});
const express = require('express');
const router = express.Router();
async function session(req, res, next) {
res.send(req.cookies);
return;
}
router.use(session);
router.use(parser())
router.use(session({
secret: process.env.APP_KEY,
store: store,
cookie: {
// secure cookies didnt work for some reason
secure: false
},
resave: true,
genid: (req) => {
return crypto.randomBytes(256).toString('base64');
}
}));
module.exports = router;