Skip to content

Commit

Permalink
使用 jwt token
Browse files Browse the repository at this point in the history
  • Loading branch information
SunWuyuan committed Jan 13, 2024
1 parent dd6e246 commit 6d56a48
Show file tree
Hide file tree
Showing 8 changed files with 185 additions and 174 deletions.
120 changes: 72 additions & 48 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
var express = require("express");
var app = express();
var http = require("http");
const jwt = require("jsonwebtoken"); // 首先确保安装了jsonwebtoken库

//环境变量
require("dotenv").config();
Expand All @@ -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 = {
Expand Down Expand Up @@ -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));
Expand All @@ -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));
}
//全局变量
Expand All @@ -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:推荐的优秀作品
Expand Down Expand Up @@ -184,7 +209,6 @@ app.get("/", function (req, res) {

// res.locals["ads"] = encodeURIComponent(JSON.stringify(ADS));


//});
res.render("ejs/index.ejs");
});
Expand Down
24 changes: 17 additions & 7 deletions server/lib/fuck.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand All @@ -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,
Expand All @@ -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);
Expand Down Expand Up @@ -74,15 +71,17 @@ 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;
var pwd = "";
for (var i = 0; i < len; i++) {
pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
}
pwd = pwd + "@Aa1";
return pwd;
};

Expand All @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions server/router_admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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':[]});
Expand All @@ -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':[]});
Expand Down
2 changes: 1 addition & 1 deletion server/router_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
Expand Down
Loading

0 comments on commit 6d56a48

Please sign in to comment.