dcycle / starterkit-node

0 stars 1 forks source link

Store user sessions on disk, not in memory #40

Closed alberto56 closed 1 month ago

alberto56 commented 1 month ago

Start by getting the latest master branch of http://github.com/dcycle/starterkit-node

Then run ./scripts/deploy.sh

The deploy script will give you a username and password at the end in the console, it will look like:

username: admin
password: Ljpn+3kG1qDLGftzqmBIRsjclIWW817x
=>
=> Your node app is at: http://0.0.0.0:8428
=> Log in with the username and password above.

Log in and make sure you see the "Send Message" page.

Now in your code editor go to ./app/code/chatWeb/index.js and add this line just before async run(app) {:

this is a syntax error
async run(app)  {

The purpose of this line is to cause the app to fail.

Reload http://0.0.0.0:8428 and confirm you cannot load it

If you run:

docker compose logs node

You will see:

node-1  | Errors occurred during initialization phase:
node-1  | [
node-1  |   '/usr/src/app/app/chatWeb/index.js:14\n' +
node-1  |     '  this is a syntax error\n' +
node-1  |     '       ^^\n' +
node-1  |     '\n' +
node-1  |     "SyntaxError: Unexpected identifier 'is'\n" +

Now remove the syntax error and visit http://0.0.0.0:8428 again.

Confirm you are brought back to the login page.

This is because information pertaining to whom is logged in is stored in RAM, and RAM gets erased when node restarts (as, for example, when an error occurs during development, but also when the app is updated on a production server).

The same thing happens (your session is lost) if you run:

docker compose restart

This is because RAM is cleared when node restarts.

Note that chat messages do not get erased because they stored in the database, not in RAM.

Your task

Look over the code which uses Passport and express-session to manage user sessions.

Read https://www.passportjs.org/concepts/authentication/sessions/ to understand how sessions work

Find articles like https://meghagarwal.medium.com/storing-sessions-with-connect-mongo-in-mongodb-64d74e3bbd9c which discuss how Express Sessions can be stored in the database, not RAM.

See also https://stackoverflow.com/questions/76256585/how-to-store-an-express-session-in-a-mongodb-database-using-a-controller

We would like to be able to restart node by either inserting a syntax error or by running docker compose restart. Then we would like our session to remain active (not be logged out) because our session is stored in the database, not in RAM.