Using session within the express framework

Keywords: node.js Session Mongoose Database npm

The last article mentioned the shortcomings of cookie s and suggested that session is one way to solve the shortcomings.This article tells you how to use session. The author used the file save session method.If you don't want to save in memory or database, remember to use the appropriate module.
Below are two ways to use memory storage and file storage.

Memory storage session

Implementation process

// app.js
// Introducing express-session
var session = require('express-session')
// Bind session middleware for application
app.use(session({
    name: 'session-id',
    secret: '12345-67890',
    saveUninitialized: false,
    resave: false
}))

View results

router.get('/session/first', (req, res, next) => {
  let s = req.session
  console.log(s)
  res.send(s)
})

Use

Use this method to do a demo. For example, show the number of views.

router.get('/session/view', (req, res, next) => {
  let s = req.session
  if (req.session.views) {
    req.session.views++
    res.send(`views: ${req.session.views} time.`)
  } else {
    req.session.views = 1
    res.send('views: 0')
  }
})


I find that after working with sessions, I create a session directory in the root directory where sessions are saved.

File Storage session

The difference with memory storage sessions is the location where sessions are saved.Memory is stored by saving sessions in sessions.For background services, which consume a lot of memory, this method is certainly not possible.The file is stored by saving sessions in a folder.I heard there is another kind called database saving.

install

To use file storage for sessions, you need to install session-file-store.

npm i express-session session-file-store

Use file storage

// app.js
var session = require('express-session')
var FileStore = require('session-file-store')(session) // Introduce 
// Use in express-session
app.use(session({
  name: 'session-id',
  secret: '12345-67890',
  saveUninitialized: false,
  resave: false,
  store: new FileStore() // Indicates the use of file storage
}))

Registration, Login, Login Verification and Logout

This section requires the bodyParser mongoose module.Remember to install.

1. Create a database connection.

Connecting to the database allows you to place user data in the database.

// app.js
const mongoose = require('mongoose')
const url = 'mongoodb://localhost:27017/confusion'
const connect = mongoose.connect(url, {useNewUrlParser: true, useCreateIndex: true})
connest.then(db => {
  console.log('Connect correct to server')
}, err => {console.log(err)})

2. Create a user's model to connect to the database.

Create the models directory under the project root directory, then create user.js.The user's model is defined below

// @/models/user.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
User = new Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  admin: {
    type: Boolean,
    default: false
  }
})
module.exports = mongoose.model('User', User)

3. Create registered interfaces.

Registered interfaces
    //Is there an existing user - ----------> Do not create again.  
            |-----------Non-existent----->Create User

// @/routes/users.js
// /session/first/session/view commented or deleted.
// This file is before app.user(session(...), so req.session is not available.
// //View session
// router.get('/session/first', (req, res, next) => {
//   let s = req.session
//   console.log(s)
//   res.send(s)
// })
// //Save views in session
// router.get('/session/view', (req, res, next) => {
//   let s = req.session
//   if (req.session.views) {
//     req.session.views++
//     res.send(`views: ${req.session.views} time.`)
//   } else {
//     req.session.views = 1
//     res.send('views: 1')
//   }
// })

router.post('/signup', (req, res, next) => {
  console.log(req.body)
  User.findOne({username: req.body.username}).then(user => {
    if (user === null) {
      return User.create({
        username: req.body.username,
        password: req.body.password
      })
    } else {
      var err = new Error(`User ${req.body.username} already exist!`)
      err.status = 403
      next(err)
    }
  }).then(user => {
    res.statusCode = 200
    res.json({status: 'registration successful', user: user})
  }).catch(err => {
    res.send(err)
  })
})

4. Create a login interface.

Login Interface https://github.com/feigebaobei/nodejs/tree/master/node-session
    //Have you logged in already------------> Do nothing  
        |-----------Not logged in----->Verification username/password Is it correct.----Correct---->Settings are already logged in  
                                        |----------------------Incorrect---->Return error

router.post('/login', (req, res, next) => {
  if (req.session.auth) { // Tagged with req.session.auth, whether the tag has passed login validation
    res.statusCode = 200
    res.send('You are already authenticated')
  } else {
    User.findOne({username: req.body.username}).then(user => {
      if (user) {
        if (user.password !== req.body.password) {
          var err = new Error(`password error`)
          err.status = 403
          next(err)
        } else {
          req.session.auth = true // Logon success setting marked true
          res.statusCode = 200
          res.send('login successful')
        }
      } else { // No user specified
        var err = new Error(`User ${req.body.username} does not exist!`)
        err.status = 403
        next(err)
      }
    // }).catch(err => next(err))
    }).catch(err => {
      res.send(err)
    })
  }
})

5. Create a logged-out interface.

router.get('/logout', (req, res, next) => {
  if (req.session) {
    req.session.destroy() // Delete session
    res.clearCookie('session-id') // delete cookie
    res.send('Logout success.Redirected things for the front end to do')
  } else {
    var err = new Error('you are not logged in!')
    err.status = 403
    next(err)
  }
})

6. Accessible interfaces after login

// @/routes/news.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
module.exports = router;

7. Write the middleware for login verification.Note the order of login interfaces, login validation middleware, and interfaces accessible after login.

// app.js
// 1. Introducing Routing
var index = require('./routes/index');
var users = require('./routes/users');
var news = require('./routes/news');
// 2. Mount session Middleware
app.use(session({
  name: 'session-id',
  secret: '12345-67890',
  saveUninitialized: false,
  resave: false,
  store: new FileStore()
}))
// 3. Mount routes that do not require login validation
app.use('/', index)
app.use('/users', users)
// 4. Define Authentication Logon Functions
let authFn = (req, res, next) => {
  console.log(req.session)
  if (req.session.auth) {
    next()
  } else {
    var err = new Error('You are not authenticated!')
    err.status = 403
    next(err)
  }
}
// 5. Mount routes that require login validation
app.use('/news', news)

summary

This example only demonstrates simple login, authenticated login, and logout functions.The following is the js module (express-session, session-file-store, mongoose) used in this article, which can be found on npm. Complete Code

Posted by citricsquid on Tue, 30 Jul 2019 09:24:20 -0700