From 6e95554e0c04d5fa90eb6ce7e6e1d4b2069178eb Mon Sep 17 00:00:00 2001 From: longdayi <13477510+longdayilongdayi@user.noreply.gitee.com> Date: Tue, 10 Sep 2024 11:23:02 +0800 Subject: [PATCH] 09101122 --- apps/server/src/app.module.ts | 7 +++- apps/server/src/auth/auth.controller.ts | 2 - apps/server/src/auth/auth.guard.ts | 6 +-- apps/server/src/auth/auth.module.ts | 5 --- apps/server/src/trpc/trpc.service.spec.ts | 18 --------- apps/server/src/trpc/trpc.service.ts | 11 +++--- apps/web/src/App.tsx | 5 ++- apps/web/src/app/login.tsx | 45 +++++++++-------------- apps/web/src/app/main/page.tsx | 5 ++- apps/web/src/providers/auth-provider.tsx | 24 ++++++++++++ 10 files changed, 65 insertions(+), 63 deletions(-) delete mode 100644 apps/server/src/trpc/trpc.service.spec.ts diff --git a/apps/server/src/app.module.ts b/apps/server/src/app.module.ts index 0204d1b..0212e07 100644 --- a/apps/server/src/app.module.ts +++ b/apps/server/src/app.module.ts @@ -10,9 +10,14 @@ import { AuthModule } from './auth/auth.module'; import { ScheduleModule } from '@nestjs/schedule'; import { ConfigService } from '@nestjs/config'; import { TasksModule } from './tasks/tasks.module'; +import { JwtModule } from '@nestjs/jwt'; +import { env } from './env'; @Module({ - imports: [ScheduleModule.forRoot(), TrpcModule, RedisModule, QueueModule, TransformModule, AuthModule, TasksModule], + imports: [ScheduleModule.forRoot(), JwtModule.register({ + global: true, + secret: env.JWT_SECRET + }), TrpcModule, RedisModule, QueueModule, TransformModule, AuthModule, TasksModule], providers: [RedisService, SocketGateway, ConfigService], }) export class AppModule { } diff --git a/apps/server/src/auth/auth.controller.ts b/apps/server/src/auth/auth.controller.ts index 00eaf3c..99270e7 100644 --- a/apps/server/src/auth/auth.controller.ts +++ b/apps/server/src/auth/auth.controller.ts @@ -12,8 +12,6 @@ export class AuthController { @Get("user-profile") async getUserProfile(@Req() request: Request) { const user: JwtPayload = (request as any).user - console.log(user) - // console.log(request) return this.authService.getUserProfile(user) } @Post('login') diff --git a/apps/server/src/auth/auth.guard.ts b/apps/server/src/auth/auth.guard.ts index def8472..d0cd66d 100644 --- a/apps/server/src/auth/auth.guard.ts +++ b/apps/server/src/auth/auth.guard.ts @@ -15,7 +15,7 @@ export class AuthGuard implements CanActivate { async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const token = this.extractTokenFromHeader(request); - console.log(token) + if (!token) { throw new UnauthorizedException(); } @@ -26,7 +26,7 @@ export class AuthGuard implements CanActivate { secret: env.JWT_SECRET } ); - + // 💡 We're assigning the payload to the request object here // so that we can access it in our route handlers request['user'] = payload; @@ -36,7 +36,7 @@ export class AuthGuard implements CanActivate { return true; } - private extractTokenFromHeader(request: Request): string | undefined { + extractTokenFromHeader(request: Request): string | undefined { const [type, token] = request.headers.authorization?.split(' ') ?? []; return type === 'Bearer' ? token : undefined; } diff --git a/apps/server/src/auth/auth.module.ts b/apps/server/src/auth/auth.module.ts index a4f7c4f..5982550 100644 --- a/apps/server/src/auth/auth.module.ts +++ b/apps/server/src/auth/auth.module.ts @@ -9,11 +9,6 @@ import { DepartmentService } from '@server/models/department/department.service' @Module({ providers: [AuthService, StaffService, RoleMapService, DepartmentService], - imports: [JwtModule.register({ - global: true, - secret: env.JWT_SECRET, - signOptions: { expiresIn: '60s' }, - }),], controllers: [AuthController], exports: [AuthService] }) diff --git a/apps/server/src/trpc/trpc.service.spec.ts b/apps/server/src/trpc/trpc.service.spec.ts deleted file mode 100644 index 16bfcf0..0000000 --- a/apps/server/src/trpc/trpc.service.spec.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { TrpcService } from './trpc.service'; - -describe('TrpcService', () => { - let service: TrpcService; - - beforeEach(async () => { - const module: TestingModule = await Test.createTestingModule({ - providers: [TrpcService], - }).compile(); - - service = module.get(TrpcService); - }); - - it('should be defined', () => { - expect(service).toBeDefined(); - }); -}); diff --git a/apps/server/src/trpc/trpc.service.ts b/apps/server/src/trpc/trpc.service.ts index b6195b7..137bf10 100644 --- a/apps/server/src/trpc/trpc.service.ts +++ b/apps/server/src/trpc/trpc.service.ts @@ -1,4 +1,4 @@ -import { Injectable } from '@nestjs/common'; +import { Injectable, Logger } from '@nestjs/common'; import { initTRPC, TRPCError } from '@trpc/server'; import superjson from 'superjson-cjs'; import * as trpcExpress from '@trpc/server/adapters/express'; @@ -9,7 +9,7 @@ import { JwtService } from '@nestjs/jwt'; type Context = Awaited>; @Injectable() export class TrpcService { - constructor(private readonly jwtService: JwtService) { } + async createContext({ req, res, @@ -17,10 +17,11 @@ export class TrpcService { const token = req.headers.authorization?.split(' ')[1]; let tokenData: JwtPayload | undefined = undefined; let staff: Staff | undefined = undefined; + console.log(token) if (token) { try { - // Verify JWT token and extract tokenData - tokenData = await this.jwtService.verifyAsync(token, { secret: env.JWT_SECRET }) as JwtPayload; + const jwtService = new JwtService() + tokenData = await jwtService.verifyAsync(token, { secret: env.JWT_SECRET }) as JwtPayload; if (tokenData) { // Fetch staff details from the database using tokenData.id staff = await db.staff.findUnique({ where: { id: tokenData.sub } }); @@ -35,7 +36,7 @@ export class TrpcService { } return { - staff, + staff }; }; trpc = initTRPC.context().create({ diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 0b2a473..61b094f 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -6,13 +6,16 @@ import QueryProvider from './providers/query-provider' import { router } from './routes'; import { AuthProvider } from './providers/auth-provider'; import ThemeProvider from './providers/theme-provider'; +import { App as AntdApp } from 'antd'; function App() { return ( - + + + diff --git a/apps/web/src/app/login.tsx b/apps/web/src/app/login.tsx index bf3560d..704781e 100644 --- a/apps/web/src/app/login.tsx +++ b/apps/web/src/app/login.tsx @@ -8,29 +8,28 @@ import SineWave from '../components/presentation/animation/sine-wave'; const LoginPage: React.FC = () => { const [showLogin, setShowLogin] = useState(true); const [registerLoading, setRegisterLoading] = useState(false); - const { login, isAuthenticated } = useAuth(); + const { login, isAuthenticated, signup } = useAuth(); const loginFormRef = useRef(null); const registerFormRef = useRef(null); const location = useLocation(); - const navigate = useNavigate() + const navigate = useNavigate(); + const onFinishLogin = async (values: any) => { try { const { username, password } = values; await login(username, password); message.success('登录成功!'); } catch (err) { - message.warning('用户名或密码错误!'); + message.error('用户名或密码错误!'); console.error(err); } }; const onFinishRegister = async (values: any) => { setRegisterLoading(true); + const { username, password, phoneNumber } = values; try { - // await wp.RegisterUser().create({ - // ...values, - // custom_data: { org_unit: values.org_unit }, - // }); + await signup(username, password, phoneNumber); message.success('注册成功!'); setShowLogin(true); loginFormRef.current.submit(); @@ -51,13 +50,10 @@ const LoginPage: React.FC = () => { return (
-
+
{showLogin ? ( <> - - 返回首页 -
登录
@@ -77,33 +73,28 @@ const LoginPage: React.FC = () => { ) : ( - <> -
setShowLogin(true)} - className="text-sm text-gray-400 hover:cursor-pointer hover:text-primary" - > - 返回登录 -
+
+
注册
- + - - - + + - - + - ({ @@ -115,7 +106,7 @@ const LoginPage: React.FC = () => { } }) ]}> - +
@@ -124,7 +115,7 @@ const LoginPage: React.FC = () => {
- +
)}
diff --git a/apps/web/src/app/main/page.tsx b/apps/web/src/app/main/page.tsx index 81a0c87..e0ad288 100644 --- a/apps/web/src/app/main/page.tsx +++ b/apps/web/src/app/main/page.tsx @@ -1,3 +1,6 @@ +import { useAuth } from "@web/src/providers/auth-provider" + export default function MainPage() { - return <>hello,world + const { user } = useAuth() + return <>hello,{user?.username} } diff --git a/apps/web/src/providers/auth-provider.tsx b/apps/web/src/providers/auth-provider.tsx index 08a21d5..a548566 100644 --- a/apps/web/src/providers/auth-provider.tsx +++ b/apps/web/src/providers/auth-provider.tsx @@ -10,6 +10,7 @@ interface AuthContextProps { user: UserProfile | null; login: (username: string, password: string) => Promise; logout: () => Promise; + signup: (username: string, password: string, phoneNumber?: string) => Promise; refreshAccessToken: () => Promise; initializeAuth: () => void; startTokenRefreshInterval: () => void; @@ -102,6 +103,28 @@ export function AuthProvider({ children }: AuthProviderProps) { } }; + const signup = async (username: string, password: string, phoneNumber?: string): Promise => { + try { + setIsLoading(true); + const response = await apiClient.post(`/auth/signup`, { username, password, phoneNumber }); + // const { access_token, refresh_token, access_token_expires_at, refresh_token_expires_at } = response.data; + // localStorage.setItem('access_token', access_token); + // localStorage.setItem('refresh_token', refresh_token); + // localStorage.setItem('access_token_expires_at', access_token_expires_at); + // localStorage.setItem('refresh_token_expires_at', refresh_token_expires_at); + // setAccessToken(access_token); + // setRefreshToken(refresh_token); + // setIsAuthenticated(true); + // startTokenRefreshInterval(); + // fetchUserProfile(); + } catch (err) { + console.error("Signup failed", err); + throw new Error("Signup failed"); + } finally { + setIsLoading(false); + } + }; + const logout = async (): Promise => { try { setIsLoading(true); @@ -154,6 +177,7 @@ export function AuthProvider({ children }: AuthProviderProps) { user, login, logout, + signup, refreshAccessToken, initializeAuth, startTokenRefreshInterval,