中介軟體在儲存之前雜湊使用者密碼

*這是 Serial Document Middleware一個例子 *****

在此示例中,我們將編寫一箇中介軟體,將純文字密碼轉換為雜湊密碼,然後將其儲存在資料庫中。

在建立新使用者或更新現有使用者詳細資訊時,此中介軟體將自動啟動。

FILENAME: User.js

// lets import mongoose first
import mongoose from 'mongoose'

// lets create a schema for the user model
const UserSchema = mongoose.Schema(
  {
    name: String,
    email: { type: String, lowercase: true, requird: true },
    password: String,
  },
);

/**
 * This is the middleware, It will be called before saving any record
 */
UserSchema.pre('save', function(next) {

  // check if password is present and is modified.
  if ( this.password && this.isModified('password') ) {

    // call your hashPassword method here which will return the hashed password.
    this.password = hashPassword(this.password);

  }

  // everything is done, so let's call the next callback.
  next();

});

// lets export it, so we can import it in other files.
export default mongoose.model( 'User', UserSchema );

現在,每次我們儲存使用者時,此中介軟體將檢查密碼是否已設定並被修改 (這樣,如果未修改密碼,我們就不會對使用者密碼進行雜湊處理。)

FILENAME: App.js

import express from 'express';
import mongoose from 'mongoose';

// lets import our User Model
import User from './User';

// connect to MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://127.0.0.1:27017/database');

let app = express();
/* ... express middlewares here .... */

app.post( '/', (req, res) => {

  /*
    req.body = {
      name: 'John Doe',
      email: 'john.doe@gmail.com',
      password: '!trump'
    }
   */

  // validate the POST data

  let newUser = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });

  newUser.save( ( error, record ) => {
    if (error) {
      res.json({
        message: 'error',
        description: 'some error occoured while saving the user in database.'
      });
    } else {
      res.json({
        message: 'success',
        description: 'user details successfully saved.',
        user: record
      });
    }
  });

});

let server = app.listen( 3000, () => {
    console.log(`Server running at http://localhost:3000` );
  }
);