first commit
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
.next
|
||||
.git
|
||||
.gitignore
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
package-lock.json
|
||||
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Build output
|
||||
.next/
|
||||
dist/
|
||||
build/
|
||||
|
||||
# Database
|
||||
*.db
|
||||
prisma/dev.db
|
||||
prisma/dev.db-journal
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
# Docker (optional)
|
||||
casdoor-data/
|
||||
|
||||
# Testing
|
||||
coverage/
|
||||
.nyc_output/
|
||||
|
||||
# Misc
|
||||
*.tgz
|
||||
.turbo/
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(npm install)",
|
||||
"Bash(npx *)",
|
||||
"Bash(rm *)",
|
||||
"Bash(chmod *)",
|
||||
"Bash(npm run *)",
|
||||
"Bash(sleep *)",
|
||||
"Bash(curl *)",
|
||||
"Bash(pkill *)",
|
||||
"Bash(timeout *)",
|
||||
"Bash(nohup *)",
|
||||
"Bash(ss *)"
|
||||
]
|
||||
},
|
||||
"$version": 3
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(npm install)"
|
||||
]
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
# 阶段1: 构建前端
|
||||
FROM node:20-alpine AS frontend-builder
|
||||
WORKDIR /app/frontend
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
# 阶段2: 构建后端
|
||||
FROM node:20-alpine AS backend-builder
|
||||
WORKDIR /app/backend
|
||||
COPY backend/package*.json ./
|
||||
RUN npm ci
|
||||
COPY backend/ ./
|
||||
RUN npx prisma generate
|
||||
|
||||
# 阶段3: 生产环境
|
||||
FROM node:20-alpine AS production
|
||||
WORKDIR /app
|
||||
|
||||
# 安装nginx和sqlite
|
||||
RUN apk add --no-cache nginx sqlite
|
||||
|
||||
# 复制后端
|
||||
COPY --from=backend-builder /app/backend ./backend
|
||||
RUN cd backend && npm ci --only=production
|
||||
|
||||
# 复制前端构建
|
||||
COPY --from=frontend-builder /app/frontend/.next ./frontend/.next
|
||||
COPY --from=frontend-builder /app/frontend/package*.json ./frontend/
|
||||
COPY --from=frontend-builder /app/frontend/public ./frontend/public
|
||||
COPY --from=frontend-builder /app/frontend/next.config.ts ./frontend/
|
||||
COPY --from=frontend-builder /app/frontend/tsconfig.json ./frontend/
|
||||
RUN cd frontend && npm ci --only=production
|
||||
|
||||
# 复制nginx配置
|
||||
COPY docker/nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
# 复制启动脚本
|
||||
COPY docker/start.sh /app/start.sh
|
||||
RUN chmod +x /app/start.sh
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 3000
|
||||
|
||||
# 启动服务
|
||||
CMD ["/app/start.sh"]
|
||||
@@ -0,0 +1,355 @@
|
||||
# 门户登录基座应用 - 开发计划
|
||||
|
||||
## 项目概述
|
||||
|
||||
建立一个门户登录的基座应用,提供基础的用户认证功能,采用前后端分离架构,最终打包为单个Docker镜像部署。
|
||||
|
||||
---
|
||||
|
||||
## 技术栈
|
||||
|
||||
### 后端
|
||||
- **框架**: Node.js + Koa (ES Modules)
|
||||
- **ORM**: Prisma v5.22
|
||||
- **数据库**: SQLite
|
||||
- **认证**: OAuth 2.0 / OIDC (对接 Casdoor v3.18.0)
|
||||
- **JWT**: jsonwebtoken v9
|
||||
|
||||
### 前端
|
||||
- **框架**: Next.js 16 (App Router)
|
||||
- **React**: v19
|
||||
- **TypeScript**: v5
|
||||
- **UI组件库**: Radix UI + Lucide Icons + TailwindCSS v4
|
||||
- **状态管理**: Zustand v5
|
||||
- **HTTP客户端**: Axios
|
||||
|
||||
### 部署
|
||||
- **容器化**: Docker (多阶段构建)
|
||||
- **反向代理**: Nginx
|
||||
- **认证服务**: Casdoor v3.18.0 (本地Docker部署)
|
||||
|
||||
---
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
base-imtim/
|
||||
├── backend/ # Koa后端服务
|
||||
│ ├── prisma/ # Prisma ORM配置
|
||||
│ │ ├── migrations/ # 数据库迁移历史
|
||||
│ │ └── schema.prisma # 数据模型定义
|
||||
│ └── src/
|
||||
│ ├── config/ # 配置文件
|
||||
│ ├── controllers/ # 控制器
|
||||
│ ├── middleware/ # 中间件(认证、日志等)
|
||||
│ ├── routes/ # 路由定义
|
||||
│ ├── services/ # 业务逻辑
|
||||
│ └── index.js # 入口文件
|
||||
├── frontend/ # Next.js前端应用
|
||||
│ └── src/
|
||||
│ ├── app/ # App Router页面
|
||||
│ │ ├── api/ # API代理路由
|
||||
│ │ ├── dashboard/ # 仪表板(需认证)
|
||||
│ │ ├── login/ # 登录页
|
||||
│ │ └── page.tsx # 首页
|
||||
│ ├── components/ # React组件
|
||||
│ │ ├── header.tsx # 导航栏
|
||||
│ │ ├── layout.tsx # 布局组件
|
||||
│ │ └── protected-route.tsx # 路由守卫
|
||||
│ └── lib/
|
||||
│ ├── api.ts # HTTP客户端
|
||||
│ └── auth-store.ts # 认证状态管理
|
||||
├── docker/ # Docker配置
|
||||
│ ├── Dockerfile # 多阶段构建定义
|
||||
│ ├── nginx.conf # Nginx反向代理配置
|
||||
│ └── start.sh # 容器启动脚本
|
||||
├── docs/ # 文档
|
||||
│ └── casdoor-setup.md # Casdoor配置手册
|
||||
├── .gitignore # Git忽略规则
|
||||
├── docker-compose.yml # 开发环境编排
|
||||
├── PLAN.md # 本文件
|
||||
└── README.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 功能模块
|
||||
|
||||
### 1. 后端 (Koa)
|
||||
|
||||
#### 1.1 核心功能
|
||||
- [x] 项目初始化 (Koa + 中间件)
|
||||
- [x] 数据库配置 (SQLite + Prisma)
|
||||
- [x] 用户模型设计
|
||||
- `id`: UUID
|
||||
- `username`: 用户名
|
||||
- `email`: 邮箱
|
||||
- `avatar`: 头像URL
|
||||
- `casdoorId`: Casdoor用户ID
|
||||
- `createdAt`: 创建时间
|
||||
- `updatedAt`: 更新时间
|
||||
|
||||
#### 1.2 认证模块
|
||||
- [x] Casdoor OAuth 2.0 集成
|
||||
- `/api/auth/login` - 生成Casdoor登录链接
|
||||
- `/api/auth/callback` - 处理Casdoor回调
|
||||
- `/api/auth/logout` - 登出
|
||||
- `/api/auth/user` - 获取当前用户信息
|
||||
- [x] JWT Token管理
|
||||
- [x] 认证中间件
|
||||
|
||||
#### 1.3 API路由
|
||||
```
|
||||
POST /api/auth/login # 获取登录URL
|
||||
GET /api/auth/callback # OAuth回调
|
||||
POST /api/auth/logout # 登出
|
||||
GET /api/auth/user # 获取用户信息 (需认证)
|
||||
GET /api/health # 健康检查
|
||||
```
|
||||
|
||||
#### 1.4 中间件
|
||||
- [x] 认证中间件 (验证JWT)
|
||||
- [x] 错误处理中间件
|
||||
- [x] 日志中间件
|
||||
- [x] CORS中间件
|
||||
|
||||
### 2. 前端 (Next.js)
|
||||
|
||||
#### 2.1 页面结构
|
||||
- [x] 首页 (`/`)
|
||||
- [x] 登录页 (`/login`)
|
||||
- [x] 仪表板 (`/dashboard`) - 登录后可见
|
||||
- [x] API代理路由 (`/api/*`)
|
||||
|
||||
#### 2.2 核心组件
|
||||
- [x] Layout (布局组件)
|
||||
- Header (导航栏 + 用户菜单)
|
||||
- Footer (页脚)
|
||||
- [x] LoginButton (登录按钮)
|
||||
- [x] UserMenu (用户菜单 - Radix Dropdown)
|
||||
- [x] ProtectedRoute (受保护路由)
|
||||
|
||||
#### 2.3 功能实现
|
||||
- [x] 与后端API对接 (Axios)
|
||||
- [x] 认证状态管理 (Zustand + localStorage)
|
||||
- [x] 路由守卫 (未登录跳转)
|
||||
- [x] 响应式设计 (TailwindCSS v4)
|
||||
- [x] OAuth回调Token处理
|
||||
|
||||
---
|
||||
|
||||
## 开发步骤
|
||||
|
||||
### Phase 1: 项目初始化 ✅
|
||||
|
||||
#### 1.1 后端初始化
|
||||
```bash
|
||||
cd backend
|
||||
npm init -y
|
||||
npm install koa koa-router koa-bodyparser koa-cors
|
||||
npm install @prisma/client prisma
|
||||
npm install jsonwebtoken axios dotenv
|
||||
```
|
||||
|
||||
初始化Prisma:
|
||||
```bash
|
||||
npx prisma init
|
||||
```
|
||||
|
||||
#### 1.2 前端初始化
|
||||
```bash
|
||||
npx create-next-app@latest frontend --typescript --tailwind --app --src-dir
|
||||
cd frontend
|
||||
npm install @radix-ui/react-dialog @radix-ui/react-dropdown-menu
|
||||
npm install @radix-ui/react-avatar @radix-ui/react-separator
|
||||
npm install axios zustand lucide-react
|
||||
```
|
||||
|
||||
### Phase 2: 数据库与认证 ✅
|
||||
|
||||
#### 2.1 数据库模型
|
||||
`backend/prisma/schema.prisma`:
|
||||
```prisma
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
username String @unique
|
||||
email String? @unique
|
||||
avatar String?
|
||||
casdoorId String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
```
|
||||
|
||||
运行迁移:
|
||||
```bash
|
||||
npx prisma migrate dev
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
#### 2.2 Casdoor集成
|
||||
环境变量配置 (`backend/.env`):
|
||||
```env
|
||||
CASDOOR_SERVER_URL=http://localhost:8000
|
||||
CASDOOR_CLIENT_ID=your-client-id
|
||||
CASDOOR_CLIENT_SECRET=your-client-secret
|
||||
CASDOOR_ORG_NAME=imtim
|
||||
CASDOOR_APP_NAME=base-imtim
|
||||
CASDOOR_REDIRECT_URI=http://localhost:3000/api/auth/callback
|
||||
JWT_SECRET=your-jwt-secret-key
|
||||
APP_PORT=3001
|
||||
```
|
||||
|
||||
### Phase 3: 后端API开发 ✅
|
||||
|
||||
#### 3.1 认证流程实现
|
||||
|
||||
```
|
||||
1. 用户访问 /login → 点击登录
|
||||
2. 前端请求后端获取Casdoor登录URL
|
||||
3. 用户跳转到Casdoor登录
|
||||
4. 登录成功后Casdoor回调 /api/auth/callback
|
||||
5. Next.js API路由重定向到后端处理
|
||||
6. 后端用code换取token,获取用户信息
|
||||
7. 创建/更新本地用户记录
|
||||
8. 生成JWT token
|
||||
9. 重定向到前端dashboard,携带token
|
||||
10. 前端存储token到localStorage
|
||||
```
|
||||
|
||||
#### 3.2 核心服务
|
||||
|
||||
`backend/src/services/auth.service.js`:
|
||||
- `getLoginUrl()` - 生成Casdoor授权URL
|
||||
- `handleCallback(code, redirectUri)` - 处理OAuth回调
|
||||
- `verifyToken(token)` - 验证JWT
|
||||
|
||||
### Phase 4: 前端开发 ✅
|
||||
|
||||
#### 4.1 认证状态管理
|
||||
|
||||
`frontend/src/lib/auth-store.ts`:
|
||||
```typescript
|
||||
import { create } from 'zustand';
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
token: string | null;
|
||||
isAuthenticated: boolean;
|
||||
login: (token: string, user: User) => void;
|
||||
logout: () => void;
|
||||
initialize: () => void;
|
||||
}
|
||||
```
|
||||
|
||||
#### 4.2 API代理路由
|
||||
|
||||
`frontend/src/app/api/auth/*/route.ts`:
|
||||
- `/api/auth/login` - POST - 获取登录URL
|
||||
- `/api/auth/callback` - GET - OAuth回调重定向
|
||||
- `/api/auth/user` - GET - 获取用户信息
|
||||
- `/api/auth/logout` - POST - 登出
|
||||
|
||||
#### 4.3 受保护路由
|
||||
|
||||
`frontend/src/app/dashboard/page.tsx`:
|
||||
- 使用 Suspense 包裹 useSearchParams
|
||||
- Token从URL参数传递到API请求
|
||||
- 成功后存储到localStorage
|
||||
|
||||
### Phase 5: Docker化部署 ✅
|
||||
|
||||
#### 5.1 Dockerfile (多阶段构建)
|
||||
|
||||
```dockerfile
|
||||
# 阶段1: 构建前端
|
||||
FROM node:20-alpine AS frontend-builder
|
||||
WORKDIR /app/frontend
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
# 阶段2: 构建后端
|
||||
FROM node:20-alpine AS backend-builder
|
||||
WORKDIR /app/backend
|
||||
COPY backend/package*.json ./
|
||||
RUN npm ci
|
||||
COPY backend/ ./
|
||||
RUN npx prisma generate
|
||||
|
||||
# 阶段3: 生产环境
|
||||
FROM node:20-alpine AS production
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache nginx
|
||||
|
||||
# 复制后端和前端构建
|
||||
COPY --from=backend-builder /app/backend ./backend
|
||||
COPY --from=frontend-builder /app/frontend/.next ./frontend/.next
|
||||
|
||||
# 安装生产依赖、配置nginx、启动脚本
|
||||
# ...
|
||||
```
|
||||
|
||||
#### 5.2 Nginx配置
|
||||
|
||||
反向代理配置:
|
||||
- `/` → Next.js (3002)
|
||||
- `/api/` → Koa (3001)
|
||||
|
||||
---
|
||||
|
||||
## 开发状态
|
||||
|
||||
| 阶段 | 任务 | 状态 |
|
||||
|------|------|------|
|
||||
| Phase 1 | 项目初始化 | ✅ 已完成 |
|
||||
| Phase 2 | 数据库与认证配置 | ✅ 已完成 |
|
||||
| Phase 3 | 后端API开发 | ✅ 已完成 |
|
||||
| Phase 4 | 前端开发 | ✅ 已完成 |
|
||||
| Phase 5 | Docker化部署 | ✅ 已完成 |
|
||||
| **总计** | | **✅ 基座功能已完成** |
|
||||
|
||||
---
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **Casdoor版本**: 确保使用v3.18.0,API可能与其他版本不兼容
|
||||
2. **回调URL**: Casdoor配置的重定向URL必须为 `http://localhost:3000/api/auth/callback`
|
||||
3. **Casdoor用户信息端点**: v3.x 使用 `/api/get-account` 而非 `/api/userinfo`
|
||||
4. **网络配置**: Docker容器间通信需要使用服务名而非localhost
|
||||
5. **数据持久化**: SQLite数据库文件需要挂载volume以防数据丢失
|
||||
6. **useSearchParams**: 必须包裹在 Suspense 边界内
|
||||
|
||||
---
|
||||
|
||||
## 后续扩展
|
||||
|
||||
- [ ] 角色权限管理 (RBAC)
|
||||
- [ ] 多租户支持
|
||||
- [ ] 第三方登录 (GitHub, Google等)
|
||||
- [ ] 用户资料编辑
|
||||
- [ ] 审计日志
|
||||
- [ ] API限流
|
||||
- [ ] 监控与告警
|
||||
- [ ] 国际化 (i18n)
|
||||
|
||||
---
|
||||
|
||||
## 参考资源
|
||||
|
||||
- [Koa文档](https://koajs.com/)
|
||||
- [Next.js文档](https://nextjs.org/docs)
|
||||
- [Radix UI文档](https://www.radix-ui.com/)
|
||||
- [Casdoor文档](https://casdoor.org/docs/overview)
|
||||
- [Prisma文档](https://www.prisma.io/docs)
|
||||
- [Docker文档](https://docs.docker.com/)
|
||||
@@ -0,0 +1,155 @@
|
||||
# IMTIM Portal
|
||||
|
||||
企业级门户登录基座应用
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **后端**: Node.js + Koa (ES Modules)
|
||||
- **前端**: Next.js 16 (App Router) + React 19 + TypeScript
|
||||
- **UI组件库**: Radix UI + Lucide Icons + TailwindCSS v4
|
||||
- **数据库**: SQLite + Prisma ORM
|
||||
- **认证**: Casdoor v3.18.0 (OAuth 2.0)
|
||||
- **状态管理**: Zustand
|
||||
- **部署**: Docker (多阶段构建) + Nginx
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 前置要求
|
||||
|
||||
- Node.js >= 20
|
||||
- Casdoor v3.18.0 (本地Docker部署)
|
||||
|
||||
### 开发环境
|
||||
|
||||
1. **配置后端**
|
||||
```bash
|
||||
cd backend
|
||||
cp .env.example .env # 编辑Casdoor凭据
|
||||
npm install
|
||||
npx prisma migrate dev
|
||||
npx prisma generate
|
||||
npm run dev # 启动于 http://localhost:3001
|
||||
```
|
||||
|
||||
2. **启动前端**
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev # 启动于 http://localhost:3000
|
||||
```
|
||||
|
||||
3. **访问应用**
|
||||
- 前端: http://localhost:3000
|
||||
- 后端API: http://localhost:3001
|
||||
|
||||
### Docker 部署
|
||||
|
||||
```bash
|
||||
docker build -t imtim-portal:latest .
|
||||
|
||||
docker run -d \
|
||||
--name imtim-portal \
|
||||
-p 3000:3000 \
|
||||
-e CASDOOR_SERVER_URL=http://your-casdoor:8000 \
|
||||
-e CASDOOR_CLIENT_ID=xxx \
|
||||
-e CASDOOR_CLIENT_SECRET=xxx \
|
||||
-e JWT_SECRET=xxx \
|
||||
imtim-portal:latest
|
||||
```
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
base-imtim/
|
||||
├── backend/ # Koa后端服务
|
||||
│ ├── prisma/
|
||||
│ │ ├── migrations/ # 数据库迁移
|
||||
│ │ └── schema.prisma # 数据模型
|
||||
│ └── src/
|
||||
│ ├── config/ # 配置文件
|
||||
│ ├── controllers/ # 控制器
|
||||
│ ├── middleware/ # 中间件(认证等)
|
||||
│ ├── routes/ # 路由
|
||||
│ ├── services/ # 业务逻辑
|
||||
│ └── index.js # 入口文件
|
||||
├── frontend/ # Next.js前端应用
|
||||
│ └── src/
|
||||
│ ├── app/ # App Router页面
|
||||
│ │ ├── api/ # API代理路由
|
||||
│ │ ├── dashboard/ # 仪表板(需认证)
|
||||
│ │ ├── login/ # 登录页
|
||||
│ │ └── page.tsx # 首页
|
||||
│ ├── components/ # React组件
|
||||
│ │ ├── header.tsx # 导航栏
|
||||
│ │ ├── layout.tsx # 布局组件
|
||||
│ │ └── protected-route.tsx
|
||||
│ └── lib/
|
||||
│ ├── api.ts # HTTP客户端
|
||||
│ └── auth-store.ts # 认证状态管理
|
||||
├── docker/ # Docker配置
|
||||
│ ├── Dockerfile # 多阶段构建
|
||||
│ ├── nginx.conf # 反向代理
|
||||
│ └── start.sh # 启动脚本
|
||||
├── docs/ # 文档
|
||||
│ └── casdoor-setup.md # Casdoor配置手册
|
||||
├── docker-compose.yml # 开发环境编排
|
||||
├── PLAN.md # 开发计划
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## API文档
|
||||
|
||||
| 方法 | 路径 | 描述 | 认证 |
|
||||
|------|------|------|------|
|
||||
| POST | /api/auth/login | 获取Casdoor登录URL | 无 |
|
||||
| GET | /api/auth/callback | OAuth回调处理 | 无 |
|
||||
| POST | /api/auth/logout | 登出 | 需要Token |
|
||||
| GET | /api/auth/user | 获取当前用户信息 | 需要Token |
|
||||
| GET | /api/health | 健康检查 | 无 |
|
||||
|
||||
## 环境变量
|
||||
|
||||
### 后端 (backend/.env)
|
||||
|
||||
| 变量 | 描述 | 默认值 |
|
||||
|------|------|--------|
|
||||
| CASDOOR_SERVER_URL | Casdoor服务器URL | http://localhost:8000 |
|
||||
| CASDOOR_CLIENT_ID | 客户端ID | - |
|
||||
| CASDOOR_CLIENT_SECRET | 客户端密钥 | - |
|
||||
| CASDOOR_ORG_NAME | 组织名称 | imtim |
|
||||
| CASDOOR_APP_NAME | 应用名称 | base-imtim |
|
||||
| CASDOOR_REDIRECT_URI | OAuth回调URL | http://localhost:3000/api/auth/callback |
|
||||
| JWT_SECRET | JWT密钥 | - |
|
||||
| APP_PORT | 后端端口 | 3001 |
|
||||
| FRONTEND_URL | 前端URL | http://localhost:3000 |
|
||||
|
||||
### 前端 (frontend/.env.local)
|
||||
|
||||
| 变量 | 描述 | 默认值 |
|
||||
|------|------|--------|
|
||||
| NEXT_PUBLIC_API_URL | 后端API地址 | http://localhost:3001/api |
|
||||
| BACKEND_URL | 后端服务器URL | http://localhost:3001 |
|
||||
| FRONTEND_URL | 前端服务器URL | http://localhost:3000 |
|
||||
|
||||
## 认证流程
|
||||
|
||||
```
|
||||
1. 用户访问 /login → 点击登录按钮
|
||||
2. 前端请求 /api/auth/login → 获取Casdoor授权URL
|
||||
3. 用户跳转到Casdoor登录页面
|
||||
4. 登录成功后Casdoor回调 /api/auth/callback?code=xxx
|
||||
5. Next.js API路由重定向到后端 /api/auth/callback
|
||||
6. 后端用code换取token,获取用户信息
|
||||
7. 创建/更新本地用户,生成JWT
|
||||
8. 重定向到 /dashboard?token=xxx
|
||||
9. 前端存储token到localStorage,后续请求自动携带
|
||||
```
|
||||
|
||||
## 文档
|
||||
|
||||
- [开发计划](PLAN.md)
|
||||
- [Casdoor配置手册](docs/casdoor-setup.md)
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,18 @@
|
||||
# Casdoor配置
|
||||
CASDOOR_SERVER_URL=http://localhost:8000
|
||||
CASDOOR_CLIENT_ID=your-client-id
|
||||
CASDOOR_CLIENT_SECRET=your-client-secret
|
||||
CASDOOR_ORG_NAME=imtim
|
||||
CASDOOR_APP_NAME=base-imtim
|
||||
CASDOOR_REDIRECT_URI=http://localhost:3000/api/auth/callback
|
||||
|
||||
# JWT配置
|
||||
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
|
||||
|
||||
# 应用配置
|
||||
APP_PORT=3001
|
||||
NODE_ENV=development
|
||||
FRONTEND_URL=http://localhost:3000
|
||||
|
||||
# 数据库
|
||||
DATABASE_URL=file:./prisma/dev.db
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "1.0.0",
|
||||
"description": "Koa backend for IMTIM Portal",
|
||||
"main": "src/index.js",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "nodemon src/index.js",
|
||||
"start": "node src/index.js",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:generate": "prisma generate",
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/client": "^5.22.0",
|
||||
"axios": "^1.15.0",
|
||||
"casdoor-nodejs-sdk": "^1.27.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"koa": "^2.15.3",
|
||||
"koa-bodyparser": "^4.4.1",
|
||||
"koa-cors": "^0.0.16",
|
||||
"koa-router": "^12.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.1.7",
|
||||
"prisma": "^5.22.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "User" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"username" TEXT NOT NULL,
|
||||
"email" TEXT,
|
||||
"avatar" TEXT,
|
||||
"casdoorId" TEXT NOT NULL,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_casdoorId_key" ON "User"("casdoorId");
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "sqlite"
|
||||
@@ -0,0 +1,19 @@
|
||||
// Prisma Schema
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
username String @unique
|
||||
email String? @unique
|
||||
avatar String?
|
||||
casdoorId String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
export default prisma;
|
||||
@@ -0,0 +1,21 @@
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export const config = {
|
||||
casdoor: {
|
||||
serverUrl: process.env.CASDOOR_SERVER_URL,
|
||||
clientId: process.env.CASDOOR_CLIENT_ID,
|
||||
clientSecret: process.env.CASDOOR_CLIENT_SECRET,
|
||||
orgName: process.env.CASDOOR_ORG_NAME,
|
||||
appName: process.env.CASDOOR_APP_NAME,
|
||||
},
|
||||
jwt: {
|
||||
secret: process.env.JWT_SECRET,
|
||||
expiresIn: '7d',
|
||||
},
|
||||
app: {
|
||||
port: parseInt(process.env.APP_PORT || '3001', 10),
|
||||
env: process.env.NODE_ENV || 'development',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
import { getLoginUrl, handleCallback } from '../services/auth.service.js';
|
||||
import prisma from '../config/database.js';
|
||||
|
||||
/**
|
||||
* POST /api/auth/login
|
||||
* 获取 Casdoor 登录 URL
|
||||
*/
|
||||
export const login = (ctx) => {
|
||||
const loginUrl = getLoginUrl();
|
||||
ctx.body = {
|
||||
success: true,
|
||||
data: { loginUrl },
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* GET /api/auth/callback
|
||||
* 处理 Casdoor OAuth 回调
|
||||
*/
|
||||
export const callback = async (ctx) => {
|
||||
const { code } = ctx.query;
|
||||
|
||||
if (!code) {
|
||||
ctx.status = 400;
|
||||
ctx.body = {
|
||||
success: false,
|
||||
message: 'Missing authorization code',
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const redirectUri = process.env.CASDOOR_REDIRECT_URI || 'http://localhost:3000/api/auth/callback';
|
||||
const { user, token } = await handleCallback(code, redirectUri);
|
||||
|
||||
// 重定向到前端仪表板,携带 token
|
||||
ctx.redirect(`${process.env.FRONTEND_URL || 'http://localhost:3000'}/dashboard?token=${token}`);
|
||||
} catch (error) {
|
||||
ctx.status = 401;
|
||||
ctx.body = {
|
||||
success: false,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /api/auth/logout
|
||||
* 登出
|
||||
*/
|
||||
export const logout = (ctx) => {
|
||||
// JWT 是无状态的,客户端删除 token 即可
|
||||
ctx.body = {
|
||||
success: true,
|
||||
message: 'Logged out successfully',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* GET /api/auth/user
|
||||
* 获取当前用户信息
|
||||
*/
|
||||
export const getUser = async (ctx) => {
|
||||
try {
|
||||
const userId = ctx.state.user.userId;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
avatar: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
ctx.body = {
|
||||
success: false,
|
||||
message: 'User not found',
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
data: user,
|
||||
};
|
||||
} catch (error) {
|
||||
ctx.status = 500;
|
||||
ctx.body = {
|
||||
success: false,
|
||||
message: 'Failed to fetch user info',
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
import Koa from 'koa';
|
||||
import bodyParser from 'koa-bodyparser';
|
||||
import cors from 'koa-cors';
|
||||
import { config } from './config/index.js';
|
||||
import authRoutes from './routes/auth.routes.js';
|
||||
import healthRoutes from './routes/health.routes.js';
|
||||
|
||||
const app = new Koa();
|
||||
|
||||
// 中间件
|
||||
app.use(cors());
|
||||
app.use(bodyParser());
|
||||
|
||||
// 日志中间件
|
||||
app.use(async (ctx, next) => {
|
||||
const start = Date.now();
|
||||
await next();
|
||||
const ms = Date.now() - start;
|
||||
console.log(`${ctx.method} ${ctx.path} - ${ms}ms`);
|
||||
});
|
||||
|
||||
// 错误处理中间件
|
||||
app.use(async (ctx, next) => {
|
||||
try {
|
||||
await next();
|
||||
} catch (error) {
|
||||
console.error('Server error:', error);
|
||||
ctx.status = error.status || 500;
|
||||
ctx.body = {
|
||||
success: false,
|
||||
message: error.message || 'Internal Server Error',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// 路由
|
||||
app.use(authRoutes.routes());
|
||||
app.use(authRoutes.allowedMethods());
|
||||
app.use(healthRoutes.routes());
|
||||
app.use(healthRoutes.allowedMethods());
|
||||
|
||||
// 启动服务器
|
||||
const PORT = config.app.port;
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 Backend server running on http://localhost:${PORT}`);
|
||||
console.log(`📊 Environment: ${config.app.env}`);
|
||||
});
|
||||
|
||||
export default app;
|
||||
@@ -0,0 +1,32 @@
|
||||
import { verifyToken } from '../services/auth.service.js';
|
||||
|
||||
/**
|
||||
* 认证中间件 - 验证 JWT token
|
||||
*/
|
||||
export const authMiddleware = async (ctx, next) => {
|
||||
const authHeader = ctx.headers.authorization;
|
||||
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
ctx.status = 401;
|
||||
ctx.body = {
|
||||
success: false,
|
||||
message: 'Unauthorized: No token provided',
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const token = authHeader.split(' ')[1];
|
||||
const decoded = verifyToken(token);
|
||||
|
||||
if (!decoded) {
|
||||
ctx.status = 401;
|
||||
ctx.body = {
|
||||
success: false,
|
||||
message: 'Unauthorized: Invalid token',
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.state.user = decoded;
|
||||
await next();
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import Router from 'koa-router';
|
||||
import { login, callback, logout, getUser } from '../controllers/auth.controller.js';
|
||||
import { authMiddleware } from '../middleware/auth.js';
|
||||
|
||||
const router = new Router({ prefix: '/api/auth' });
|
||||
|
||||
// 公开路由
|
||||
router.post('/login', login);
|
||||
router.get('/callback', callback);
|
||||
router.post('/logout', logout);
|
||||
|
||||
// 需要认证的路由
|
||||
router.get('/user', authMiddleware, getUser);
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,13 @@
|
||||
import Router from 'koa-router';
|
||||
|
||||
const router = new Router({ prefix: '/api' });
|
||||
|
||||
router.get('/health', (ctx) => {
|
||||
ctx.body = {
|
||||
success: true,
|
||||
message: 'OK',
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,109 @@
|
||||
import axios from 'axios';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { config } from '../config/index.js';
|
||||
import prisma from '../config/database.js';
|
||||
|
||||
/**
|
||||
* 生成 Casdoor 登录 URL
|
||||
*/
|
||||
export const getLoginUrl = () => {
|
||||
const { serverUrl, clientId, appName, orgName } = config.casdoor;
|
||||
// Casdoor回调到前端3000端口,middleware代理转发到后端
|
||||
const redirectUri = process.env.CASDOOR_REDIRECT_URI || 'http://localhost:3000/api/auth/callback';
|
||||
const state = 'imtim-portal';
|
||||
|
||||
return `${serverUrl}/login/oauth/authorize?client_id=${clientId}&response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}&scope=read&state=${state}&org=${orgName}&app=${appName}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理 Casdoor OAuth 回调
|
||||
*/
|
||||
export const handleCallback = async (code, redirectUri) => {
|
||||
try {
|
||||
// 用 code 换取 token
|
||||
const tokenResponse = await axios.post(
|
||||
`${config.casdoor.serverUrl}/api/login/oauth/access_token`,
|
||||
new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
client_id: config.casdoor.clientId,
|
||||
client_secret: config.casdoor.clientSecret,
|
||||
code: code,
|
||||
redirect_uri: redirectUri,
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const { access_token } = tokenResponse.data;
|
||||
|
||||
if (!access_token) {
|
||||
console.error('Token response:', tokenResponse.data);
|
||||
throw new Error('Failed to get access token');
|
||||
}
|
||||
|
||||
// 获取用户信息 - Casdoor v3.x 使用 /api/get-account
|
||||
const userResponse = await axios.get(
|
||||
`${config.casdoor.serverUrl}/api/get-account`,
|
||||
{
|
||||
headers: {
|
||||
'Authorization': `Bearer ${access_token}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Casdoor get-account response:', JSON.stringify(userResponse.data, null, 2));
|
||||
|
||||
const userInfo = userResponse.data.data;
|
||||
|
||||
if (!userInfo || !userInfo.id) {
|
||||
console.error('User info missing. Got:', userInfo);
|
||||
throw new Error('Failed to get user info');
|
||||
}
|
||||
|
||||
// 创建或更新本地用户
|
||||
const user = await prisma.user.upsert({
|
||||
where: { casdoorId: userInfo.id },
|
||||
update: {
|
||||
username: userInfo.name || userInfo.displayName,
|
||||
email: userInfo.email,
|
||||
avatar: userInfo.avatar,
|
||||
},
|
||||
create: {
|
||||
username: userInfo.name || userInfo.displayName || 'user',
|
||||
email: userInfo.email || null,
|
||||
casdoorId: userInfo.id,
|
||||
avatar: userInfo.avatar || null,
|
||||
},
|
||||
});
|
||||
|
||||
// 生成 JWT
|
||||
const jwtToken = jwt.sign(
|
||||
{
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
casdoorId: user.casdoorId,
|
||||
},
|
||||
config.jwt.secret,
|
||||
{ expiresIn: config.jwt.expiresIn }
|
||||
);
|
||||
|
||||
return { user, token: jwtToken };
|
||||
} catch (error) {
|
||||
console.error('OAuth callback error:', error.response?.data || error.message);
|
||||
throw new Error(`Authentication failed: ${error.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 验证 JWT token
|
||||
*/
|
||||
export const verifyToken = (token) => {
|
||||
try {
|
||||
return jwt.verify(token, config.jwt.secret);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
casdoor:
|
||||
image: casbin/casdoor:v3.18.0
|
||||
container_name: casdoor
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
- driverName=sqlite3
|
||||
- dataSourceName=casdoor.db
|
||||
volumes:
|
||||
- ./casdoor-data:/conf
|
||||
restart: unless-stopped
|
||||
|
||||
# 开发环境不需要单独启动app服务
|
||||
# app:
|
||||
# build: .
|
||||
# container_name: imtim-portal
|
||||
# ports:
|
||||
# - "3000:3000"
|
||||
# environment:
|
||||
# - CASDOOR_SERVER_URL=http://casdoor:8000
|
||||
# - CASDOOR_CLIENT_ID=your-client-id
|
||||
# - CASDOOR_CLIENT_SECRET=your-client-secret
|
||||
# - JWT_SECRET=your-jwt-secret
|
||||
# depends_on:
|
||||
# - casdoor
|
||||
@@ -0,0 +1,54 @@
|
||||
worker_processes auto;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
sendfile on;
|
||||
keepalive_timeout 65;
|
||||
|
||||
upstream frontend {
|
||||
server 127.0.0.1:3002; # Next.js
|
||||
}
|
||||
|
||||
upstream backend {
|
||||
server 127.0.0.1:3001; # Koa
|
||||
}
|
||||
|
||||
server {
|
||||
listen 3000;
|
||||
server_name localhost;
|
||||
|
||||
# 前端路由
|
||||
location / {
|
||||
proxy_pass http://frontend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
|
||||
# API路由
|
||||
location /api/ {
|
||||
proxy_pass http://backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
error_page 500 502 503 504 /50x.html;
|
||||
location = /50x.html {
|
||||
root /usr/share/nginx/html;
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
|
||||
# 启动后端
|
||||
cd /app/backend
|
||||
node src/index.js &
|
||||
|
||||
# 启动前端
|
||||
cd /app/frontend
|
||||
HOSTNAME=127.0.0.1 PORT=3002 node server.js &
|
||||
|
||||
# 启动nginx
|
||||
nginx -g 'daemon off;'
|
||||
@@ -0,0 +1,204 @@
|
||||
# Casdoor v3.18.0 配置手册
|
||||
|
||||
本文档详细说明如何配置本地Docker部署的Casdoor实例,以便与base-imtim门户应用集成。
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
1. [访问Casdoor管理界面](#1-访问casdoor管理界面)
|
||||
2. [创建组织](#2-创建组织)
|
||||
3. [创建应用](#3-创建应用)
|
||||
4. [配置认证方式](#4-配置认证方式)
|
||||
5. [配置到base-imtim](#5-配置到base-imtim)
|
||||
6. [测试登录流程](#6-测试登录流程)
|
||||
7. [常见问题排查](#7-常见问题排查)
|
||||
|
||||
---
|
||||
|
||||
## 1. 访问Casdoor管理界面
|
||||
|
||||
### 1.1 确认Casdoor运行状态
|
||||
|
||||
```bash
|
||||
docker ps | grep casdoor
|
||||
```
|
||||
|
||||
### 1.2 访问管理后台
|
||||
|
||||
```
|
||||
http://localhost:8000
|
||||
```
|
||||
|
||||
### 1.3 登录
|
||||
|
||||
- **用户名**: `admin`
|
||||
- **密码**: `123` (默认)
|
||||
|
||||
> ⚠️ 首次登录后请修改密码
|
||||
|
||||
---
|
||||
|
||||
## 2. 创建组织
|
||||
|
||||
1. 左侧导航栏 → **组织管理** → **组织**
|
||||
2. 点击 **添加**
|
||||
3. 填写:
|
||||
|
||||
| 字段 | 值 |
|
||||
|------|------|
|
||||
| 组织名称 | `imtim` |
|
||||
| 显示名称 | `IMTIM Portal` |
|
||||
| 密码类型 | `salt` |
|
||||
|
||||
4. 点击 **保存**
|
||||
|
||||
---
|
||||
|
||||
## 3. 创建应用
|
||||
|
||||
1. 左侧导航栏 → **应用管理** → **应用**
|
||||
2. 点击 **添加**
|
||||
3. 填写配置:
|
||||
|
||||
### 基本信息
|
||||
|
||||
| 字段 | 值 | 说明 |
|
||||
|------|------|------|
|
||||
| 名称 | `base-imtim` | 应用唯一标识 |
|
||||
| 显示名称 | `IMTIM Portal` | 界面显示名称 |
|
||||
| 组织 | `imtim` | 选择刚创建的组织 |
|
||||
|
||||
### 认证配置 (关键)
|
||||
|
||||
| 字段 | 值 | 说明 |
|
||||
|------|------|------|
|
||||
| **重定向URL** | `http://localhost:3000/api/auth/callback` | **必须一致** |
|
||||
| 令牌格式 | `JWT` | |
|
||||
| 令牌有效期 | `168` | 7天(小时) |
|
||||
|
||||
4. 点击 **保存**
|
||||
|
||||
5. **复制凭据**:
|
||||
- Client ID (如: `a129daf893d964c03bfb`)
|
||||
- Client Secret (如: `c3ecaa0d0e3f315d0a1a164087c88cbdf8324f00`)
|
||||
|
||||
---
|
||||
|
||||
## 4. 配置认证方式
|
||||
|
||||
### 4.1 创建测试用户
|
||||
|
||||
1. 左侧导航栏 → **用户管理** → **用户**
|
||||
2. 点击 **添加**
|
||||
3. 填写:
|
||||
- 组织: `imtim`
|
||||
- 用户名: 如 `imtim`
|
||||
- 显示名称
|
||||
- 密码
|
||||
- 邮箱 (可选)
|
||||
4. 点击 **保存**
|
||||
|
||||
---
|
||||
|
||||
## 5. 配置到base-imtim
|
||||
|
||||
### 5.1 创建后端配置文件
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
### 5.2 编辑 .env 文件
|
||||
|
||||
```env
|
||||
# Casdoor配置
|
||||
CASDOOR_SERVER_URL=http://localhost:8000
|
||||
CASDOOR_CLIENT_ID=你的ClientID
|
||||
CASDOOR_CLIENT_SECRET=你的ClientSecret
|
||||
CASDOOR_ORG_NAME=imtim
|
||||
CASDOOR_APP_NAME=base-imtim
|
||||
CASDOOR_REDIRECT_URI=http://localhost:3000/api/auth/callback
|
||||
|
||||
# JWT配置
|
||||
JWT_SECRET=your-super-secret-jwt-key
|
||||
|
||||
# 应用配置
|
||||
APP_PORT=3001
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 测试登录流程
|
||||
|
||||
### 6.1 启动应用
|
||||
|
||||
```bash
|
||||
# 后端
|
||||
cd backend && npm run dev
|
||||
|
||||
# 前端 (新终端)
|
||||
cd frontend && npm run dev
|
||||
```
|
||||
|
||||
### 6.2 测试步骤
|
||||
|
||||
1. 访问 http://localhost:3000
|
||||
2. 点击登录按钮
|
||||
3. 跳转到Casdoor登录页面
|
||||
4. 使用测试用户登录
|
||||
5. 登录成功后应自动跳转到 /dashboard
|
||||
|
||||
---
|
||||
|
||||
## 7. 常见问题排查
|
||||
|
||||
### 7.1 重定向URL不匹配
|
||||
|
||||
**错误**: `redirect URI mismatch`
|
||||
|
||||
**解决**: 检查Casdoor应用配置中的重定向URL是否为 `http://localhost:3000/api/auth/callback`
|
||||
|
||||
### 7.2 获取用户信息失败
|
||||
|
||||
**错误**: `Authentication failed: Failed to get user info`
|
||||
|
||||
**解决**: Casdoor v3.x 使用 `/api/get-account` 而非 `/api/userinfo`
|
||||
|
||||
### 7.3 Client ID或Secret错误
|
||||
|
||||
**错误**: `invalid_client`
|
||||
|
||||
**解决**: 重新从Casdoor复制Client ID和Secret
|
||||
|
||||
### 7.4 Code已使用
|
||||
|
||||
**错误**: `authorization code has been used`
|
||||
|
||||
**说明**: OAuth code只能用一次,刷新页面重新登录
|
||||
|
||||
---
|
||||
|
||||
## 附录: Casdoor Docker部署
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
casdoor:
|
||||
image: casbin/casdoor:v3.18.0
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
- driverName=sqlite3
|
||||
- dataSourceName=casdoor.db
|
||||
volumes:
|
||||
- ./casdoor-data:/conf
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**文档版本**: 1.1
|
||||
**最后更新**: 2026-04-16
|
||||
**适用Casdoor版本**: v3.18.0
|
||||
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
@@ -0,0 +1,36 @@
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -0,0 +1,13 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: '/api/:path*',
|
||||
destination: 'http://localhost:3001/api/:path*',
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"axios": "^1.15.0",
|
||||
"http-proxy-middleware": "^3.0.5",
|
||||
"lucide-react": "^1.8.0",
|
||||
"next": "^16.2.4",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"zustand": "^5.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.4",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
@@ -0,0 +1,25 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001';
|
||||
const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:3000';
|
||||
|
||||
// GET /api/auth/callback - 处理OAuth回调
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
|
||||
if (!code) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Missing authorization code' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 重定向到后端处理
|
||||
const backendCallbackUrl = new URL('/api/auth/callback', BACKEND_URL);
|
||||
backendCallbackUrl.searchParams.set('code', code);
|
||||
if (state) backendCallbackUrl.searchParams.set('state', state);
|
||||
|
||||
return NextResponse.redirect(backendCallbackUrl.toString());
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001';
|
||||
|
||||
// POST /api/auth/login - 获取登录URL
|
||||
export async function POST() {
|
||||
const res = await fetch(`${BACKEND_URL}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
});
|
||||
const data = await res.json();
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001';
|
||||
|
||||
// POST /api/auth/logout - 登出
|
||||
export async function POST() {
|
||||
const res = await fetch(`${BACKEND_URL}/api/auth/logout`, {
|
||||
method: 'POST',
|
||||
});
|
||||
const data = await res.json();
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001';
|
||||
|
||||
// GET /api/auth/user - 获取用户信息
|
||||
export async function GET(request: NextRequest) {
|
||||
// 从 cookie 或 query 参数获取 token
|
||||
const token = request.nextUrl.searchParams.get('token') ||
|
||||
request.cookies.get('token')?.value ||
|
||||
request.headers.get('authorization')?.replace('Bearer ', '');
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'No token provided' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const res = await fetch(`${BACKEND_URL}/api/auth/user`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
return NextResponse.json(data, { status: res.status });
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, Suspense } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { getUserInfo } from '@/lib/api';
|
||||
import Layout from '@/components/layout';
|
||||
|
||||
function DashboardContent() {
|
||||
const { login, initialize } = useAuthStore();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
initialize();
|
||||
}, [initialize]);
|
||||
|
||||
useEffect(() => {
|
||||
const token = searchParams.get('token');
|
||||
if (token) {
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
// 先用 URL 中的 token 直接请求用户信息
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api'}/auth/user`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
const result = await res.json();
|
||||
const user = result.data;
|
||||
|
||||
// 成功后存入 localStorage
|
||||
login(token, user);
|
||||
router.replace('/dashboard');
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch user info:', error);
|
||||
router.push('/login');
|
||||
}
|
||||
};
|
||||
fetchUser();
|
||||
}
|
||||
}, [searchParams, login, router]);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<h1 className="text-3xl font-bold mb-6">仪表板</h1>
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="rounded-lg border p-6 shadow-sm">
|
||||
<h2 className="text-xl font-semibold mb-2">欢迎</h2>
|
||||
<p className="text-muted-foreground">
|
||||
您已成功登录 IMTIM Portal
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-6 shadow-sm">
|
||||
<h2 className="text-xl font-semibold mb-2">账户状态</h2>
|
||||
<p className="text-green-600 font-medium">已激活</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-6 shadow-sm">
|
||||
<h2 className="text-xl font-semibold mb-2">系统信息</h2>
|
||||
<p className="text-muted-foreground">版本 1.0.0</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
return (
|
||||
<Layout>
|
||||
<Suspense fallback={<div className="container mx-auto px-4 py-8">加载中...</div>}>
|
||||
<DashboardContent />
|
||||
</Suspense>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,34 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--destructive-foreground: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
* {
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Metadata } from 'next';
|
||||
import './globals.css';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'IMTIM Portal',
|
||||
description: '企业级门户登录基座应用',
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body className="antialiased">
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { getLoginUrl } from '@/lib/api';
|
||||
import { LogIn } from 'lucide-react';
|
||||
import Layout from '@/components/layout';
|
||||
|
||||
export default function LoginPage() {
|
||||
const { isAuthenticated } = useAuthStore();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
router.push('/dashboard');
|
||||
}
|
||||
}, [isAuthenticated, router]);
|
||||
|
||||
const handleLogin = async () => {
|
||||
try {
|
||||
const loginUrl = await getLoginUrl();
|
||||
window.location.href = loginUrl;
|
||||
} catch (error) {
|
||||
console.error('Failed to get login URL:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="flex items-center justify-center min-h-[calc(100vh-12rem)]">
|
||||
<div className="w-full max-w-md">
|
||||
<div className="rounded-lg border p-8 shadow-sm">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl font-bold mb-2">登录</h1>
|
||||
<p className="text-muted-foreground">
|
||||
使用 Casdoor 账号登录 IMTIM Portal
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleLogin}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
|
||||
>
|
||||
<LogIn className="h-5 w-5" />
|
||||
<span>使用 Casdoor 登录</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { ArrowRight, Shield, Zap, Users } from 'lucide-react';
|
||||
import Layout from '@/components/layout';
|
||||
|
||||
export default function Home() {
|
||||
const { isAuthenticated, initialize } = useAuthStore();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
initialize();
|
||||
}, [initialize]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
router.push('/dashboard');
|
||||
}
|
||||
}, [isAuthenticated, router]);
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="flex flex-col items-center">
|
||||
{/* Hero Section */}
|
||||
<section className="w-full py-24 bg-gradient-to-b from-background to-secondary/20">
|
||||
<div className="container px-4 text-center">
|
||||
<h1 className="text-4xl md:text-6xl font-bold tracking-tight mb-4">
|
||||
IMTIM Portal
|
||||
</h1>
|
||||
<p className="text-xl text-muted-foreground mb-8 max-w-2xl mx-auto">
|
||||
企业级门户登录基座应用,安全、高效、易于扩展
|
||||
</p>
|
||||
<button
|
||||
onClick={() => router.push('/login')}
|
||||
className="inline-flex items-center gap-2 px-6 py-3 text-base font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
开始使用
|
||||
<ArrowRight className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Features Section */}
|
||||
<section className="w-full py-16">
|
||||
<div className="container px-4">
|
||||
<h2 className="text-3xl font-bold text-center mb-12">核心特性</h2>
|
||||
<div className="grid gap-8 md:grid-cols-3 max-w-5xl mx-auto">
|
||||
<div className="rounded-lg border p-6 text-center">
|
||||
<Shield className="h-12 w-12 mx-auto mb-4 text-primary" />
|
||||
<h3 className="text-xl font-semibold mb-2">安全可靠</h3>
|
||||
<p className="text-muted-foreground">
|
||||
基于 OAuth 2.0 的企业级认证,支持多因素认证
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-6 text-center">
|
||||
<Zap className="h-12 w-12 mx-auto mb-4 text-primary" />
|
||||
<h3 className="text-xl font-semibold mb-2">快速部署</h3>
|
||||
<p className="text-muted-foreground">
|
||||
Docker 一键部署,开箱即用,降低运维成本
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-6 text-center">
|
||||
<Users className="h-12 w-12 mx-auto mb-4 text-primary" />
|
||||
<h3 className="text-xl font-semibold mb-2">易于扩展</h3>
|
||||
<p className="text-muted-foreground">
|
||||
模块化架构设计,支持自定义业务逻辑和第三方集成
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import Link from 'next/link';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { getLoginUrl } from '@/lib/api';
|
||||
import { LogOut, User } from 'lucide-react';
|
||||
import * as Avatar from '@radix-ui/react-avatar';
|
||||
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
|
||||
|
||||
export default function Header() {
|
||||
const { user, isAuthenticated, logout } = useAuthStore();
|
||||
|
||||
const handleLogin = async () => {
|
||||
try {
|
||||
const loginUrl = await getLoginUrl();
|
||||
window.location.href = loginUrl;
|
||||
} catch (error) {
|
||||
console.error('Failed to get login URL:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
window.location.href = '/';
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<div className="container flex h-16 items-center justify-between px-4">
|
||||
<Link href="/" className="text-xl font-bold">
|
||||
IMTIM Portal
|
||||
</Link>
|
||||
|
||||
<nav className="flex items-center gap-4">
|
||||
{isAuthenticated && user ? (
|
||||
<DropdownMenu.Root>
|
||||
<DropdownMenu.Trigger asChild>
|
||||
<button className="flex items-center gap-2 rounded-full hover:bg-accent p-1">
|
||||
<Avatar.Root className="h-8 w-8 rounded-full bg-secondary flex items-center justify-center overflow-hidden">
|
||||
{user.avatar ? (
|
||||
<Avatar.Image
|
||||
src={user.avatar}
|
||||
alt={user.username}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<Avatar.Fallback className="text-lg">
|
||||
<User className="h-4 w-4" />
|
||||
</Avatar.Fallback>
|
||||
)}
|
||||
</Avatar.Root>
|
||||
<span className="text-sm font-medium">{user.username}</span>
|
||||
</button>
|
||||
</DropdownMenu.Trigger>
|
||||
|
||||
<DropdownMenu.Portal>
|
||||
<DropdownMenu.Content
|
||||
className="min-w-[220px] bg-popover rounded-md p-1 shadow-md border"
|
||||
sideOffset={5}
|
||||
>
|
||||
<DropdownMenu.Item className="flex items-center gap-2 px-3 py-2 text-sm rounded cursor-pointer hover:bg-accent outline-none">
|
||||
<User className="h-4 w-4" />
|
||||
<span>个人资料</span>
|
||||
</DropdownMenu.Item>
|
||||
|
||||
<DropdownMenu.Separator className="h-px bg-border my-1" />
|
||||
|
||||
<DropdownMenu.Item
|
||||
className="flex items-center gap-2 px-3 py-2 text-sm rounded cursor-pointer hover:bg-accent text-red-600 outline-none"
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
<span>退出登录</span>
|
||||
</DropdownMenu.Item>
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Portal>
|
||||
</DropdownMenu.Root>
|
||||
) : (
|
||||
<button
|
||||
onClick={handleLogin}
|
||||
className="px-4 py-2 text-sm font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
登录
|
||||
</button>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import Header from '@/components/header';
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<Header />
|
||||
<main className="flex-1">{children}</main>
|
||||
<footer className="border-t py-6">
|
||||
<div className="container px-4 text-center text-sm text-muted-foreground">
|
||||
© 2026 IMTIM Portal. All rights reserved.
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
|
||||
export default function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { isAuthenticated, initialize } = useAuthStore();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
initialize();
|
||||
}, [initialize]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
router.push('/login');
|
||||
}
|
||||
}, [isAuthenticated, router]);
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[200px]">
|
||||
<div className="text-muted-foreground">加载中...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: API_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// 请求拦截器 - 自动添加token
|
||||
api.interceptors.request.use((config) => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// 获取登录URL
|
||||
export const getLoginUrl = async () => {
|
||||
const response = await api.post('/auth/login');
|
||||
return response.data.data.loginUrl;
|
||||
};
|
||||
|
||||
// 获取用户信息
|
||||
export const getUserInfo = async () => {
|
||||
const response = await api.get('/auth/user');
|
||||
return response.data.data;
|
||||
};
|
||||
|
||||
// 登出
|
||||
export const logout = async () => {
|
||||
const response = await api.post('/auth/logout');
|
||||
return response.data;
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
'use client';
|
||||
|
||||
import { create } from 'zustand';
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
email?: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
token: string | null;
|
||||
isAuthenticated: boolean;
|
||||
login: (token: string, user: User) => void;
|
||||
logout: () => void;
|
||||
initialize: () => void;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>((set) => ({
|
||||
user: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
|
||||
login: (token, user) => {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('token', token);
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
}
|
||||
set({ user, token, isAuthenticated: true });
|
||||
},
|
||||
|
||||
logout: () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
set({ user: null, token: null, isAuthenticated: false });
|
||||
},
|
||||
|
||||
initialize: () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const token = localStorage.getItem('token');
|
||||
const userStr = localStorage.getItem('user');
|
||||
if (token && userStr) {
|
||||
set({
|
||||
token,
|
||||
user: JSON.parse(userStr),
|
||||
isAuthenticated: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user