码迷,mamicode.com
首页 > Web开发 > 详细

nodejs加密模块bcryptjs应用

时间:2016-01-11 23:40:37      阅读:3792      评论:0      收藏:0      [点我收藏+]

标签:

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]

运行结果:

技术分享

nodejs加密模块bcryptjs应用

标签:

原文地址:http://www.cnblogs.com/visonme/p/5122691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!