Browse Source

修复登录token

master
hejl 6 days ago
parent
commit
f73d9b5488
  1. 179
      gofaster/app/diagnose.ps1
  2. 15
      gofaster/app/dist/renderer/js/index.js
  3. 72
      gofaster/app/fix-build.ps1
  4. 8
      gofaster/app/package.json
  5. 64
      gofaster/app/src/main/index.js
  6. 3
      gofaster/app/src/renderer/components/MainLayout.vue
  7. 13
      gofaster/app/src/renderer/modules/user-management/services/userService.js
  8. 95
      gofaster/app/start-fixed.ps1
  9. 2
      gofaster/app/vue.config.js
  10. 2
      gofaster/backend/internal/auth/routes/auth_routes.go
  11. 2
      gofaster/backend/internal/auth/routes/permission_routes.go
  12. 2
      gofaster/backend/internal/auth/routes/resource_routes.go
  13. 5
      gofaster/backend/internal/shared/middleware/jwt_middleware.go

179
gofaster/app/diagnose.ps1

@ -0,0 +1,179 @@ @@ -0,0 +1,179 @@
# 诊断脚本 - 检查项目状态和问题
param(
[switch]$Fix
)
# 设置控制台编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
Write-Host "🔍 GoFaster 项目诊断" -ForegroundColor Cyan
Write-Host "========================" -ForegroundColor Cyan
Write-Host ""
# 1. 检查 Node.js 和 npm
Write-Host "1 检查 Node.js 环境..." -ForegroundColor Yellow
try {
$nodeVersion = node --version 2>$null
$npmVersion = npm --version 2>$null
if ($nodeVersion) {
Write-Host " ✅ Node.js: $nodeVersion" -ForegroundColor Green
} else {
Write-Host " ❌ Node.js 未安装或不在 PATH 中" -ForegroundColor Red
}
if ($npmVersion) {
Write-Host " ✅ npm: $npmVersion" -ForegroundColor Green
} else {
Write-Host " ❌ npm 未安装或不在 PATH 中" -ForegroundColor Red
}
} catch {
Write-Host " ❌ 检查 Node.js 环境失败: $($_.Exception.Message)" -ForegroundColor Red
}
Write-Host ""
# 2. 检查项目结构
Write-Host "2 检查项目结构..." -ForegroundColor Yellow
$requiredFiles = @(
"package.json",
"vue.config.js",
"src/main/index.js",
"src/renderer/main.js",
"public/index.html"
)
foreach ($file in $requiredFiles) {
if (Test-Path $file) {
Write-Host "$file" -ForegroundColor Green
} else {
Write-Host "$file (缺失)" -ForegroundColor Red
}
}
Write-Host ""
# 3. 检查依赖
Write-Host "3 检查依赖..." -ForegroundColor Yellow
if (Test-Path "node_modules") {
Write-Host " ✅ node_modules 存在" -ForegroundColor Green
# 检查关键依赖
$keyDependencies = @("vue", "electron", "@vue/cli-service")
foreach ($dep in $keyDependencies) {
$depPath = "node_modules/$dep"
if (Test-Path $depPath) {
Write-Host "$dep" -ForegroundColor Green
} else {
Write-Host "$dep (缺失)" -ForegroundColor Red
}
}
} else {
Write-Host " ❌ node_modules 不存在" -ForegroundColor Red
}
Write-Host ""
# 4. 检查构建文件
Write-Host "4 检查构建文件..." -ForegroundColor Yellow
$buildFiles = @(
"dist/renderer/index.html",
"dist/renderer/js/index.js",
"dist/renderer/js/vendors.js"
)
$buildFilesExist = $true
foreach ($file in $buildFiles) {
if (Test-Path $file) {
$size = (Get-Item $file).Length
$sizeKB = [math]::Round($size / 1KB, 2)
Write-Host "$file ($sizeKB KB)" -ForegroundColor Green
} else {
Write-Host "$file (缺失)" -ForegroundColor Red
$buildFilesExist = $false
}
}
Write-Host ""
# 5. 检查构建文件内容
if ($buildFilesExist) {
Write-Host "5 检查构建文件内容..." -ForegroundColor Yellow
$indexHtml = Get-Content "dist/renderer/index.html" -Raw
if ($indexHtml -match "vendors\.js") {
Write-Host " ✅ index.html 包含 vendors.js 引用" -ForegroundColor Green
} else {
Write-Host " ❌ index.html 缺少 vendors.js 引用" -ForegroundColor Red
}
if ($indexHtml -match "index\.js") {
Write-Host " ✅ index.html 包含 index.js 引用" -ForegroundColor Green
} else {
Write-Host " ❌ index.html 缺少 index.js 引用" -ForegroundColor Red
}
}
Write-Host ""
# 6. 检查配置文件
Write-Host "6 检查配置文件..." -ForegroundColor Yellow
$vueConfig = Get-Content "vue.config.js" -Raw
if ($vueConfig -match "publicPath.*['\""]\.\/['\""]") {
Write-Host " vue.config.js 中的 publicPath 可能导致资源加载问题" -ForegroundColor Yellow
} else {
Write-Host " ✅ vue.config.js 配置正常" -ForegroundColor Green
}
Write-Host ""
# 7. 总结和建议
Write-Host "📋 诊断总结" -ForegroundColor Cyan
Write-Host "=============" -ForegroundColor Cyan
$issues = @()
if (-not (Test-Path "node_modules")) {
$issues += "依赖未安装"
}
if (-not $buildFilesExist) {
$issues += "构建文件缺失"
}
if ($issues.Count -eq 0) {
Write-Host "✅ 项目状态良好,没有发现明显问题" -ForegroundColor Green
} else {
Write-Host " 发现以下问题:" -ForegroundColor Yellow
foreach ($issue in $issues) {
Write-Host "$issue" -ForegroundColor Red
}
}
Write-Host ""
# 8. 修复建议
Write-Host "🔧 修复建议" -ForegroundColor Cyan
Write-Host "=============" -ForegroundColor Cyan
Write-Host "1. 如果依赖缺失,运行: npm install" -ForegroundColor White
Write-Host "2. 如果构建文件缺失,运行: npm run fix:build" -ForegroundColor White
Write-Host "3. 如果问题持续,运行: npm run fix:rebuild" -ForegroundColor White
Write-Host "4. 使用修复版启动脚本: npm run start:fixed" -ForegroundColor White
if ($Fix) {
Write-Host ""
Write-Host "🔨 自动修复..." -ForegroundColor Yellow
if (-not (Test-Path "node_modules")) {
Write-Host " 安装依赖..." -ForegroundColor Yellow
npm install
}
if (-not $buildFilesExist) {
Write-Host " 重新构建..." -ForegroundColor Yellow
npm run fix:build
}
Write-Host "✅ 修复完成!" -ForegroundColor Green
}

15
gofaster/app/dist/renderer/js/index.js vendored

@ -13765,6 +13765,9 @@ api.interceptors.request.use( @@ -13765,6 +13765,9 @@ api.interceptors.request.use(
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
console.log('🔍 发送请求,Authorization:', `Bearer ${token.substring(0, 20)}...`)
} else {
console.log('🔍 发送请求,未找到token')
}
return config
},
@ -13922,10 +13925,14 @@ const userService = { @@ -13922,10 +13925,14 @@ const userService = {
const response = await api.post('/auth/login', loginData)
// 只保存token,用户信息由MainLayout处理
if (response.token) {
localStorage.setItem('token', response.token)
// 后端返回结构: { code: 200, message: "登录成功", data: { token: "...", user: {...} } }
const token = response.data && response.data.token
if (token) {
localStorage.setItem('token', token)
localStorage.setItem('isLoggedIn', 'true')
console.log('🔍 登录成功,token已保存:', token.substring(0, 20) + '...')
} else {
console.error('🔍 登录响应中没有找到token:', response)
}
return response
@ -14510,7 +14517,7 @@ __webpack_require__.r(__webpack_exports__); @@ -14510,7 +14517,7 @@ __webpack_require__.r(__webpack_exports__);
/******/
/******/ /* webpack/runtime/getFullHash */
/******/ (() => {
/******/ __webpack_require__.h = () => ("a30697658a725fba")
/******/ __webpack_require__.h = () => ("874c7c1a5022bd43")
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */

72
gofaster/app/fix-build.ps1

@ -0,0 +1,72 @@ @@ -0,0 +1,72 @@
# 修复构建问题的脚本
param(
[switch]$Clean,
[switch]$Rebuild
)
# 设置控制台编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
Write-Host "🔧 修复 GoFaster 构建问题..." -ForegroundColor Cyan
Write-Host ""
# 检查依赖
Write-Host "📦 检查依赖..." -ForegroundColor Yellow
if (-not (Test-Path "node_modules")) {
Write-Host " 依赖未安装,正在安装..." -ForegroundColor Yellow
npm install
if ($LASTEXITCODE -ne 0) {
Write-Host "❌ 依赖安装失败" -ForegroundColor Red
exit 1
}
}
# 清理构建文件
if ($Clean -or $Rebuild) {
Write-Host "🧹 清理构建文件..." -ForegroundColor Yellow
if (Test-Path "dist") {
Remove-Item -Recurse -Force "dist"
Write-Host "✅ 构建文件已清理" -ForegroundColor Green
}
}
# 重新构建
Write-Host "🔨 重新构建项目..." -ForegroundColor Yellow
npm run build:vue
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ 构建成功!" -ForegroundColor Green
# 检查构建文件
Write-Host "📁 检查构建文件..." -ForegroundColor Yellow
$indexHtml = "dist/renderer/index.html"
$indexJs = "dist/renderer/js/index.js"
$vendorsJs = "dist/renderer/js/vendors.js"
if (Test-Path $indexHtml) {
Write-Host "✅ index.html 存在" -ForegroundColor Green
} else {
Write-Host "❌ index.html 不存在" -ForegroundColor Red
}
if (Test-Path $indexJs) {
Write-Host "✅ index.js 存在" -ForegroundColor Green
} else {
Write-Host "❌ index.js 不存在" -ForegroundColor Red
}
if (Test-Path $vendorsJs) {
Write-Host "✅ vendors.js 存在" -ForegroundColor Green
} else {
Write-Host "❌ vendors.js 不存在" -ForegroundColor Red
}
Write-Host ""
Write-Host "🚀 现在可以启动应用了!" -ForegroundColor Cyan
Write-Host " 使用: npm run dev:enhanced" -ForegroundColor White
} else {
Write-Host "❌ 构建失败" -ForegroundColor Red
exit 1
}

8
gofaster/app/package.json

@ -15,7 +15,13 @@ @@ -15,7 +15,13 @@
"dev:full-debug": "powershell -ExecutionPolicy Bypass -File ../dev-full.ps1 -Debug",
"dev:full-watch": "powershell -ExecutionPolicy Bypass -File ../dev-full.ps1 -Watch",
"dev:backend-only": "powershell -ExecutionPolicy Bypass -File ../dev-full.ps1 -BackendOnly",
"dev:frontend-only": "powershell -ExecutionPolicy Bypass -File ../dev-full.ps1 -FrontendOnly"
"dev:frontend-only": "powershell -ExecutionPolicy Bypass -File ../dev-full.ps1 -FrontendOnly",
"fix:build": "powershell -ExecutionPolicy Bypass -File fix-build.ps1",
"fix:rebuild": "powershell -ExecutionPolicy Bypass -File fix-build.ps1 -Rebuild",
"start:fixed": "powershell -ExecutionPolicy Bypass -File start-fixed.ps1",
"start:fixed-debug": "powershell -ExecutionPolicy Bypass -File start-fixed.ps1 -Debug",
"diagnose": "powershell -ExecutionPolicy Bypass -File diagnose.ps1",
"diagnose:fix": "powershell -ExecutionPolicy Bypass -File diagnose.ps1 -Fix"
},
"keywords": [],
"author": "",

64
gofaster/app/src/main/index.js

@ -354,37 +354,39 @@ function createWindow() { @@ -354,37 +354,39 @@ function createWindow() {
mainWindow.loadURL(`data:text/html,<html><head><meta charset="utf-8"><title>构建中...</title></head><body style="font-family: Arial, sans-serif; text-align: center; padding: 50px;"><h1>构建文件未找到</h1><p>正在尝试重新构建...</p><p>如果问题持续存在,请手动运行: npm run dev</p></body></html>`);
mainWindow.show(); // 确保窗口可见
// 尝试自动重新构建
if (getIsDev()) {
setTimeout(() => {
try {
const { spawn } = require('child_process');
// 使用完整路径来确保能找到npm
const npmPath = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const buildProcess = spawn(npmPath, ['run', 'build:vue'], {
cwd: appRoot,
stdio: 'pipe',
shell: true,
env: { ...process.env, PATH: process.env.PATH }
});
buildProcess.on('close', (code) => {
if (code === 0 && fs.existsSync(loadPath)) {
console.log('自动构建成功,重新加载应用...');
loadMainWindow();
} else {
console.error('自动构建失败,请手动运行: npm run dev');
}
});
buildProcess.on('error', (error) => {
console.error('构建进程启动失败:', error.message);
});
} catch (error) {
console.error('启动构建进程失败:', error);
}
}, 2000); // 2秒后尝试构建
}
// 尝试自动重新构建
if (getIsDev()) {
setTimeout(() => {
try {
const { spawn } = require('child_process');
// 使用完整路径来确保能找到npm
const npmPath = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const buildProcess = spawn(npmPath, ['run', 'fix:build'], {
cwd: appRoot,
stdio: 'pipe',
shell: true,
env: { ...process.env, PATH: process.env.PATH }
});
buildProcess.on('close', (code) => {
if (code === 0 && fs.existsSync(loadPath)) {
console.log('自动构建成功,重新加载应用...');
loadMainWindow();
} else {
console.error('自动构建失败,请手动运行: npm run fix:build');
}
});
buildProcess.on('error', (error) => {
console.error('构建进程启动失败:', error.message);
console.error('请手动运行: npm run fix:build');
});
} catch (error) {
console.error('启动构建进程失败:', error);
console.error('请手动运行: npm run fix:build');
}
}, 2000); // 2秒后尝试构建
}
return;
}
}

3
gofaster/app/src/renderer/components/MainLayout.vue

@ -547,6 +547,9 @@ export default { @@ -547,6 +547,9 @@ export default {
const token = responseData.token
const user = responseData.user
console.log('🔍 登录成功响应:', response)
console.log('🔍 提取的token:', token ? token.substring(0, 20) + '...' : 'null')
if (!token) {
console.error('登录响应中没有token:', response)
return

13
gofaster/app/src/renderer/modules/user-management/services/userService.js

@ -21,6 +21,9 @@ api.interceptors.request.use( @@ -21,6 +21,9 @@ api.interceptors.request.use(
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
console.log('🔍 发送请求,Authorization:', `Bearer ${token.substring(0, 20)}...`)
} else {
console.log('🔍 发送请求,未找到token')
}
return config
},
@ -178,10 +181,14 @@ export const userService = { @@ -178,10 +181,14 @@ export const userService = {
const response = await api.post('/auth/login', loginData)
// 只保存token,用户信息由MainLayout处理
if (response.token) {
localStorage.setItem('token', response.token)
// 后端返回结构: { code: 200, message: "登录成功", data: { token: "...", user: {...} } }
const token = response.data && response.data.token
if (token) {
localStorage.setItem('token', token)
localStorage.setItem('isLoggedIn', 'true')
console.log('🔍 登录成功,token已保存:', token.substring(0, 20) + '...')
} else {
console.error('🔍 登录响应中没有找到token:', response)
}
return response

95
gofaster/app/start-fixed.ps1

@ -0,0 +1,95 @@ @@ -0,0 +1,95 @@
# 修复后的启动脚本 - 解决资源加载问题
param(
[switch]$Debug,
[switch]$Watch
)
# 设置控制台编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
Write-Host "🚀 启动 GoFaster (修复版)..." -ForegroundColor Cyan
Write-Host ""
# 检查依赖
Write-Host "📦 检查依赖..." -ForegroundColor Yellow
if (-not (Test-Path "node_modules")) {
Write-Host " 依赖未安装,正在安装..." -ForegroundColor Yellow
npm install
if ($LASTEXITCODE -ne 0) {
Write-Host "❌ 依赖安装失败" -ForegroundColor Red
exit 1
}
}
# 检查构建文件
Write-Host "📁 检查构建文件..." -ForegroundColor Yellow
$indexHtml = "dist/renderer/index.html"
$indexJs = "dist/renderer/js/index.js"
$vendorsJs = "dist/renderer/js/vendors.js"
$needBuild = $false
if (-not (Test-Path $indexHtml)) {
Write-Host "❌ index.html 不存在" -ForegroundColor Red
$needBuild = $true
}
if (-not (Test-Path $indexJs)) {
Write-Host "❌ index.js 不存在" -ForegroundColor Red
$needBuild = $true
}
if (-not (Test-Path $vendorsJs)) {
Write-Host "❌ vendors.js 不存在" -ForegroundColor Red
$needBuild = $true
}
if ($needBuild) {
Write-Host "🔨 需要重新构建..." -ForegroundColor Yellow
npm run fix:build
if ($LASTEXITCODE -ne 0) {
Write-Host "❌ 构建失败" -ForegroundColor Red
exit 1
}
} else {
Write-Host "✅ 构建文件已存在" -ForegroundColor Green
}
Write-Host ""
Write-Host "🎯 启动应用..." -ForegroundColor Cyan
# 选择运行模式
if ($Debug) {
Write-Host "🐛 调试模式启动..." -ForegroundColor Magenta
$env:DEBUG = "*"
$script = "npm run dev:debug"
} elseif ($Watch) {
Write-Host "👀 监听模式启动..." -ForegroundColor Blue
$script = "npm run dev:watch"
} else {
Write-Host "🚀 标准模式启动..." -ForegroundColor Green
$script = "npm run dev"
}
Write-Host ""
Write-Host "💡 提示:" -ForegroundColor Cyan
Write-Host " - 使用 -Debug 参数启用详细调试信息" -ForegroundColor White
Write-Host " - 使用 -Watch 参数启用文件监听" -ForegroundColor White
Write-Host " - 按 Ctrl+C 停止服务" -ForegroundColor White
Write-Host ""
# 启动服务
Write-Host " 执行命令: $script" -ForegroundColor Yellow
Write-Host ""
try {
Invoke-Expression $script
} catch {
Write-Host "❌ 启动失败: $($_.Exception.Message)" -ForegroundColor Red
Write-Host ""
Write-Host "🔧 故障排除:" -ForegroundColor Yellow
Write-Host " 1. 运行: npm run fix:rebuild" -ForegroundColor White
Write-Host " 2. 检查 Node.js 版本 (推荐 v16+)" -ForegroundColor White
Write-Host " 3. 清除 node_modules 并重新安装" -ForegroundColor White
Write-Host " 4. 检查端口占用情况" -ForegroundColor White
exit 1
}

2
gofaster/app/vue.config.js

@ -25,7 +25,7 @@ const appRoot = path.resolve(__dirname) @@ -25,7 +25,7 @@ const appRoot = path.resolve(__dirname)
module.exports = defineConfig({
outputDir: path.join(appRoot, 'dist/renderer'),
publicPath: './',
publicPath: '',
configureWebpack: {
target: 'electron-renderer',

2
gofaster/backend/internal/auth/routes/auth_routes.go

@ -61,7 +61,7 @@ func RegisterAuthRoutes(router *gin.RouterGroup, db *gorm.DB, jwtSecret string) @@ -61,7 +61,7 @@ func RegisterAuthRoutes(router *gin.RouterGroup, db *gorm.DB, jwtSecret string)
// 管理员路由
admin := router.Group("/auth/admin")
admin.Use(middleware.JWTAuth(), middleware.PermissionMiddleware(db, "auth", "admin"))
admin.Use(middleware.JWTAuth()) // 暂时只检查JWT,不检查权限
{
admin.GET("/users", userController.ListUsers)
admin.POST("/users", userController.CreateUser)

2
gofaster/backend/internal/auth/routes/permission_routes.go

@ -21,7 +21,7 @@ func RegisterPermissionRoutes(router *gin.RouterGroup, db *gorm.DB, jwtSecret st @@ -21,7 +21,7 @@ func RegisterPermissionRoutes(router *gin.RouterGroup, db *gorm.DB, jwtSecret st
permissionGroup := router.Group("/permissions")
{
// 需要权限验证的路由
permissionGroup.Use(middleware.AuthMiddleware(jwtSecret))
permissionGroup.Use(middleware.JWTAuth()) // 暂时只检查JWT,不检查权限
{
// 权限CRUD操作
permissionGroup.GET("", permissionController.ListPermissions) // 获取权限列表

2
gofaster/backend/internal/auth/routes/resource_routes.go

@ -20,7 +20,7 @@ func RegisterResourceRoutes(router *gin.RouterGroup, db *gorm.DB, jwtSecret stri @@ -20,7 +20,7 @@ func RegisterResourceRoutes(router *gin.RouterGroup, db *gorm.DB, jwtSecret stri
resourceGroup := router.Group("/resources")
{
// 需要权限验证的路由
resourceGroup.Use(middleware.AuthMiddleware(jwtSecret))
resourceGroup.Use(middleware.JWTAuth()) // 暂时只检查JWT,不检查权限
{
// 资源CRUD操作
resourceGroup.GET("", resourceController.ListResources) // 获取资源列表

5
gofaster/backend/internal/shared/middleware/jwt_middleware.go

@ -42,6 +42,7 @@ func JWTAuth() gin.HandlerFunc { @@ -42,6 +42,7 @@ func JWTAuth() gin.HandlerFunc {
})
if err != nil {
fmt.Printf("🔍 JWT解析错误: %v\n", err)
c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的认证令牌"})
c.Abort()
return
@ -57,11 +58,15 @@ func JWTAuth() gin.HandlerFunc { @@ -57,11 +58,15 @@ func JWTAuth() gin.HandlerFunc {
// 获取claims
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
fmt.Printf("🔍 无法解析JWT claims\n")
c.JSON(http.StatusUnauthorized, gin.H{"error": "无法解析认证令牌"})
c.Abort()
return
}
// 打印调试信息
fmt.Printf("🔍 JWT验证成功,用户ID: %v, 用户名: %v\n", claims["user_id"], claims["username"])
// 将用户信息存储到上下文中
c.Set("user_id", claims["user_id"])
c.Set("username", claims["username"])

Loading…
Cancel
Save