标签:
bcryptjs 比nodejs自带的crypt更好用的加密模块
环境: nodejs 4.2.3 /
一个密码验证的应用
命令行输入:init ==> command_init用于初始化mongodb数据库
命令行输入:check [name] [password] ==> command_check 用于验证密码的正确性(name用户名,password 用户密码)
‘use strict‘ const bcrypt = require(‘bcryptjs‘); const readline = require(‘readline‘); const mongoose = require("mongoose"); const Schema = mongoose.Schema; const UserShema = new Schema({ name : {type:String ,required: true }, password: {type:String ,required : true } }); const UserModel = mongoose.model(‘user_‘ , UserShema); function connect_mongodb(){ mongoose.connect(‘mongodb://localhost/test‘); } connect_mongodb(); //connect db //crypt //根据指定的字符串生产一个hash值 let _hash_fn = ( text , cb ) =>{ bcrypt.hash( text , 10 , cb ); }; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function command_init(){ var name = ‘vison‘; var password = ‘vison1987‘; _hash_fn( password , function( err , hashvalue ){ if( err ) return console.log(err); else{ let u = new UserModel({ name: name , password: hashvalue }); u.save((err)=>{console.log(err);}); } }); } function command_check(n , pwd){ UserModel.findOne({name:n} ,(err,user) =>{ if(err)return console.log(err); else{ bcrypt.compare( pwd , user.password , function(err,result){ if( err) return console.log(err); else{ if(result === true ) console.log("The password is correct"); else console.log(‘Password error‘); } }); } }); } rl.on(‘line‘,function(cmd){ //多命令以空格分隔 var cmdarray = cmd.split(" "); if( cmdarray.length === 1 ){ switch(cmd){ case "init": command_init();break; default: return ; //other command } }else if( cmdarray.length === 3 ){ if( cmdarray[0] === ‘check‘){ command_check(cmdarray[1],cmdarray[2]); } } rl.prompt(); }); rl.setPrompt("v+>"); rl.prompt();
启动mongod服务器 : mongod --dbpath [Your datebase path]
运行结果:
标签:
原文地址:http://www.cnblogs.com/visonme/p/5122691.html