添加token过期检查
This commit is contained in:
1 parent
84025a83ab
commit
ba43ad2bbc
3 files changed
+86
-47
No files matched your search
@@ -11,7 +11,7 @@ import http from "http";
|
|||||||
import { v4 as uuid4 } from "uuid";
|
import { v4 as uuid4 } from "uuid";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import sha256 from "crypto-js/sha256.js";
|
import sha256 from "crypto-js/sha256.js";
|
||||||
import Config from './miaoShareConfig.json' assert { type: 'json' };
|
import Config from "./miaoShareConfig.json" assert { type: "json" };
|
||||||
import { verify } from "crypto";
|
import { verify } from "crypto";
|
||||||
// function loadJSON(path){
|
// function loadJSON(path){
|
||||||
// return JSON.parse(fs.readFileSync(path).toString());
|
// return JSON.parse(fs.readFileSync(path).toString());
|
||||||
@@ -19,7 +19,7 @@ import { verify } from "crypto";
|
|||||||
// const Config = loadJSON("./miaoShareConfig.json");
|
// const Config = loadJSON("./miaoShareConfig.json");
|
||||||
|
|
||||||
const HOST = "0.0.0.0";
|
const HOST = "0.0.0.0";
|
||||||
const PORT = Config.PORT
|
const PORT = Config.PORT;
|
||||||
// const PORT = 17057;
|
// const PORT = 17057;
|
||||||
const fileDir = "./temp";
|
const fileDir = "./temp";
|
||||||
const dbPath = "./miaoShare.db";
|
const dbPath = "./miaoShare.db";
|
||||||
@@ -66,7 +66,9 @@ const stmt_getFileSize = db.prepare(`SELECT fileSize FROM id2fileName WHERE id =
|
|||||||
const stmt_getFreeze = db.prepare(`SELECT freeze FROM id2fileName WHERE id = ?`);
|
const stmt_getFreeze = db.prepare(`SELECT freeze FROM id2fileName WHERE id = ?`);
|
||||||
const stmt_getDownloadCredit = db.prepare(`SELECT downloadCredit FROM id2fileName WHERE id = ?`);
|
const stmt_getDownloadCredit = db.prepare(`SELECT downloadCredit FROM id2fileName WHERE id = ?`);
|
||||||
const stmt_getFreezenIDs = db.prepare(`SELECT id,fileSize,sender_id FROM id2fileName WHERE freeze = 1`);
|
const stmt_getFreezenIDs = db.prepare(`SELECT id,fileSize,sender_id FROM id2fileName WHERE freeze = 1`);
|
||||||
const stmt_insertId2FileName = db.prepare(`INSERT INTO id2fileName (id, fileName, timestamp, freeze, downloadCredit, fileSize, sender_id) VALUES (?, ?, ?, ?, ?, ?, ?)`);
|
const stmt_insertId2FileName = db.prepare(
|
||||||
|
`INSERT INTO id2fileName (id, fileName, timestamp, freeze, downloadCredit, fileSize, sender_id) VALUES (?, ?, ?, ?, ?, ?, ?)`
|
||||||
|
);
|
||||||
const stmt_deleteExpireData = db.prepare(`DELETE FROM id2fileName WHERE freeze=1`);
|
const stmt_deleteExpireData = db.prepare(`DELETE FROM id2fileName WHERE freeze=1`);
|
||||||
const stmt_freezeExpireData = db.prepare(`UPDATE id2fileName SET freeze=1 WHERE timestamp < ? OR downloadCredit < 1`);
|
const stmt_freezeExpireData = db.prepare(`UPDATE id2fileName SET freeze=1 WHERE timestamp < ? OR downloadCredit < 1`);
|
||||||
const stmt_updateDownloadCredit = db.prepare(`UPDATE id2fileName SET downloadCredit=downloadCredit-1 WHERE id = ?`);
|
const stmt_updateDownloadCredit = db.prepare(`UPDATE id2fileName SET downloadCredit=downloadCredit-1 WHERE id = ?`);
|
||||||
@@ -93,21 +95,21 @@ const db_getFileName = id => {
|
|||||||
// }
|
// }
|
||||||
// };
|
// };
|
||||||
const db_getFileInfo = (function () {
|
const db_getFileInfo = (function () {
|
||||||
const infoCache = {}
|
const infoCache = {};
|
||||||
return function (id) {
|
return function (id) {
|
||||||
if (infoCache[id]) {
|
if (infoCache[id]) {
|
||||||
return infoCache[id]
|
return infoCache[id];
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
if (stmt_getFreeze.get(id)["freeze"] == 1) return null;
|
if (stmt_getFreeze.get(id)["freeze"] == 1) return null;
|
||||||
const info = stmt_getFileInfo.get(id);
|
const info = stmt_getFileInfo.get(id);
|
||||||
infoCache[id]=info
|
infoCache[id] = info;
|
||||||
return info;
|
return info;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
})()
|
})();
|
||||||
// 检查是否可下载
|
// 检查是否可下载
|
||||||
const db_downloadable = id => {
|
const db_downloadable = id => {
|
||||||
try {
|
try {
|
||||||
@@ -140,12 +142,12 @@ const db_getUserUploadFilesSizeCount = id => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function db_updateUserUploadFilesSizeCount(id, size) {
|
function db_updateUserUploadFilesSizeCount(id, size) {
|
||||||
return stmt_updateUserUploadFilesSizeCount.run(size,id)
|
return stmt_updateUserUploadFilesSizeCount.run(size, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 减
|
// 减
|
||||||
function db_updateUserUploadFilesSizeCount_d(id, size) {
|
function db_updateUserUploadFilesSizeCount_d(id, size) {
|
||||||
return stmt_updateUserUploadFilesSizeCount_d.run(size,id)
|
return stmt_updateUserUploadFilesSizeCount_d.run(size, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新存储的文件,删除已经被冻结的文件以及相关记录,然后冻结过期文件
|
// 更新存储的文件,删除已经被冻结的文件以及相关记录,然后冻结过期文件
|
||||||
@@ -155,9 +157,9 @@ const updateDBAndFiles = () => {
|
|||||||
stmt_deleteExpireData.run();
|
stmt_deleteExpireData.run();
|
||||||
for (let row of rows) {
|
for (let row of rows) {
|
||||||
let fileName = row["id"];
|
let fileName = row["id"];
|
||||||
let sid = row['sender_id']
|
let sid = row["sender_id"];
|
||||||
let fsize = row['fileSize']
|
let fsize = row["fileSize"];
|
||||||
db_updateUserUploadFilesSizeCount_d(sid,fsize)
|
db_updateUserUploadFilesSizeCount_d(sid, fsize);
|
||||||
let path = fileDir + "/" + fileName;
|
let path = fileDir + "/" + fileName;
|
||||||
try {
|
try {
|
||||||
fs.unlink(path, e => {
|
fs.unlink(path, e => {
|
||||||
@@ -220,7 +222,7 @@ function uploadFile(req, res, fileName, downloadCredit, fileSize) {
|
|||||||
let id = generateId();
|
let id = generateId();
|
||||||
const fileStream = fs.createWriteStream(fileDir + "/" + id);
|
const fileStream = fs.createWriteStream(fileDir + "/" + id);
|
||||||
db_insert(id, fileName, downloadCredit, fileSize, req.sender_id);
|
db_insert(id, fileName, downloadCredit, fileSize, req.sender_id);
|
||||||
db_updateUserUploadFilesSizeCount(req.sender_id,fileSize)
|
db_updateUserUploadFilesSizeCount(req.sender_id, fileSize);
|
||||||
// tempMap[id] = fileName;
|
// tempMap[id] = fileName;
|
||||||
// console.log(tempMap);
|
// console.log(tempMap);
|
||||||
req.pipe(fileStream);
|
req.pipe(fileStream);
|
||||||
@@ -290,28 +292,28 @@ function getFileInfo(req, res, fileId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getUserGroup = (function () {
|
const getUserGroup = (function () {
|
||||||
const cache = {}
|
const cache = {};
|
||||||
return function (userId) {
|
return function (userId) {
|
||||||
if (!cache[userId]) {
|
if (!cache[userId]) {
|
||||||
cache[userId]= stmt_getUserGroup.get(userId)['user_group']
|
cache[userId] = stmt_getUserGroup.get(userId)["user_group"];
|
||||||
}
|
}
|
||||||
return cache[userId]
|
return cache[userId];
|
||||||
}
|
};
|
||||||
})()
|
})();
|
||||||
|
|
||||||
// 验证token
|
// 验证token
|
||||||
const verifyToken = (req, res, next) => {
|
const verifyToken = (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization.split(" ")[1]; // 从Authorization头中提取JWT
|
const token = req.headers.authorization.split(" ")[1]; // 从Authorization头中提取JWT
|
||||||
console.log(req.headers.authorization,token)
|
console.log(req.headers.authorization, token);
|
||||||
let verifyData = jwt.verify(token, JWT_SK);
|
let verifyData = jwt.verify(token, JWT_SK);
|
||||||
if (verifyData.exp > parseInt(Date.now())) {
|
if (verifyData.exp > parseInt(Date.now())) {
|
||||||
throw "token has expired";
|
throw "token has expired";
|
||||||
}
|
}
|
||||||
req.sender_id = verifyData.id
|
req.sender_id = verifyData.id;
|
||||||
next();
|
next();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err)
|
console.log(err);
|
||||||
return res.status(401).json({ message: "Invalid token", err });
|
return res.status(401).json({ message: "Invalid token", err });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -323,7 +325,7 @@ app.post("/user/login", express.json(),function (req, res) {
|
|||||||
res.header("Access-Control-Allow-Methods", "POST");
|
res.header("Access-Control-Allow-Methods", "POST");
|
||||||
// console.log(req.body)
|
// console.log(req.body)
|
||||||
let { id, pwd } = req.body;
|
let { id, pwd } = req.body;
|
||||||
console.log(req.body)
|
console.log(req.body);
|
||||||
let pwdH = sha256(id + pwd).toString();
|
let pwdH = sha256(id + pwd).toString();
|
||||||
let userGroup = db_getPermissionGroup(id, pwdH);
|
let userGroup = db_getPermissionGroup(id, pwdH);
|
||||||
if (userGroup !== null) {
|
if (userGroup !== null) {
|
||||||
@@ -336,33 +338,27 @@ app.post("/user/login", express.json(),function (req, res) {
|
|||||||
// console.log(req)
|
// console.log(req)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
app.post("/user/refrashToken", express.json(), function (req, res) {
|
app.post("/user/refrashToken", express.json(), function (req, res) {
|
||||||
res.header("Access-Control-Allow-Origin", "*");
|
res.header("Access-Control-Allow-Origin", "*");
|
||||||
res.header("Access-Control-Allow-Headers", "*");
|
res.header("Access-Control-Allow-Headers", "*");
|
||||||
res.header("Access-Control-Allow-Methods", "POST");
|
res.header("Access-Control-Allow-Methods", "POST");
|
||||||
// console.log(req.body)
|
// console.log(req.body)
|
||||||
let { token } = req.body;
|
try {
|
||||||
console.log(req.body)
|
const token = req.headers.authorization.split(" ")[1]; // 从Authorization头中提取JWT
|
||||||
|
// const token = req.body.token
|
||||||
|
console.log(token)
|
||||||
let verifyData = jwt.verify(token, JWT_SK);
|
let verifyData = jwt.verify(token, JWT_SK);
|
||||||
if (verifyData.exp > parseInt(Date.now())) {
|
if (verifyData.exp > parseInt(Date.now())) {
|
||||||
return res.status(401).json({ message: "Invalid token" });
|
return res.status(401).json({ status: "Error", message: "Invalid token" });
|
||||||
}
|
}
|
||||||
let id = verifyData.id
|
let id = verifyData.id;
|
||||||
let pwd = verifyData.pwd
|
let pwd = verifyData.pwd;
|
||||||
let new_token = jwt.sign({ id, pwd }, JWT_SK, { expiresIn: `${Config.tokenExpiresIn}h` });
|
let new_token = jwt.sign({ id, pwd }, JWT_SK, { expiresIn: `${Config.tokenExpiresIn}h` });
|
||||||
res.end(JSON.stringify({ status: "Success", token }));
|
console.log({ token, new_token });
|
||||||
// let pwdH = sha256(id + pwd).toString();
|
res.end(JSON.stringify({ status: "Success", new_token }));
|
||||||
// let userGroup = db_getPermissionGroup(id, pwdH);
|
} catch (e) {
|
||||||
// if (userGroup !== null) {
|
return res.status(401).json({ status: "Error", message: "Invalid token" });
|
||||||
// res.writeHead(200);
|
}
|
||||||
// let token = jwt.sign({ id, pwd }, JWT_SK, { expiresIn: `${Config.tokenExpiresIn}h` });
|
|
||||||
// res.end(JSON.stringify({ status: "Success", userGroup, token }));
|
|
||||||
// } else {
|
|
||||||
// res.end(JSON.stringify({ status: "Error" }));
|
|
||||||
// }
|
|
||||||
// console.log(req)
|
|
||||||
});
|
});
|
||||||
// app.all()
|
// app.all()
|
||||||
app.post("/file/upload", verifyToken, function (req, res) {
|
app.post("/file/upload", verifyToken, function (req, res) {
|
||||||
@@ -377,7 +373,10 @@ app.post("/file/upload", verifyToken, function (req, res) {
|
|||||||
if (!fileName) {
|
if (!fileName) {
|
||||||
res.statusCode = 500;
|
res.statusCode = 500;
|
||||||
res.end("FileName Not Found");
|
res.end("FileName Not Found");
|
||||||
} else if (fileSize > uploadMaxSize || db_getUserUploadFilesSizeCount(req.sender_id) + fileSize > Config.userGroupSetting[getUserGroup(req.sender_id)].cloudCapacity) {
|
} else if (
|
||||||
|
fileSize > uploadMaxSize ||
|
||||||
|
db_getUserUploadFilesSizeCount(req.sender_id) + fileSize > Config.userGroupSetting[getUserGroup(req.sender_id)].cloudCapacity
|
||||||
|
) {
|
||||||
res.statusCode = 500;
|
res.statusCode = 500;
|
||||||
res.end("Maximum size limit exceeded");
|
res.end("Maximum size limit exceeded");
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+38
-3
@@ -19,11 +19,18 @@ import {
|
|||||||
|
|
||||||
} from '@vicons/ionicons5'
|
} from '@vicons/ionicons5'
|
||||||
import { useSettingStore } from "@/pinia/store";
|
import { useSettingStore } from "@/pinia/store";
|
||||||
|
import config from "../miaoShareConfig.json"
|
||||||
|
|
||||||
// console.log(process.env.NODE_ENV)
|
// console.log(process.env.NODE_ENV)
|
||||||
|
|
||||||
|
|
||||||
const settingData = useSettingStore();
|
const settingData = useSettingStore();
|
||||||
|
const serverPort = settingData.serverPort;
|
||||||
|
const baseUrl =
|
||||||
|
location.protocol + "//" + location.hostname + ":" + serverPort + "/";
|
||||||
|
const tokenExpiresIn = config.tokenExpiresIn
|
||||||
|
|
||||||
|
|
||||||
const activePage = ref('upload')
|
const activePage = ref('upload')
|
||||||
const isComponent = shallowRef(upload)
|
const isComponent = shallowRef(upload)
|
||||||
watch(activePage, () => {
|
watch(activePage, () => {
|
||||||
@@ -86,13 +93,15 @@ const menuOptions = ref([
|
|||||||
// }
|
// }
|
||||||
|
|
||||||
|
|
||||||
onMounted(()=>{
|
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
let aP = getQueryString('aP')
|
let aP = getQueryString('aP')
|
||||||
// console.log(aP)
|
// console.log(aP)
|
||||||
if (aP) {
|
if (aP) {
|
||||||
activePage.value = aP
|
activePage.value = aP
|
||||||
}
|
}
|
||||||
if(settingData.token === null){
|
if (settingData.getToken() === null) {
|
||||||
aP = activePage.value
|
aP = activePage.value
|
||||||
activePage.value = 'login'
|
activePage.value = 'login'
|
||||||
// 登录后跳原来的activePage
|
// 登录后跳原来的activePage
|
||||||
@@ -102,6 +111,30 @@ onMounted(()=>{
|
|||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
// 刷新token
|
// 刷新token
|
||||||
|
(async function refreshToken() {
|
||||||
|
const old_token = settingData.getToken()
|
||||||
|
console.log(old_token)
|
||||||
|
const response = await fetch(`${baseUrl}user/refrashToken`, {
|
||||||
|
// credentials: 'include',
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${settingData.token}`,
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
// body: JSON.stringify({
|
||||||
|
// token:settingData.token
|
||||||
|
// })
|
||||||
|
});
|
||||||
|
console.log(response)
|
||||||
|
let data = await response.json()
|
||||||
|
if (data.status === 'Error') {
|
||||||
|
console.log('falied')
|
||||||
|
} else {
|
||||||
|
// console.log(data)
|
||||||
|
localStorage.setItem('token', data.new_token)
|
||||||
|
localStorage.setItem('tokenExpiredTime', parseInt(Date.now()) + parseInt(tokenExpiresIn) * 3600000)
|
||||||
|
}
|
||||||
|
})()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
@@ -113,7 +146,8 @@ onMounted(()=>{
|
|||||||
<n-modal-provider>
|
<n-modal-provider>
|
||||||
<n-card content-style="padding: 0; margin:0" id="theCard">
|
<n-card content-style="padding: 0; margin:0" id="theCard">
|
||||||
<div id="menu">
|
<div id="menu">
|
||||||
<n-menu mode="horizontal" :responsive="true" v-model:value="activePage" :options="menuOptions" :icon-size="26"></n-menu>
|
<n-menu mode="horizontal" :responsive="true" v-model:value="activePage"
|
||||||
|
:options="menuOptions" :icon-size="26"></n-menu>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style="padding: 20px;">
|
<div style="padding: 20px;">
|
||||||
@@ -152,6 +186,7 @@ onMounted(()=>{
|
|||||||
border-bottom: 1px solid rgb(60, 60, 60, 0.1);
|
border-bottom: 1px solid rgb(60, 60, 60, 0.1);
|
||||||
user-select: none
|
user-select: none
|
||||||
}
|
}
|
||||||
|
|
||||||
@media screen and (max-width:768px) {
|
@media screen and (max-width:768px) {
|
||||||
#theCard {
|
#theCard {
|
||||||
width: 100vw;
|
width: 100vw;
|
||||||
|
|||||||
+7
-2
@@ -5,7 +5,7 @@ const userID = localStorage.getItem('userID');
|
|||||||
const userGroup = localStorage.getItem('userGroup');
|
const userGroup = localStorage.getItem('userGroup');
|
||||||
|
|
||||||
const tokenExpiresIn = config.tokenExpiresIn
|
const tokenExpiresIn = config.tokenExpiresIn
|
||||||
if(!localStorage.getItem('tokenExpiredTime') ||
|
if(localStorage.getItem('tokenExpiredTime') == null ||
|
||||||
parseInt(localStorage.getItem('tokenExpiredTime')) < parseInt(Date.now())){
|
parseInt(localStorage.getItem('tokenExpiredTime')) < parseInt(Date.now())){
|
||||||
localStorage.removeItem('token')
|
localStorage.removeItem('token')
|
||||||
}
|
}
|
||||||
@@ -47,8 +47,10 @@ export const useSettingStore = defineStore("setting", {
|
|||||||
actions: {
|
actions: {
|
||||||
setJWT( token,keepTokenLocal ){
|
setJWT( token,keepTokenLocal ){
|
||||||
this.token = token
|
this.token = token
|
||||||
if(keepTokenLocal)
|
if(keepTokenLocal){
|
||||||
localStorage.setItem('token',token)
|
localStorage.setItem('token',token)
|
||||||
|
localStorage.setItem('tokenExpiredTime',parseInt(Date.now())+parseInt(tokenExpiresIn)*3600000)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
setUserID( id,keepTokenLocal ){
|
setUserID( id,keepTokenLocal ){
|
||||||
this.userID = id
|
this.userID = id
|
||||||
@@ -59,6 +61,9 @@ export const useSettingStore = defineStore("setting", {
|
|||||||
this.userGroup = g
|
this.userGroup = g
|
||||||
if(keepTokenLocal)
|
if(keepTokenLocal)
|
||||||
localStorage.setItem('userGroup',g)
|
localStorage.setItem('userGroup',g)
|
||||||
|
},
|
||||||
|
getToken(){
|
||||||
|
return localStorage.getItem('token')
|
||||||
}
|
}
|
||||||
// increment() {
|
// increment() {
|
||||||
// this.count++;
|
// this.count++;
|
||||||
|
|||||||
Reference in new issue
Block a user