36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
import { Body, Controller, Post } from '@nestjs/common';
|
|
import { z } from 'zod';
|
|
import { CurrentUser, Public, type AuthPrincipal } from '../../common/auth';
|
|
import { AppError } from '../../common/errors';
|
|
import { AuthService, type LoginResult } from './auth.service';
|
|
|
|
const loginSchema = z.object({ code: z.string().min(1) });
|
|
const refreshSchema = z.object({ refreshToken: z.string().min(1) });
|
|
|
|
@Controller('v1/auth')
|
|
export class AuthController {
|
|
constructor(private readonly auth: AuthService) {}
|
|
|
|
@Public()
|
|
@Post('wx-login')
|
|
async wxLogin(@Body() body: unknown): Promise<LoginResult> {
|
|
const parsed = loginSchema.safeParse(body);
|
|
if (!parsed.success) throw AppError.badRequest('参数错误:缺少 code');
|
|
return this.auth.loginWithCode(parsed.data.code);
|
|
}
|
|
|
|
@Public()
|
|
@Post('refresh')
|
|
refresh(@Body() body: unknown): Promise<{ accessToken: string }> {
|
|
const parsed = refreshSchema.safeParse(body);
|
|
if (!parsed.success) throw AppError.badRequest('参数错误:缺少 refreshToken');
|
|
return this.auth.refresh(parsed.data.refreshToken);
|
|
}
|
|
|
|
@Post('logout')
|
|
logout(@CurrentUser() user: AuthPrincipal): Promise<null> {
|
|
return this.auth.logOut(user.id);
|
|
}
|
|
}
|
|
|