var express = require('express');
var router = express.Router();
var models = require('../../models')
const request = require('request');// 用来请求接口
var jwt = require('jsonwebtoken');// 加密
router.post('/login',function(req,res,next){
var code = req.body.code
request.get({
url:'https://api.weixin.qq.com/sns/jscode2session',
json:true,
qs:{
grant_type:'authorization_code',
appid:'wx4a9965771e11b4bd',
secret:'e94f1c12cb09e31bff0f12826f945b60',
js_code:code
}
},async(err,respose,data)=>{
// 1. 判断data里面有没有 errcode,有就是token过期了,直接return
if(data.errcode){
return res.json({success:false,msg:'code已过期'})
}
// 2.否则就 查询openid存不存在
let user = await models.User.findOne({
where:{openid:data.openid}
})
// 3.如果openid不存在,就直接添加这个openid 和 普通权限
if(!user){
user = await models.User.create({openid:data.openid,admin:0})
}
var token = jwt.sign({
user:{
id:user.id,
openid:data.openid,
admin:false
}
},process.env.SECRET,{expiresIn:60 * 60 * 24 * 7})
res.json({success:true,message:'登陆成功',token:token})
})
})
module.exports = router;