From 6d56a48ae8a1526f7e492f45e1840a8dbbbce2e1 Mon Sep 17 00:00:00 2001 From: SUNWUYUAN <1847261658@qq.com> Date: Sat, 13 Jan 2024 16:16:20 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=BF=E7=94=A8=20jwt=20token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.js | 120 +++++++++++++++++++++++---------------- server/lib/fuck.js | 24 +++++--- server/router_admin.js | 4 +- server/router_api.js | 2 +- server/router_my.js | 50 ++++++++-------- server/router_python.js | 32 +++++------ server/router_scratch.js | 40 ++++++------- server/router_user.js | 87 +++++++++++----------------- 8 files changed, 185 insertions(+), 174 deletions(-) diff --git a/app.js b/app.js index e4f6497..ce13d29 100644 --- a/app.js +++ b/app.js @@ -1,6 +1,7 @@ var express = require("express"); var app = express(); var http = require("http"); +const jwt = require("jsonwebtoken"); // 首先确保安装了jsonwebtoken库 //环境变量 require("dotenv").config(); @@ -18,13 +19,15 @@ const logger = winston.createLogger({ ), defaultMeta: { service: "ourworld-service" }, transports: [ - process.env.AXIOM_TOKEN ? new AxiomTransport({ - dataset: process.env.AXIOM_DATASET, - token: process.env.AXIOM_TOKEN, - }) : null, + process.env.AXIOM_TOKEN + ? new AxiomTransport({ + dataset: process.env.AXIOM_DATASET, + token: process.env.AXIOM_TOKEN, + }) + : null, new winston.transports.Console(), ], -}); +}); // 创建自定义Stream,将日志写入Winston const winstonStream = { @@ -73,17 +76,7 @@ var corsOptions = { app.use(cors(corsOptions)); // 应用CORS配置函数 //设置环境变量 -var session = require("express-session"); -app.use( - session({ - secret: process.env.SessionSecret, - resave: false, - name: "OurWorld-session", - saveUninitialized: true, - cookie: { secure: false }, - }) -); - +//var session = require("express-session"); app.use( session({ secret: process.env.SessionSecret, resave: false, name: "OurWorld-session", saveUninitialized: true, cookie: { secure: false }, }) ); //express 的cookie的解析组件 var cookieParser = require("cookie-parser"); app.use(cookieParser(process.env.SessionSecret)); @@ -108,7 +101,7 @@ app.set("view engine", "ejs"); var DB = require("./server/lib/database.js"); //设置静态资源路径 -if (process.env.localstatic == 'true') { +if (process.env.localstatic == "true") { app.use(process.env.staticurl, express.static(process.env.staticpath)); } //全局变量 @@ -117,46 +110,78 @@ global.dirname = __dirname; //启动http(80端口)================================== http.createServer(app).listen(3000, "0.0.0.0", function () { console.log("Listening on http://localhost:3000"); -}); -//平台总入口 +}); // 平台总入口 app.all("*", function (req, res, next) { //console.log(req.method +' '+ req.url + " IP:" + req.ip); - if (req.session["userid"] == undefined && req.signedCookies["userid"]) { - req.session["userid"] = req.signedCookies["userid"]; - req.session["username"] = req.signedCookies["username"]; - req.session["nickname"] = req.signedCookies["nickname"]; - - //判断系统管理员权限:此处写死,无需从数据库获取 - req.session["is_admin"] = 0; - if (req.session["username"].indexOf(process.env.adminuser) == 0) { - if (req.session["username"] == process.env.adminuser) { - req.session["is_admin"] = 1; + + const token = req.cookies.token || req.body.token || req.headers["token"]; // 获取JWT令牌 + + if (token) { + jwt.verify(token, process.env.jwttoken, (err, decodedToken) => { + // 解析并验证JWT + if (err) { + // 如果验证失败,清除本地登录状态 + res.locals = { + login: false, + userid: "", + username: "", + nickname: "", + is_admin: 0, + }; + //console.log("JWT验证失败: " + err.message); } else { - let no = parseInt(req.session["username"].substring(8)); - if (0 <= no && no < 100) { - req.session["is_admin"] = 1; + // 如果验证成功,将用户信息存储在res.locals和session中 + let userInfo = decodedToken; + res.locals.userid = userInfo.userid; + res.locals.username = userInfo.username; + res.locals.nickname = userInfo.nickname; + res.locals["is_admin"] = 0; + if (userInfo.username == process.env.adminuser) { + res.locals["is_admin"] = 1; } + //console.log("JWT验证成功: " + userInfo.username); + //console.log('调试用户信息(session):'+res.locals.userid+','+res.locals.username+','+res.locals.nickname+','+res.locals.is_admin); + + + res.locals = { + login: true, + userid: res.locals.userid, + username: res.locals.username, + nickname: res.locals.nickname, + is_admin: res.locals["is_admin"], + }; + + //console.log('调试用户信息(locals ):'+res.locals.userid+','+res.locals.username+','+res.locals.nickname+','+res.locals.is_admin); + } - } - } - if (req.session["userid"]) { - res.locals["login"] = true; - res.locals["userid"] = req.session["userid"]; - res.locals["username"] = req.session["username"]; - res.locals["nickname"] = req.session["nickname"]; - res.locals["is_admin"] = req.session["is_admin"]; + next(); + }); } else { - res.locals["login"] = false; - res.locals["userid"] = ""; - res.locals["username"] = ""; - res.locals["nickname"] = ""; - res.locals["is_admin"] = 0; + // 如果未找到token,则清除本地登录状态 + res.locals = { + login: false, + userid: "", + username: "", + nickname: "", + is_admin: 0, + }; + console.log("未找到JWT Token"); + next(); } - - next(); }); +// 辅助函数:从请求头或请求体中获取JWT Token +function getTokenFromRequest(req) { + if (req.headers.token && req.headers.token) { + return req.headers.token.split(" ")[1]; + } else if (req.body && req.body.token) { + return req.body.token; + } else if (req.query && req.query.token) { + return req.query.token; + } + return null; +} //首页 app.get("/", function (req, res) { //获取已分享的作品总数:1:普通作品,2:推荐的优秀作品 @@ -184,7 +209,6 @@ app.get("/", function (req, res) { // res.locals["ads"] = encodeURIComponent(JSON.stringify(ADS)); - //}); res.render("ejs/index.ejs"); }); diff --git a/server/lib/fuck.js b/server/lib/fuck.js index 1394aea..a4e3f3a 100644 --- a/server/lib/fuck.js +++ b/server/lib/fuck.js @@ -2,9 +2,7 @@ const crypto = require("crypto"); var base64url = require("base64url"); const { PasswordHash } = require("phpass"); - -// 配置密钥 -var jwt = require("jsonwebtoken"); +const jwt = require("jsonwebtoken"); // 首先确保安装了jsonwebtoken库 var fs = require("fs"); @@ -15,7 +13,6 @@ var accessKey = process.env.qiniuaccessKey; var secretKey = process.env.qiniusecretKey; var mac = new qiniu.auth.digest.Mac(accessKey, secretKey); - exports.qiniuupdate = function qiniuupdate(name, file) { var options = { scope: process.env.qiniubucket, @@ -39,7 +36,7 @@ exports.qiniuupdate = function qiniuupdate(name, file) { } if (respInfo.statusCode == 200) { console.log(respBody); - // fs.unlink(file, function (err) { if (err) { console.log("fe"); } }); + // fs.unlink(file, function (err) { if (err) { console.log("fe"); } }); } else { console.log(respInfo.statusCode); console.log(respBody); @@ -74,8 +71,9 @@ exports.phoneTest = function (No) { //常用数据结构 exports.msg_fail = { status: "fail", msg: "请再试一次19" }; -exports.randomString = function randomString(len) { - len = len || 32; +exports.randomPassword = function randomPassword(len) { + len = len || 12; + len = len - 4; var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/ var maxPos = $chars.length; @@ -83,6 +81,7 @@ exports.randomString = function randomString(len) { for (var i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } + pwd = pwd + "@Aa1"; return pwd; }; @@ -102,6 +101,17 @@ exports.jwt = function (data) { console.log(token); return token; }; +exports.GenerateJwt = function (id, email, nickname) { + token = jwt.sign( + { + userid: id, + username: email, + nickname: nickname, + }, + process.env.jwttoken + , { expiresIn: '72h' }); + return token; +}; exports.hashpw = function (data) { var hashok = new PasswordHash().hashPassword(data); diff --git a/server/router_admin.js b/server/router_admin.js index 0cc19dc..542d44e 100644 --- a/server/router_admin.js +++ b/server/router_admin.js @@ -1001,7 +1001,7 @@ router.get('/material/sprite/worklist', function (req, res) { _title = ` AND title LIKE '%${req.query['t']}%' `; } - var SQL =`SELECT count(id) AS c FROM scratch WHERE authorid=${req.session.userid} ${_title}`; + var SQL =`SELECT count(id) AS c FROM scratch WHERE authorid=${res.locals.userid} ${_title}`; DB.query(SQL, function(err, count){ if (err || count.length==0 || count[0].c==0) { res.status(200).send({'count':0,'data':[]}); @@ -1011,7 +1011,7 @@ router.get('/material/sprite/worklist', function (req, res) { //获取当前数据集合 var page = parseInt(req.query['page']); var limit = parseInt(req.query['limit']); - var SQL =`SELECT id,title FROM scratch WHERE authorid=${req.session.userid} ${_title} ORDER BY time DESC LIMIT ${(page-1)*limit}, ${limit}`; + var SQL =`SELECT id,title FROM scratch WHERE authorid=${res.locals.userid} ${_title} ORDER BY time DESC LIMIT ${(page-1)*limit}, ${limit}`; DB.query(SQL, function (err, data) { if (err) { res.status(200).send({'count':0,'data':[]}); diff --git a/server/router_api.js b/server/router_api.js index 47b6ec3..3031f99 100644 --- a/server/router_api.js +++ b/server/router_api.js @@ -70,7 +70,7 @@ router.get('/play', function (req, res) { return; } - res.locals['is_author'] = (SCRATCH[0].authorid==req.session.userid)?true:false; + res.locals['is_author'] = (SCRATCH[0].authorid==res.locals.userid)?true:false; res.locals['project'] = SCRATCH[0]; res.render('ejs/scratch/scratch_play.ejs'); }); diff --git a/server/router_my.js b/server/router_my.js index 34f4d69..bf5d160 100644 --- a/server/router_my.js +++ b/server/router_my.js @@ -34,7 +34,7 @@ router.get('/scratch', function (req, res) { ` count(case when state=0 then 1 end) AS state0_count, `+ ` count(case when state=1 then 1 end) AS state1_count, `+ ` count(case when state=2 then 1 end) AS state2_count `+ - ` FROM scratch WHERE authorid=${req.session.userid}`; + ` FROM scratch WHERE authorid=${res.locals['userid']}`; DB.query(SQL, function(err, data){ if (err){ @@ -56,7 +56,7 @@ router.get('/python', function (req, res) { ` count(case when state=0 then 1 end) AS state0_count, `+ ` count(case when state=1 then 1 end) AS state1_count, `+ ` count(case when state=2 then 1 end) AS state2_count `+ - ` FROM python WHERE authorid=${req.session.userid}`; + ` FROM python WHERE authorid=${res.locals.userid}`; DB.query(SQL, function(err, data){ if (err){ @@ -77,7 +77,7 @@ router.post('/getScratchProjects', function (req, res) { var limit = parseInt(req.body.limit); //每页显示的作品数 var state = parseInt(req.body.state); //每页显示的作品状态 - var SQL = `SELECT id, title,view_count,description FROM scratch WHERE authorid=${req.session.userid} AND state=${state} ORDER BY view_count DESC LIMIT ${(curr-1)*limit}, ${limit}`; + var SQL = `SELECT id, title,view_count,description FROM scratch WHERE authorid=${res.locals.userid} AND state=${state} ORDER BY view_count DESC LIMIT ${(curr-1)*limit}, ${limit}`; DB.query(SQL, function (err, data) { if (err) { res.status(200).send([]); @@ -93,7 +93,7 @@ router.post('/getPythonProjects', function (req, res) { var limit = parseInt(req.body.limit); //每页显示的作品数 var state = parseInt(req.body.state); //每页显示的作品状态 - var SQL = `SELECT id, title,view_count,description FROM python WHERE authorid=${req.session.userid} AND state=${state} ORDER BY view_count DESC LIMIT ${(curr-1)*limit}, ${limit}`; + var SQL = `SELECT id, title,view_count,description FROM python WHERE authorid=${res.locals.userid} AND state=${state} ORDER BY view_count DESC LIMIT ${(curr-1)*limit}, ${limit}`; DB.query(SQL, function (err, data) { if (err) { res.status(200).send([]); @@ -105,7 +105,7 @@ router.post('/getPythonProjects', function (req, res) { //分享Scratch项目 router.post('/scratch/share', function (req, res) { - var SQL = `UPDATE scratch SET state=1 WHERE id=${ req.body['id']} AND authorid=${req.session.userid} LIMIT 1`; + var SQL = `UPDATE scratch SET state=1 WHERE id=${ req.body['id']} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(SQL, function (err, d) { if (err) { res.status(200).send(I.msg_fail); @@ -118,7 +118,7 @@ router.post('/scratch/share', function (req, res) { //分享Scratch项目 router.post('/python/share', function (req, res) { - var SQL = `UPDATE python SET state=1 WHERE id=${ req.body['id']} AND authorid=${req.session.userid} LIMIT 1`; + var SQL = `UPDATE python SET state=1 WHERE id=${ req.body['id']} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(SQL, function (err, d) { if (err) { res.status(200).send(I.msg_fail); @@ -132,7 +132,7 @@ router.post('/python/share', function (req, res) { //简介 router.post('/scratch/setdescription', function (req, res) { var SET= {description:req.body['description']}; - var SQL = `UPDATE scratch SET ? WHERE id=${ req.body['id']} AND authorid=${req.session.userid} LIMIT 1`; + var SQL = `UPDATE scratch SET ? WHERE id=${ req.body['id']} AND authorid=${res.locals.userid} LIMIT 1`; DB.qww(SQL,SET, function (err, d) { if (err) { res.status(200).send(I.msg_fail); @@ -146,7 +146,7 @@ router.post('/scratch/setdescription', function (req, res) { //简介 router.post('/python/setdescription', function (req, res) { var SET= {description:req.body['description']}; - var SQL = `UPDATE python SET ? WHERE id=${ req.body['id']} AND authorid=${req.session.userid} LIMIT 1`; + var SQL = `UPDATE python SET ? WHERE id=${ req.body['id']} AND authorid=${res.locals.userid} LIMIT 1`; DB.qww(SQL,SET, function (err, d) { if (err) { res.status(200).send(I.msg_fail); @@ -160,7 +160,7 @@ router.post('/python/setdescription', function (req, res) { //取消分享Scratch项目 router.post('/scratch/noshare', function (req, res) { - var SQL = `UPDATE scratch SET state=0 WHERE id=${ req.body['id']} AND authorid=${req.session.userid} LIMIT 1`; + var SQL = `UPDATE scratch SET state=0 WHERE id=${ req.body['id']} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(SQL, function (err, d) { if (err) { res.status(200).send(I.msg_fail); @@ -173,7 +173,7 @@ router.post('/scratch/noshare', function (req, res) { //取消分享Scratch项目 router.post('/python/noshare', function (req, res) { - var SQL = `UPDATE python SET state=0 WHERE id=${ req.body['id']} AND authorid=${req.session.userid} LIMIT 1`; + var SQL = `UPDATE python SET state=0 WHERE id=${ req.body['id']} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(SQL, function (err, d) { if (err) { res.status(200).send(I.msg_fail); @@ -189,7 +189,7 @@ router.post('/python/noshare', function (req, res) { //删除Scratch项目 router.post('/scratch/del', function (req, res) { - var DEL = `DELETE FROM scratch WHERE id=${ req.body['id']} AND authorid=${req.session.userid} LIMIT 1`; + var DEL = `DELETE FROM scratch WHERE id=${ req.body['id']} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(DEL, function (err, d) { if (err) { res.status(200).send(I.msg_fail); @@ -211,7 +211,7 @@ router.post('/scratch/del', function (req, res) { //删除Scratch项目 router.post('/python/del', function (req, res) { - var DEL = `DELETE FROM python WHERE id=${ req.body['id']} AND authorid=${req.session.userid} LIMIT 1`; + var DEL = `DELETE FROM python WHERE id=${ req.body['id']} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(DEL, function (err, d) { if (err) { res.status(200).send(I.msg_fail); @@ -234,7 +234,7 @@ router.post('/python/del', function (req, res) { //个人设置 router.get('/info', function (req, res) { res.locals['curItem']['set'] = 'active'; - var SQL = `SELECT * FROM user WHERE id=${req.session.userid} LIMIT 1`; + var SQL = `SELECT * FROM user WHERE id=${res.locals.userid} LIMIT 1`; DB.query(SQL, function (err, USER) { if (err || USER.length == 0) { res.render('ejs/404.ejs'); @@ -257,7 +257,7 @@ router.post('/set/avatar', function (req, res) { } tmppath = req['files']['file']['path']; - newpath = `./data/user/${req.session.userid}.png`; + newpath = `./data/user/${res.locals.userid}.png`; fs.rename(tmppath, newpath,function (err) { if (err) { res.status(200).send( {'status':'文件上传失败'} ); @@ -274,7 +274,7 @@ router.post('/set/avatar', function (req, res) { const hashValue = hash.digest('hex'); // 上传到七牛云 I.qiniuupdate(`user/${hashValue}.png`,newpath); - var UPDATE = `UPDATE user SET ? WHERE id=${req.session.userid} LIMIT 1`; + var UPDATE = `UPDATE user SET ? WHERE id=${res.locals.userid} LIMIT 1`; var SET = { 'images':hashValue, }; @@ -292,7 +292,7 @@ router.post('/set/avatar', function (req, res) { }); //修改个人信息 router.post('/set/userinfo', function (req, res) { - var UPDATE = `UPDATE user SET ? WHERE id=${req.session.userid} LIMIT 1`; + var UPDATE = `UPDATE user SET ? WHERE id=${res.locals.userid} LIMIT 1`; var SET = { 'nickname':req.body['nickname'], 'motto': req.body['aboutme'], @@ -304,12 +304,10 @@ router.post('/set/userinfo', function (req, res) { res.status(200).send( {'status':'请再试一次'}); return; } - - req.session['nickname'] = req.body['nickname']; + res.locals['nickname'] = req.body['nickname']; - res.cookie('nickname', req.body['nickname'], { 'maxAge': 604800000, 'signed': true }); - - var UPDATE = `UPDATE wl_Users SET ? WHERE email='${req.session.username}' LIMIT 1`; + + var UPDATE = `UPDATE wl_Users SET ? WHERE email='${res.locals.username}' LIMIT 1`; var SET = { 'display_name':req.body['nickname'], }; @@ -319,7 +317,7 @@ router.post('/set/userinfo', function (req, res) { return; } - + res.cookie("token",I.GenerateJwt(res.locals["userid"],res.locals["username"],res.locals["nickname"]),{maxAge: 604800000,}); res.status(200).send( {'status': '个人信息修成成功'}); }); @@ -327,17 +325,17 @@ router.post('/set/userinfo', function (req, res) { }); //修改密码:动作 router.post('/set/pw', function (req, res) { - var oldPW = I.md5(I.md5(req.body['oldpw'])+req.session.username); + var oldPW = I.md5(I.md5(req.body['oldpw'])+res.locals.username); //console.log(oldPW) //console.log(req.body['oldpw']) - //console.log(req.session.username) + //console.log(res.locals.username) //console.log(req.body['newpw']) - var newPW = I.md5(I.md5(req.body['newpw'])+req.session.username); + var newPW = I.md5(I.md5(req.body['newpw'])+res.locals.username); //console.log(newPW) //判断用户是手机账号用户、校区自己生成的账号 SET = {pwd:newPW}; - UPDATE = `UPDATE user SET ? WHERE id=${req.session.userid} AND pwd="${oldPW}" LIMIT 1`; + UPDATE = `UPDATE user SET ? WHERE id=${res.locals.userid} AND pwd="${oldPW}" LIMIT 1`; DB.qww(UPDATE, SET, function (err, u) { if (err) { res.status(200).send({'status': '请再试一次'}); diff --git a/server/router_python.js b/server/router_python.js index e331235..321cdb0 100644 --- a/server/router_python.js +++ b/server/router_python.js @@ -86,7 +86,7 @@ router.post('/play/like', function (req, res) { } var pid = req.body['pid']; - var SQL = `SELECT id FROM python_like WHERE userid=${req.session.userid} AND projectid=${pid} LIMIT 1`; + var SQL = `SELECT id FROM python_like WHERE userid=${res.locals.userid} AND projectid=${pid} LIMIT 1`; DB.query(SQL, function(err, LIKE){ if (err){ res.status(200).send( {'status': 'failed','msg': '数据错误,请再试一次'}); @@ -102,7 +102,7 @@ router.post('/play/like', function (req, res) { return; } - var INSERT =`INSERT INTO python_like (userid, projectid) VALUES (${req.session.userid}, ${pid})`; + var INSERT =`INSERT INTO python_like (userid, projectid) VALUES (${res.locals.userid}, ${pid})`; DB.query(INSERT, function(err, LIKE){ if (err || LIKE.affectedRows == 0){ res.status(200).send( {'status': 'failed','msg': '数据错误,请再试一次'}); @@ -142,7 +142,7 @@ router.post('/play/favo', function (req, res) { } var pid = req.body['pid']; - var SQL = `SELECT id FROM python_favo WHERE userid=${req.session.userid} AND projectid=${pid} LIMIT 1`; + var SQL = `SELECT id FROM python_favo WHERE userid=${res.locals.userid} AND projectid=${pid} LIMIT 1`; DB.query(SQL, function(err, FAVO){ if (err){ res.status(200).send( {'status': 'failed','msg': '数据错误,请再试一次'}); @@ -158,7 +158,7 @@ router.post('/play/favo', function (req, res) { return; } - var INSERT =`INSERT INTO python_favo (userid, projectid) VALUES (${req.session.userid}, ${pid})`; + var INSERT =`INSERT INTO python_favo (userid, projectid) VALUES (${res.locals.userid}, ${pid})`; DB.query(INSERT, function(err, FAVO){ if (err || FAVO.affectedRows == 0){ res.status(200).send( {'status': 'failed','msg': '数据错误,请再试一次'}); @@ -228,14 +228,12 @@ router.post('/getWork', function (req, res) { if (!res.locals.login){//未登录时,只能打开已发布的作品 SQL = `SELECT * FROM python WHERE id=${projectid} AND state>0`; }else { - if (req.session['is_admin'] == 1) { - SQL = `SELECT * FROM python WHERE id=${projectid}`; - } else { + //作品编辑:能够打开一个作品的几种权限: //1、自己的作品; //2、开源的作品; - SQL = `SELECT * FROM python WHERE id=${projectid} AND (authorid=${req.session.userid} OR state>0)`; - } + SQL = `SELECT * FROM python WHERE id=${projectid} AND (authorid=${res.locals.userid} OR state>0)`; + } } @@ -257,14 +255,14 @@ router.post('/getWork', function (req, res) { // python 保存 router.post('/save', function (req, res) { - if (!req.session.userid){ + if (!res.locals.userid){ res.status(200).send({status: "x", msg: "请先登录" }); return; } // 新作品 if (req.body.id == '0'){ - var INSERT =`INSERT INTO python (authorid, title,src) VALUES (${req.session.userid}, ?, ?)`; + var INSERT =`INSERT INTO python (authorid, title,src) VALUES (${res.locals.userid}, ?, ?)`; var SET = [req.body.title,req.body.data] DB.qww(INSERT, SET, function (err, newPython) { if (err || newPython.affectedRows==0) { @@ -279,7 +277,7 @@ router.post('/save', function (req, res) { } // 旧作品 - var UPDATE =`UPDATE python SET ? WHERE id=${req.body.id} AND authorid=${req.session.userid} LIMIT 1`; + var UPDATE =`UPDATE python SET ? WHERE id=${req.body.id} AND authorid=${res.locals.userid} LIMIT 1`; var SET = { title:req.body.title, src:req.body.data, @@ -296,13 +294,13 @@ router.post('/save', function (req, res) { }); router.post('/publish', function (req, res) { - if (!req.session.userid){ + if (!res.locals.userid){ res.status(200).send({status: "x", msg: "请先登录" }); return; } var state = req.body.s=="0"? 1:0; - var UPDATE = `UPDATE python SET state=${state} WHERE id=${req.body.id} AND authorid=${req.session.userid} LIMIT 1`; + var UPDATE = `UPDATE python SET state=${state} WHERE id=${req.body.id} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(UPDATE, function (err, u) { if (err) { res.status(200).send({status: "x", msg: "操作失败!"}); @@ -346,7 +344,7 @@ router.post('/YxLibrary_data', function (req, res) { router.all('*', function (req, res, next) { - if (!req.session.userid){ + if (!res.locals.userid){ res.status(200).send({status: "x", msg: "请先登录" }); return; } @@ -355,7 +353,7 @@ router.all('*', function (req, res, next) { }); router.post('/MyLibrary_count', function (req, res) { - var SQL = `SELECT count(id) AS c FROM python WHERE authorid=${req.session.userid}`; + var SQL = `SELECT count(id) AS c FROM python WHERE authorid=${res.locals.userid}`; DB.query(SQL, function (err, COUNT){ if (err) { res.status(200).send({status:'ok', total: 0}); @@ -368,7 +366,7 @@ router.post('/MyLibrary_count', function (req, res) { router.post('/MyLibrary_data', function (req, res) { //获取当前数据集合:以被浏览次数降序排列,每次取16个 var page = parseInt(req.body.page); - SQL = `SELECT id, state, time, title FROM python WHERE authorid=${req.session.userid} ORDER BY time DESC LIMIT ${(page-1)*16},${16}`; + SQL = `SELECT id, state, time, title FROM python WHERE authorid=${res.locals.userid} ORDER BY time DESC LIMIT ${(page-1)*16},${16}`; DB.query(SQL, function (err, data) { if (err) { res.status(200).send({status:'ok', data:[]}); diff --git a/server/router_scratch.js b/server/router_scratch.js index efcc4ff..972ce8e 100644 --- a/server/router_scratch.js +++ b/server/router_scratch.js @@ -114,8 +114,8 @@ router.get("/play", function (req, res) { ` user.nickname AS author_nickname,` + ` user.motto AS author_motto` + ` FROM scratch ` + - ` LEFT JOIN scratch_like ON (scratch_like.userid=${req.session.userid} AND scratch_like.projectid=${req.query.id}) ` + - ` LEFT JOIN scratch_favo ON (scratch_favo.userid=${req.session.userid} AND scratch_favo.projectid=${req.query.id}) ` + + ` LEFT JOIN scratch_like ON (scratch_like.userid=${res.locals.userid} AND scratch_like.projectid=${req.query.id}) ` + + ` LEFT JOIN scratch_favo ON (scratch_favo.userid=${res.locals.userid} AND scratch_favo.projectid=${req.query.id}) ` + ` LEFT JOIN user ON (user.id=scratch.authorid) ` + ` WHERE scratch.id=${req.query.id} AND scratch.state>=1 LIMIT 1`; } @@ -128,7 +128,7 @@ router.get("/play", function (req, res) { } res.locals["is_author"] = - SCRATCH[0].authorid == req.session.userid ? true : false; + SCRATCH[0].authorid == res.locals.userid ? true : false; res.locals["project"] = SCRATCH[0]; ////console.log(SCRATCH[0]); res.render("ejs/scratch/scratch_play.ejs"); @@ -172,7 +172,7 @@ router.post("/play/favo", function (req, res) { } var pid = req.body["pid"]; - var SQL = `SELECT id FROM scratch_favo WHERE userid=${req.session.userid} AND projectid=${pid} LIMIT 1`; + var SQL = `SELECT id FROM scratch_favo WHERE userid=${res.locals.userid} AND projectid=${pid} LIMIT 1`; DB.query(SQL, function (err, FAVO) { if (err) { res.status(200).send({ status: "failed", msg: "数据错误,请再试一次" }); @@ -190,7 +190,7 @@ router.post("/play/favo", function (req, res) { return; } - var INSERT = `INSERT INTO scratch_favo (userid, projectid) VALUES (${req.session.userid}, ${pid})`; + var INSERT = `INSERT INTO scratch_favo (userid, projectid) VALUES (${res.locals.userid}, ${pid})`; DB.query(INSERT, function (err, FAVO) { if (err || FAVO.affectedRows == 0) { res @@ -237,7 +237,7 @@ router.post("/play/openSrc", function (req, res) { } var pid = req.body["pid"]; - var SQL = `SELECT state FROM scratch WHERE id=${pid} AND authorid=${req.session.userid} LIMIT 1`; + var SQL = `SELECT state FROM scratch WHERE id=${pid} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(SQL, function (err, RECO) { if (err || RECO.length == 0) { res.status(200).send({ status: "failed", msg: "数据错误,请再试一次" }); @@ -297,11 +297,11 @@ router.post("/project/:projectid", function (req, res) { //2、开源的作品; //3、课堂用例、作业模板:购买课程后可以打开; //4、课堂作业作品:课程老师可以打开; - if (req.session["is_admin"] == 1) { + if (req.locals["is_admin"] == 1) { SQL = `SELECT * FROM scratch WHERE id=${projectid}`; } else { - SQL = `SELECT * FROM scratch WHERE id=${projectid} AND (authorid=${req.session.userid} OR state>0)`; - //(AND (courseid IN (SELECT courseid FROM student WHERE studentid=${req.session.userid} AND coursepayid>0))) + SQL = `SELECT * FROM scratch WHERE id=${projectid} AND (authorid=${res.locals.userid} OR state>0)`; + //(AND (courseid IN (SELECT courseid FROM student WHERE studentid=${res.locals.userid} AND coursepayid>0))) } } } @@ -314,7 +314,7 @@ router.post("/project/:projectid", function (req, res) { if (SCRATCH.length == 0) { //4、课堂作业作品:课程老师可以打开; - SQL = `SELECT * FROM scratch WHERE id=${projectid} AND courseid!=0 AND (courseid IN (SELECT courseid FROM class WHERE teacherid=${req.session.userid}))`; + SQL = `SELECT * FROM scratch WHERE id=${projectid} AND courseid!=0 AND (courseid IN (SELECT courseid FROM class WHERE teacherid=${res.locals.userid}))`; DB.query(SQL, function (err, SCRATCH) { if (err || SCRATCH.length == 0) { res.status(200).send({ status: "作品不存在或无权打开" }); //需要Scratch内部处理 @@ -328,7 +328,7 @@ router.post("/project/:projectid", function (req, res) { } }); - SCRATCH[0]["teacher_id"] = req.session.userid; + SCRATCH[0]["teacher_id"] = res.locals.userid; res.status(200).send({ status: "ok", src: SCRATCH[0] }); }); @@ -366,7 +366,7 @@ router.post("/saveProjcetTitle", function (req, res) { res.status(404); return; } - var UPDATE = `UPDATE scratch SET title=? WHERE id=${req.body.id} AND authorid=${req.session.userid} LIMIT 1`; + var UPDATE = `UPDATE scratch SET title=? WHERE id=${req.body.id} AND authorid=${res.locals.userid} LIMIT 1`; var VAL = [`${req.body.title}`]; DB.qww(UPDATE, VAL, function (err, SCRATCH) { if (err) { @@ -392,7 +392,7 @@ router.put("/projects/:projectid", function (req, res) { return; } - if (SWork[0].authorid != req.session.userid) { + if (SWork[0].authorid != res.locals.userid) { res.status(404).send({}); return; } @@ -452,7 +452,7 @@ router.post("/shareProject/:projectid", function (req, res) { } //只能分享自己的作品 - var UPDATE = `UPDATE scratch SET state=${s} WHERE id=${req.params.projectid} AND authorid=${req.session.userid} LIMIT 1`; + var UPDATE = `UPDATE scratch SET state=${s} WHERE id=${req.params.projectid} AND authorid=${res.locals.userid} LIMIT 1`; DB.query(UPDATE, function (err, U) { if (err) { res.status(200).send({ status: "x" }); @@ -475,7 +475,7 @@ router.post("/projects", function (req, res) { if (req.query.title) { title = req.query.title; } - var INSERT = `INSERT INTO scratch (authorid, title, src) VALUES (${req.session.userid}, ?, ?)`; + var INSERT = `INSERT INTO scratch (authorid, title, src) VALUES (${res.locals.userid}, ?, ?)`; var VAL = [title, `${JSON.stringify(req.body)}`]; DB.qww(INSERT, VAL, function (err, newScratch) { if (err || newScratch.affectedRows == 0) { @@ -624,7 +624,7 @@ router.post("/getMyProjectLibrary", function (req, res) { WHERE += ` AND title LIKE '%${req.body.f}%'`; } - var SELECT = `SELECT id, title, time, state FROM scratch WHERE authorid=${req.session["userid"]} ${WHERE} ORDER BY time DESC LIMIT ${req.body.l},${req.body.n}`; //正式版本中,需要限定作者本身的作品 + var SELECT = `SELECT id, title, time, state FROM scratch WHERE authorid=${req.locals["userid"]} ${WHERE} ORDER BY time DESC LIMIT ${req.body.l},${req.body.n}`; //正式版本中,需要限定作者本身的作品 DB.query(SELECT, function (err, SCRATCH) { if (err) { res.status(200).send({ status: "err", data: [] }); @@ -872,10 +872,10 @@ router.post("/getSession", (req, res) => { }; } else { var new_session = { - userid: parseInt(req.session["userid"]), - username: req.session["username"], - nickname: req.session["nickname"], - avatar: `${process.env.qiniuurl}/user/${req.session.userid}.png`, + userid: parseInt(req.locals["userid"]), + username: req.locals["username"], + nickname: req.locals["nickname"], + avatar: `${process.env.qiniuurl}/user/${res.locals.userid}.png`, }; } diff --git a/server/router_user.js b/server/router_user.js index c25b287..72d76c8 100644 --- a/server/router_user.js +++ b/server/router_user.js @@ -65,7 +65,7 @@ router.get("/repw", function (req, res) { router.post("/login", function (req, res) { request.post( { - url:`${process.env.reverify}?secret=${process.env.resecret}&response=${req.body.re}`, + url: `${process.env.reverify}?secret=${process.env.resecret}&response=${req.body.re}`, }, function (err, httpResponse, body) { if (err) { @@ -104,9 +104,9 @@ router.post("/login", function (req, res) { } else if (User["state"] == 2) { res.status(200).send({ status: "您已经被封号,请联系管理员" }); } else { - req.session["userid"] = User["id"]; - req.session["username"] = User["username"]; - req.session["nickname"] = User["nickname"]; + res.locals["userid"] = User["id"]; + res.locals["username"] = User["username"]; + res.locals["nickname"] = User["nickname"]; //console.log('已登录:**********************************'); //判断系统管理员权限 @@ -116,14 +116,14 @@ router.post("/login", function (req, res) { // req.session['is_admin'] = 0; // } //判断系统管理员权限:此处写死,无需从数据库获取 - req.session["is_admin"] = 0; - if (req.session["username"].indexOf(process.env.adminuser) == 0) { - if (req.session["username"] == process.env.adminuser) { - req.session["is_admin"] = 1; + res.locals["is_admin"] = 0; + if (res.locals["username"].indexOf(process.env.adminuser) == 0) { + if (res.locals["username"] == process.env.adminuser) { + res.locals["is_admin"] = 1; } else { - let no = parseInt(req.session["username"].substring(8)); + let no = parseInt(res.locals["username"].substring(8)); if (0 <= no && no < 100) { - req.session["is_admin"] = 1; + res.locals["is_admin"] = 1; } } } @@ -138,7 +138,11 @@ router.post("/login", function (req, res) { maxAge: 604800000, signed: true, }); - + res.cookie( + "token", + I.GenerateJwt(User["id"], User["username"], User["nickname"]), + { maxAge: 604800000 } + ); res.status(200).send({ status: "OK", userid: parseInt(User["id"]), @@ -154,7 +158,7 @@ router.post("/login", function (req, res) { //退出 var logout = function (req, res) { - req.session.destroy(); + //req.session.destroy(); res.locals["userid"] = null; res.locals["username"] = null; @@ -162,6 +166,7 @@ var logout = function (req, res) { res.cookie("userid", "", { maxAge: 0, signed: true }); res.cookie("username", "", { maxAge: 0, signed: true }); res.cookie("nickname", "", { maxAge: 0, signed: true }); + res.cookie("token", "", { maxAge: 0, signed: true }); }; router.get("/logout", function (req, res) { logout(req, res); @@ -172,7 +177,7 @@ router.get("/logout", function (req, res) { router.post("/register", function (req, res) { request.post( { - url:`${process.env.reverify}?secret=${process.env.resecret}&response=${req.body.re}`, + url: `${process.env.reverify}?secret=${process.env.resecret}&response=${req.body.re}`, }, function (err, httpResponse, body) { if (err) { @@ -212,8 +217,7 @@ router.post("/register", function (req, res) { //对密码进行加密 //var pw = req.body.pw; - var randonpw = I.randomString(10); - var randonpw = randonpw + "@O"; + var randonpw = I.randomPassword(12); //console.log(randonpw); //console.log(username); @@ -230,33 +234,12 @@ router.post("/register", function (req, res) { return; } var userid = newUser.insertId; - req.session["userid"] = userid; - req.session["username"] = username; - req.session["nickname"] = nickname; - - req.session["jwt"] = jwt.sign( - { userid: userid, nickname: nickname, username: username }, - "test" - ); - //7天时长的毫秒数:604800000=7*24*60*60*1000 - //res.cookie("userid", newUser.insertId, { maxAge: 604800000, signed: true,}); - //res.cookie("username", username, { maxAge: 604800000, signed: true }); - //res.cookie("nickname", nickname, { maxAge: 604800000, signed: true }); - res.cookie( - "jwt", - jwt.sign( - { userid: userid, nickname: nickname, username: username }, - "test" - ), - { - maxAge: 604800000, - } - ); - oldpath = "./build/img/user_default_icon.png"; - newpath = "./data/user/" + newUser.insertId + ".png"; - let oldFile = fs["createReadStream"](oldpath); - let newFile = fs["createWriteStream"](newpath); - oldFile["pipe"](newFile); + // res.locals["userid"] = userid; res.locals["username"] = username; res.locals["nickname"] = nickname; res.locals["jwt"] = jwt.sign( { userid: userid, nickname: nickname, username: username }, "test" ); //7天时长的毫秒数:604800000=7*24*60*60*1000 //res.cookie("userid", newUser.insertId, { maxAge: 604800000, signed: true,}); //res.cookie("username", username, { maxAge: 604800000, signed: true }); //res.cookie("nickname", nickname, { maxAge: 604800000, signed: true }); res.cookie( "jwt", jwt.sign( { userid: userid, nickname: nickname, username: username }, "test" ), { maxAge: 604800000, } ); + //oldpath = "./build/img/user_default_icon.png"; + //newpath = "./data/user/" + newUser.insertId + ".png"; + //let oldFile = fs["createReadStream"](oldpath); + //let newFile = fs["createWriteStream"](newpath); + //oldFile["pipe"](newFile); var nodemailer = require("nodemailer"); @@ -324,7 +307,7 @@ router.post("/register", function (req, res) { - ` , + `, }, (err, data) => { if (err) { @@ -352,7 +335,7 @@ router.post("/register", function (req, res) { router.post("/repw", function (req, res) { request.post( { - url:`${process.env.reverify}?secret=${process.env.resecret}&response=${req.body.re}`, + url: `${process.env.reverify}?secret=${process.env.resecret}&response=${req.body.re}`, }, function (err, httpResponse, body) { if (err) { @@ -461,7 +444,6 @@ router.post("/repw", function (req, res) { } ); }); - } ); }); @@ -470,7 +452,7 @@ router.post("/repw", function (req, res) { router.post("/torepw", function (req, res) { request.post( { - url:`${process.env.reverify}?secret=${process.env.resecret}&response=${req.body.re}`, + url: `${process.env.reverify}?secret=${process.env.resecret}&response=${req.body.re}`, }, function (err, httpResponse, body) { if (err) { @@ -523,7 +505,7 @@ router.get("/walineget", function (req, res) { res.redirect( process.env.WalineServerURL + "/ui/profile?token=" + - I.jwt(req.session["username"]) + I.jwt(res.locals["username"]) ); }); @@ -537,10 +519,10 @@ router.get("/tuxiaochao", function (req, res) { if (!process.env.txckey) { res.redirect("https://support.qq.com/product/" + process.env.txcid); } - uid = req.session["userid"].toString(); + uid = res.locals["userid"].toString(); var txcinfo = uid + - req.session["nickname"] + + res.locals["nickname"] + process.env.qiniuurl + "/user/" + uid + @@ -551,17 +533,16 @@ router.get("/tuxiaochao", function (req, res) { "https://support.qq.com/product/" + process.env.txcid + "?openid=" + - req.session["userid"] + + res.locals["userid"] + "&nickname=" + - req.session["nickname"] + + res.locals["nickname"] + "&avatar=" + process.env.qiniuurl + "/user/" + - req.session["userid"] + + res.locals["userid"] + ".png&user_signature=" + cryptostr ); - }); module.exports = router;