Compare commits

...
3 Commits
Author SHA1 Message Date
539943419 8d08392cad 修复了chat中图片显示的相关问题 2024-07-07 12:40:25 +08:00
539943419 ba43ad2bbc 添加token过期检查 2024-07-02 20:13:07 +08:00
539943419 84025a83ab 优化vite配置 2024-07-02 19:27:26 +08:00
7 changed files with 178 additions and 72 deletions

No files matched your search

+2 -1
View File
@@ -8,5 +8,6 @@
"cloudCapacity":2147483648 "cloudCapacity":2147483648
} }
}, },
"enableGuest":false "enableGuest":false,
"tokenExpiresIn":168
} }
+71 -42
View File
@@ -11,14 +11,15 @@ 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";
// function loadJSON(path){ // function loadJSON(path){
// return JSON.parse(fs.readFileSync(path).toString()); // return JSON.parse(fs.readFileSync(path).toString());
// } // }
// 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";
@@ -65,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 = ?`);
@@ -91,22 +94,22 @@ const db_getFileName = id => {
// return null; // return null;
// } // }
// }; // };
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 {
@@ -138,13 +141,13 @@ const db_getUserUploadFilesSizeCount = id => {
return stmt_getUserUploadFilesSizeCount.get(id)["uploadFilesSizeCount"]; return stmt_getUserUploadFilesSizeCount.get(id)["uploadFilesSizeCount"];
}; };
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);
} }
// 更新存储的文件,删除已经被冻结的文件以及相关记录,然后冻结过期文件 // 更新存储的文件,删除已经被冻结的文件以及相关记录,然后冻结过期文件
@@ -154,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 => {
@@ -219,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);
@@ -288,52 +291,75 @@ 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 });
} }
}; };
app.use(express.static(PATH)); app.use(express.static(PATH));
app.post("/user/login", express.json(),function (req, res) { app.post("/user/login", 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 { 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) {
res.writeHead(200); res.writeHead(200);
let token = jwt.sign({ id, pwd }, JWT_SK, { expiresIn: "168h" }); let token = jwt.sign({ id, pwd }, JWT_SK, { expiresIn: `${Config.tokenExpiresIn}h` });
res.end(JSON.stringify({ status: "Success", userGroup, token })); res.end(JSON.stringify({ status: "Success", userGroup, token }));
} else { } else {
res.end(JSON.stringify({ status: "Error" })); res.end(JSON.stringify({ status: "Error" }));
} }
// console.log(req) // console.log(req)
}); });
app.post("/user/refrashToken", express.json(), function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
res.header("Access-Control-Allow-Methods", "POST");
// console.log(req.body)
try {
const token = req.headers.authorization.split(" ")[1]; // 从Authorization头中提取JWT
// const token = req.body.token
console.log(token)
let verifyData = jwt.verify(token, JWT_SK);
if (verifyData.exp > parseInt(Date.now())) {
return res.status(401).json({ status: "Error", message: "Invalid token" });
}
let id = verifyData.id;
let pwd = verifyData.pwd;
let new_token = jwt.sign({ id, pwd }, JWT_SK, { expiresIn: `${Config.tokenExpiresIn}h` });
console.log({ token, new_token });
res.end(JSON.stringify({ status: "Success", new_token }));
} catch (e) {
return res.status(401).json({ status: "Error", message: "Invalid token" });
}
});
// app.all() // app.all()
app.post("/file/upload", verifyToken, function (req, res) { app.post("/file/upload", verifyToken, function (req, res) {
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
@@ -347,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 {
@@ -451,11 +480,11 @@ function createGroupTableDB(gID, verify) {
} }
// 插入信息 // 插入信息
function insertMessageByGID(gID, msg,type1, from, timestamp) { function insertMessageByGID(gID, msg, type1, from, timestamp) {
if (!generateStmt_insertMessage_map[gID]) { if (!generateStmt_insertMessage_map[gID]) {
generateStmt_insertMessage_map[gID] = db.prepare(`INSERT INTO ${gID} (message,type,type1,sender, timestamp) VALUES (?, ?, ?, ?, ?)`); generateStmt_insertMessage_map[gID] = db.prepare(`INSERT INTO ${gID} (message,type,type1,sender, timestamp) VALUES (?, ?, ?, ?, ?)`);
} }
generateStmt_insertMessage_map[gID].run(msg, "gMsg",type1, from, timestamp); generateStmt_insertMessage_map[gID].run(msg, "gMsg", type1, from, timestamp);
} }
function updateActiveTimestamp(gID) { function updateActiveTimestamp(gID) {
@@ -489,14 +518,14 @@ function getHistory(gID) {
return groupsMap[gID].msgHistory; return groupsMap[gID].msgHistory;
} }
function broadcastMsg(gID, msg,type1, from) { function broadcastMsg(gID, msg, type1, from) {
const timestamp = parseInt(Date.now()); const timestamp = parseInt(Date.now());
initMsgHistory(gID); initMsgHistory(gID);
updateActiveTimestamp(gID); updateActiveTimestamp(gID);
insertMessageByGID(gID, msg,type1, from, timestamp); insertMessageByGID(gID, msg, type1, from, timestamp);
let bmsg = JSON.stringify({ type: `gMsg`,type1, gID, msg, from, timestamp }); let bmsg = JSON.stringify({ type: `gMsg`, type1, gID, msg, from, timestamp });
groupsMap[gID].msgHistory.push({ type: `gMsg`,type1, msg, from, timestamp }); groupsMap[gID].msgHistory.push({ type: `gMsg`, type1, msg, from, timestamp });
for (let socket of groupsMap[gID].member) { for (let socket of groupsMap[gID].member) {
socket.send(bmsg); socket.send(bmsg);
} }
@@ -510,7 +539,7 @@ function initMsgHistory(gID) {
.prepare(`SELECT message,type,type1,sender,timestamp FROM ${gID}`) .prepare(`SELECT message,type,type1,sender,timestamp FROM ${gID}`)
.all() .all()
.map(v => { .map(v => {
return { type: v.type,type1:v.type1, msg: v.message, from: v.sender, timestamp: v.timestamp }; return { type: v.type, type1: v.type1, msg: v.message, from: v.sender, timestamp: v.timestamp };
}); });
// console.log(msgHistory) // console.log(msgHistory)
groupsMap[gID] = { verify, member: [], msgHistory }; groupsMap[gID] = { verify, member: [], msgHistory };
@@ -556,7 +585,7 @@ wss.on("connection", socket => {
} }
} else if (type === "message") { } else if (type === "message") {
let gID = msg.gID; let gID = msg.gID;
broadcastMsg(gID, msg.msg,msg.type1, uuid); broadcastMsg(gID, msg.msg, msg.type1, uuid);
} else if (type === "heartbeat") { } else if (type === "heartbeat") {
socket.send(JSON.stringify({ type: "sMsg", type1: "heartbeat" })); socket.send(JSON.stringify({ type: "sMsg", type1: "heartbeat" }));
} else if (type === "uuid") { } else if (type === "uuid") {
+62 -26
View File
@@ -6,8 +6,8 @@ import chat from "./views/chat.vue";
import login from "./views/login.vue"; import login from "./views/login.vue";
import account from "./views/accountInfo.vue"; import account from "./views/accountInfo.vue";
import getQueryString from '@/func/getQuery' import getQueryString from '@/func/getQuery'
import { NNotificationProvider, NMessageProvider, NCard, NMenu, NIcon,NModalProvider } from 'naive-ui' import { NNotificationProvider, NMessageProvider, NCard, NMenu, NIcon, NModalProvider } from 'naive-ui'
import { ref, watch, h ,shallowRef, onMounted, computed} from "vue"; import { ref, watch, h, shallowRef, onMounted, computed } from "vue";
// import { useRoute } from "vue-router"; // import { useRoute } from "vue-router";
import { import {
CloudUploadOutline as uploadIcon, CloudUploadOutline as uploadIcon,
@@ -19,15 +19,22 @@ 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, () => {
isComponent.value={upload,download,setting,chat,login,account}[activePage.value] isComponent.value = { upload, download, setting, chat, login, account }[activePage.value]
}) })
function renderIcon(icon) { function renderIcon(icon) {
return () => h(NIcon, null, { default: () => h(icon) }) return () => h(NIcon, null, { default: () => h(icon) })
@@ -38,7 +45,7 @@ const menuOptions = ref([
label: '上传', label: '上传',
key: 'upload', key: 'upload',
icon: renderIcon(uploadIcon), icon: renderIcon(uploadIcon),
disabled:computed(()=>{ disabled: computed(() => {
// console.log(settingData) // console.log(settingData)
return settingData.token === null return settingData.token === null
}) })
@@ -47,7 +54,7 @@ const menuOptions = ref([
label: '下载', label: '下载',
key: 'download', key: 'download',
icon: renderIcon(downloadIcon), icon: renderIcon(downloadIcon),
disabled:computed(()=>{ disabled: computed(() => {
return settingData.token === null return settingData.token === null
}) })
}, },
@@ -55,7 +62,7 @@ const menuOptions = ref([
label: 'Chat', label: 'Chat',
key: 'chat', key: 'chat',
icon: renderIcon(chatIcon), icon: renderIcon(chatIcon),
disabled:computed(()=>{ disabled: computed(() => {
return settingData.token === null return settingData.token === null
}) })
}, },
@@ -63,15 +70,15 @@ const menuOptions = ref([
label: '设置', label: '设置',
key: 'setting', key: 'setting',
icon: renderIcon(settingIcon), icon: renderIcon(settingIcon),
disabled:computed(()=>{ disabled: computed(() => {
return settingData.token === null return settingData.token === null
}) })
}, },
{ {
label:'账户', label: '账户',
key:'account', key: 'account',
icon: renderIcon(AccountIcon), icon: renderIcon(AccountIcon),
disabled:computed(()=>{ disabled: computed(() => {
return settingData.token === null return settingData.token === null
}) })
} }
@@ -86,20 +93,47 @@ 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
const w = watch(()=>settingData.token,()=>{ const w = watch(() => settingData.token, () => {
activePage.value = aP activePage.value = aP
w() w()
}) })
} else {
// 刷新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 {
localStorage.setItem('token', data.new_token)
localStorage.setItem('tokenExpiredTime', parseInt(Date.now()) + parseInt(tokenExpiresIn) * 3600000)
}
})()
} }
}) })
</script> </script>
@@ -109,16 +143,17 @@ onMounted(()=>{
<n-notification-provider placement="bottom-right" :max="3"> <n-notification-provider placement="bottom-right" :max="3">
<n-message-provider> <n-message-provider>
<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"
</div> :options="menuOptions" :icon-size="26"></n-menu>
</div>
<div style="padding: 20px;"> <div style="padding: 20px;">
<KeepAlive> <KeepAlive>
<component :is="isComponent"></component> <component :is="isComponent"></component>
</KeepAlive> </KeepAlive>
</div> </div>
</n-card> </n-card>
</n-modal-provider> </n-modal-provider>
</n-message-provider> </n-message-provider>
@@ -142,14 +177,15 @@ onMounted(()=>{
height: 90vh; height: 90vh;
} }
#menu{ #menu {
width: 100%; width: 100%;
height: auto; height: auto;
/* background-color: blue; */ /* background-color: blue; */
padding-top: 5px; padding-top: 5px;
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;
+1 -2
View File
@@ -240,9 +240,8 @@ watch(() => props.messages, async () => {
if (!imgDownloadingQueue.includes(msg.msg)) { if (!imgDownloadingQueue.includes(msg.msg)) {
imgDownloadingQueue.push(msg.msg) imgDownloadingQueue.push(msg.msg)
const imgData = await downloadImage(msg.msg) const imgData = await downloadImage(msg.msg)
const url = URL.createObjectURL(new Blob([imgData])) const url = URL.createObjectURL(new Blob([imgData], { type: "image/png" }))
imgUrlCache.value[msg.msg] = url imgUrlCache.value[msg.msg] = url
// console.log(new Blob(imgData), imgData, url, imgUrlCache.value, imgDownloadingQueue)
} }
} else if (msg.type1 === 'file') { } else if (msg.type1 === 'file') {
if (!getFileInfoQueue.includes(msg.msg)) { if (!getFileInfoQueue.includes(msg.msg)) {
+11
View File
@@ -70,11 +70,22 @@ const decryptString = (key, str) => {
return decryptedStr; return decryptedStr;
}; };
const _saveAs = (blob,fileName)=>{
const blobUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.download = fileName;
a.href = blobUrl;
a.click();
}
const downloadFromUint8Array = (data, fileName) => { const downloadFromUint8Array = (data, fileName) => {
let uint8Array = data; let uint8Array = data;
let blob = new Blob([uint8Array], { type: "application/octet-stream" }); let blob = new Blob([uint8Array], { type: "application/octet-stream" });
// const blobUrl = window.URL.createObjectURL(blob);
// 使用file-saver.js // 使用file-saver.js
saveAs(blob, fileName); saveAs(blob, fileName);
// _saveAs(blob, fileName);
}; };
export { blob2Uint8Array, decrypt, decryptString, downloadFromUint8Array }; export { blob2Uint8Array, decrypt, decryptString, downloadFromUint8Array };
+13 -1
View File
@@ -4,7 +4,14 @@ import config from "../../miaoShareConfig.json"
const userID = localStorage.getItem('userID'); const userID = localStorage.getItem('userID');
const userGroup = localStorage.getItem('userGroup'); const userGroup = localStorage.getItem('userGroup');
const tokenExpiresIn = config.tokenExpiresIn
if(localStorage.getItem('tokenExpiredTime') == null ||
parseInt(localStorage.getItem('tokenExpiredTime')) < parseInt(Date.now())){
localStorage.removeItem('token')
}
const token = localStorage.getItem('token'); const token = localStorage.getItem('token');
// console.log(token) // console.log(token)
var activeFuctionLocal = localStorage.getItem('activeFuction') var activeFuctionLocal = localStorage.getItem('activeFuction')
@@ -40,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
@@ -52,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++;
+18
View File
@@ -21,4 +21,22 @@ export default defineConfig({
esbuild: { esbuild: {
drop: ['console', 'debugger'], drop: ['console', 'debugger'],
}, },
build: {
minify: true,
rollupOptions: {
output: {
// 打包输出的配置
manualChunks: id => {
// 这个ID,就是所有文件的绝对路径
if (id.includes("node_modules")) {
// 因为 node_modules 中的依赖通常是不会改变的
// 所以直接单独打包出去
// 这个return 的值就是打包的名称
// return id.split('node_modules')[1]
return "modules";
}
}
}
}
}
}) })