node 中jwt的使用token的加解密

// nodejs+express+jwt-simple

let jwt = require('jwt-simple');
//秘钥
let secret = "laney";
let time = 10;
let tokenExpiresTime = 1000 * 60 * 60 * 24 * 7;//token过期时间,毫秒为单位, 7天
 module.exports = {
      
 /*
  *检验token合法性
 */ 
 validate:function(req,res,next){
      
        let token = req.headers.token;
        if(token){
      
          let decodeToken = null;
          try {
      
            //防止假冒token解析報錯 
            // decodeToken = jwt.decode(token,secret,'HS256'); 
             decodeToken = jwt.decode(token,secret);  //解密
          } catch (err) {
      
            res.status(401).send("非法访问"); 
            return; 
          } 
        let exp = decodeToken.exp; 
        if(!exp){
     
          res.status(401).send("非法访问");
        }
        // time*60*1000   = > 10分钟
     if(exp<(Date.now()+time*60*1000)){
     
        res.send({
     code:'002',"errorMsg":"授权超时"})
      }
      next();
    }else{
      
       res.status(401).send("非法访问");
    }
  },
  /* 生成token*/ 
  makeToken(username){
      
      let Token = null; 
      //需要加密的对象
      let payload = {
      
              user:username,
              time:new Date().getTime(), 
              exp:Date.now() + tokenExpiresTime
          };
      Token = jwt.encode(payload,secret); //加密
       return Token; 
 }

 }


// jwt 编码解码方法
// jwt_encode(payload, key, algorithm, options)
// jwt_decode(token, key, noVerify, algorithm)
var express = require('express');
var mysql = require('mysql');
var router = express.Router();
let auth = require('../lib/auth.js'); 

/*建立数据库链接*/
var db = mysql.createConnection({
     
  host:'127.0.0.1',
  user: 'root',
  password: 'root',
  port: '3306',
  database: 'ruanmoutest'
});

 // Connect
db.connect((err) => {
     
  if(err) {
     
      throw(err);
  }
  console.log('MySql Connected...')
})


/* GET users listing. */
router.get('/', function(req, res, next) {
     
  //发送各种类型的响应
  res.send('respond with a resource');
  // res.end();//结束响应过程
});

//登录接口
router.post('/login',function(req,res,next){
      
  let username = req.body.username;
  let password = req.body.password;
  const adminStr = `select * from manage where username='${
       username}' and password='${
       password}'`;
 
  db.query(adminStr, (err, data) => {
     
    if (err) {
     
        console.log(err);
        res.status(500).send('database err').end();
    } else {
     
        if (data.length == 0) {
     
            res.json({
     
              code:0,
              data:0,
              message:'用户名或者密码错误'
            });
        } else {
     
            // res.send(data);
               //先从数据库里查询是否有这个用户, 如果有就开始鉴权生成token,否则不处理
            let Token = auth.makeToken(username); 
            res.json({
     
              code:1,
              data:{
     
                  user:username
              },
              token:Token
            },200)
        }
    }
});   
});
//注册
router.post('/reg',(req,res)=>{
     
   //先验证数据库里是否有这个 用户名
   var  sqlStr01 = 'select * from manage';
   db.query(sqlStr01,(err,results) => {
     
     if(err){
     
          return res.json({
     
              code:0,
              message:'注册失败,用户名已经被注册过了!',
              data:0
          })
     } else if(results.length>0) {
     
        //这里再进行数据库的插入工作
        var {
     phone,username,password} = req.query;
       
        var sqlInsert = `insert into manage(username,password,phone) values("${
       phone}","${
       username}","${
       password}")`;
        db.query(sqlInsert,(err,results) => {
     
          if(err) {
     
                return res.json({
     
                    code:0,
                    message:'获取失败'
                })
            }
            res.json({
     
                code:1,
                message:'注册成功',
                data:1
            })
         })
     }
   })
})
//员工列表
router.post('/staffs',(req,res)=>{
     
  const sqlStr = 'select * from staffs';
  db.query(sqlStr,(err,results) => {
     
      if(err) {
     
          return res.json({
     
              code:0,
              message:'获取失败',
              data:0
          })
      }
      res.json({
     
          code:1,
          message:'获取成功',
          data:results
      })
  })
})
router.use('*',[auth.validate],function(req,res,next){
      
  next();
}); 
//添加员工
router.post('/staffs/add',(req,res)=>{
     
  var {
     username,sex,age,hometown} = req.query;
       console.log(req.query);
      //  var sqp2="INSERT INTO staffs(username,age,hometown,sex) values('11','33','oo','ppp')";
   var sqlInsert = `INSERT INTO staffs(username,age,hometown,sex) values("${
       username}","${
       age}","${
       hometown}","${
       sex}")`;

  db.query(sqlInsert,(err,results) => {
     
      if(err) {
     
          return res.json({
     
              code:0,
              message:'插入数据失败',
              data:0
          })
      }
      res.json({
     
          code:1,
          message:'插入数据成功',
          data:results
      })
  })
});

//删除员工
router.delete('/staffs/delete',(req,res)=>{
     
  var {
     id} = req.query;
      console.log(req.query);  
   var sqlDelete = `DELETE FROM staffs where id=${
       id}`;
  db.query(sqlDelete,(err,results) => {
     
      if(err) {
     
          return res.json({
     
              code:0,
              message:'删除数据失败',
              data:0
          })
      }
      res.json({
     
          code:1,
          message:'删除数据成功',
          data:1
      })
  })
});

//修改员工
router.post('/staffs/update',(req,res)=>{
     
    var {
     id,username,sex,age,hometown} = req.query;
    
   var sqlDelete = `UPDATE staffs SET username = '${
       username}',sex='${
       sex}', age='${
       age}', hometown='${
       hometown}' WHERE id = ${
       id} `;
  db.query(sqlDelete,(err,results) => {
     
      if(err) {
     
          return res.json({
     
              code:0,
              message:'修改数据失败',
              data:0
          })
      }
      res.json({
     
          code:1,
          message:'修改数据成功',
          data:1
      })
  })
});

module.exports = router;

 var formLogin =document.getElementById('formLogin');
    document.getElementById('btnLogin').onclick = async function(){
     

        ajax.post("/users/login",{
     
            username:formLogin.username.value,
            password:formLogin.password.value
        }).then((res)=>{
     
            
            if(res && res.code==1){
     
                localStorage.setItem('token',res.token);
                localStorage.setItem('userInfo',res.data.user);
                createMessTipWin.tipMsg('登陆成功!',function(){
     
                    location.href="/staffs";
                });
            }
     
        });     
    }
    
        //滑块验证码
	window.addEventListener('load',function(){
     
        
		//code是后台传入的验证字符串
		var code = "jsaidaisd656",
			codeFn = new moveCode(code);
		
		//获取当前的code值
		//console.log(codeFn.getCode());

		//改变code值
		//code = '46asd546as5';
		//codeFn.setCode(code);
		
		//重置为初始状态
        //codeFn.resetCode();
     
	});

你可能感兴趣的:(node.js)