crypto
crypto 模塊提供了加密的功能,包括對 OpenSSL 的哈希铺峭、HMAC墓怀、加密、解密逛薇、簽名捺疼、以及驗證功能的一整套封裝
const crypto = require('crypto'); // 使用require('crypto')來訪問該模塊
const secret = 'abcdefg';
const hash = crypto.createHamc('sha256', secret).update('I love cupcakes').digest('hex');
console.log(hash);
想要了解更多關(guān)于crypto模塊的知識可以去看相關(guān)的知識,這里就不多說了
鏈接:http://nodejs.cn/api/crypto.html
實踐
1. 關(guān)鍵代碼
注冊登錄要以相同的方式進(jìn)行處理永罚,這樣子的密碼才會一致
const crypto = require('crypto'); // 引入加密模塊
let userPwd = req.body.userPwd,
md5 = crypto.createHash("md5"); // md5加密
let newPwd = md5.update(userPwd).digest("hex");
2. 前置
引入模塊啤呼、參數(shù)定義、數(shù)據(jù)庫連接
require('./../util/util');
let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
let Users = require('../models/users');
const crypto = require('crypto'); // 引入加密模塊
const SUCCESS = 2000; // 請求成功
const NO_LOGIN = 4003; // 未登錄
const NO_POWER = 4001; // 沒有權(quán)限
const ERROR = 5000; // 請求失敗
const EXCEPTION = 4005; // 異常
const WARN = 2001; // 警告
mongoose.connect('mongodb://127.0.0.1:27017/teacher', {useNewUrlParser: true});
mongoose.connection.on('connected', function () {
console.log('MongoDB connected success.');
});
mongoose.connection.on('error', function () {
console.log('MongoDB connected fail.');
});
mongoose.connection.on('disconnected', function () {
console.log('MongoDB connected disconnected.')
});
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
3. 注冊
// 注冊
router.post('/register', function (req, res, next) {
let phone = req.body.phone,
userPwd = req.body.userPwd,
md5 = crypto.createHash("md5");
let newPwd = md5.update(userPwd).digest("hex");
let param = {
createDate: '',
phone: phone,
userPwd: newPwd
}
// 檢驗手機(jī)號碼是否被注冊過
Users.findOne({phone: param.phone}, function (err, doc) {
if (err) {
res.json({
code: ERROR,
msg: err.message,
result: ''
})
} else {
if (doc) { // 手機(jī)號碼被注冊過
res.json({
code: WARN,
msg: '該手機(jī)號碼已被注冊過',
result: ''
})
} else { // 手機(jī)號碼沒有被注冊過
let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
param.createDate = createDate;
Users.insertMany([param], function(err2, doc2) {
if (err2) {
res.json({
code: ERROR,
msg: err.message,
result: ''
})
} else {
res.json({
code: SUCCESS,
msg: '注冊成功',
result: doc2
})
}
})
}
}
})
});
4. 登錄
// 登錄
router.post('/login', function (req, res, next) {
let phone = req.body.phone,
userPwd = req.body.userPwd;
let md5 = crypto.createHash("md5");
let pwd = md5.update(userPwd).digest("hex");
let param = {
phone: phone,
userPwd: pwd
}
Users.findOne(param, function(err, doc) {
if (err) {
res.json({
code: ERROR,
msg: err.message,
result: ''
})
} else {
if (doc) {
// 存儲cookie
res.cookie('userId', doc._id, {
path: '/',
maxAge: 1000 * 60 * 60
});
res.json ({
code: SUCCESS,
msg: '登錄成功',
result: {
phone: doc.phone,
userId: doc._id
}
})
} else {
res.json ({
code: WARN,
msg: '賬號或密碼錯誤',
result: ''
})
}
}
})
});