-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.controller.ts
More file actions
188 lines (170 loc) · 5.54 KB
/
auth.controller.ts
File metadata and controls
188 lines (170 loc) · 5.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import {
BadRequestException,
Body,
Controller,
ForbiddenException,
Get,
Post,
Req,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { CurrentUserInterceptor } from '../interceptors/current-user.interceptor';
import { Status } from '../users/types';
import { SignInDto } from './dtos/sign-in.dto';
import { SignUpDto } from './dtos/sign-up.dto';
import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service';
import { VerifyUserDto } from './dtos/verify-user.dto';
import { DeleteUserDto } from './dtos/delete-user.dto';
import { User } from '../users/user.entity';
import { SignInResponseDto } from './dtos/sign-in-response.dto';
import { RefreshTokenDto } from './dtos/refresh-token.dto';
import { ConfirmPasswordDto } from './dtos/confirm-password.dto';
import { ForgotPasswordDto } from './dtos/forgot-password.dto';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('Auth')
@Controller('auth')
export class AuthController {
constructor(
private authService: AuthService,
private usersService: UsersService,
) {}
@Get('/me')
@UseGuards(AuthGuard('jwt'))
@UseInterceptors(CurrentUserInterceptor)
async me(@Req() req: any) {
return req.user;
}
@Post('/admin-verify')
@UseGuards(AuthGuard('jwt'))
@UseInterceptors(CurrentUserInterceptor)
async adminVerify(
@Req() req: any,
@Body() body: { email: string },
): Promise<void> {
if (req.user.status !== Status.ADMIN) {
throw new ForbiddenException('Only admins can verify users');
}
try {
await this.authService.adminConfirmUser(body.email);
} catch (e) {
console.error('Admin verify error:', e);
throw new BadRequestException(e.message);
}
}
@Get('/users')
@UseGuards(AuthGuard('jwt'))
@UseInterceptors(CurrentUserInterceptor)
async listUsers(@Req() req: any) {
try {
const cognitoUsers = await this.authService.listAllUsers();
// Combine with DB users
const results = await Promise.all(
cognitoUsers.map(async (cu) => {
const email = cu.Attributes.find((a) => a.Name === 'email')?.Value;
const dbUsers = email ? await this.usersService.find(email) : [];
return {
username: cu.Username,
status: cu.UserStatus, // UNCONFIRMED, CONFIRMED, etc.
email,
dbUser: dbUsers[0] || null,
};
}),
);
return results;
} catch (e) {
throw new BadRequestException(e.message);
}
}
@Post('/signup')
async createUser(@Body() signUpDto: SignUpDto): Promise<User> {
console.log(`Signup request received for: ${signUpDto.email}`);
// By default, creates a standard user
try {
await this.authService.signup(signUpDto);
} catch (e) {
console.error('Signup error:', e);
throw new BadRequestException(e.message);
}
const user = await this.usersService.create(
signUpDto.email,
signUpDto.firstName,
signUpDto.lastName,
);
return user;
}
// TODO deprecated if verification code is replaced by link
@Post('/verify')
verifyUser(@Body() body: VerifyUserDto): void {
try {
this.authService.verifyUser(body.email, body.verificationCode);
} catch (e) {
console.error('Verify error:', e);
throw new BadRequestException(e.message);
}
}
@Post('/signin')
async signin(@Body() signInDto: SignInDto): Promise<SignInResponseDto> {
console.log(`Signin request received for: ${signInDto.email}`);
try {
return await this.authService.signin(signInDto);
} catch (e) {
throw new BadRequestException(e.message);
}
}
@Post('/refresh')
refresh(@Body() refreshDto: RefreshTokenDto): Promise<SignInResponseDto> {
return this.authService.refreshToken(refreshDto);
}
@Post('/forgotPassword')
async forgotPassword(@Body() body: ForgotPasswordDto): Promise<void> {
const registeredUsers = await this.usersService.find(body.email);
if (!registeredUsers.length) {
throw new BadRequestException('Account is not registered.');
}
try {
await this.authService.forgotPassword(body.email);
} catch (e) {
console.error('Forgot password error:', e);
throw new BadRequestException(e.message);
}
}
@Post('/confirmPassword')
async confirmPassword(@Body() body: ConfirmPasswordDto): Promise<void> {
try {
await this.authService.confirmForgotPassword(body);
} catch (e) {
console.error('Confirm password error:', e);
// Map Cognito errors to user-friendly messages
if (e instanceof Error) {
const errName = (e as any).name || '';
if (
errName === 'InvalidVerificationCodeException' ||
errName === 'CodeMismatchException'
) {
throw new BadRequestException('Confirmation code is incorrect');
}
if (errName === 'UserNotFoundException') {
throw new BadRequestException('User not found');
}
if (errName === 'ExpiredCodeException') {
throw new BadRequestException('Confirmation code has expired');
}
}
throw new BadRequestException(e.message || 'Failed to reset password');
}
}
@Post('/delete')
async delete(@Body() body: DeleteUserDto): Promise<void> {
const user = await this.usersService.findOne(body.userId);
try {
await this.authService.deleteUser(user.email);
} catch (e) {
console.error('Delete error:', e);
throw new BadRequestException(e.message);
}
this.usersService.remove(user.id);
}
}