-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathauth.controller.ts
More file actions
239 lines (207 loc) · 6.74 KB
/
auth.controller.ts
File metadata and controls
239 lines (207 loc) · 6.74 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import { AuthGuard } from '@nestjs/passport';
import { Response } from 'express';
import { ApiTags, ApiExcludeController } from '@nestjs/swagger';
import {
Body,
ClassSerializerInterceptor,
Controller,
Get,
Logger,
Post,
Put,
Res,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { constructQueryString, IJwtPayload, UserRolesEnum } from '@impler/shared';
import { AuthService } from './services/auth.service';
import { IStrategyResponse } from '@shared/types/auth.types';
import { CONSTANTS, COOKIE_CONFIG } from '@shared/constants';
import { UserSession } from '@shared/framework/user.decorator';
import { ApiException } from '@shared/exceptions/api.exception';
import { StrategyUser } from './decorators/strategy-user.decorator';
import {
RegisterUserDto,
LoginUserDto,
RequestForgotPasswordDto,
ResetPasswordDto,
OnboardUserDto,
VerifyDto,
UpdateUserDto,
} from './dtos';
import {
Verify,
LoginUser,
ResendOTP,
UpdateUser,
OnboardUser,
RegisterUser,
ResetPassword,
ResetPasswordCommand,
RequestForgotPassword,
RequestForgotPasswordCommand,
} from './usecases';
@ApiTags('Auth')
@Controller('/auth')
@ApiExcludeController()
@UseInterceptors(ClassSerializerInterceptor)
export class AuthController {
private readonly logger = new Logger(AuthController.name);
constructor(
private verify: Verify,
private resendOTP: ResendOTP,
private loginUser: LoginUser,
private updateUser: UpdateUser,
private onboardUser: OnboardUser,
private authService: AuthService,
private registerUser: RegisterUser,
private resetPassword: ResetPassword,
private requestForgotPassword: RequestForgotPassword
) {}
@Get('/github')
githubAuth() {
if (!process.env.GITHUB_OAUTH_CLIENT_ID || !process.env.GITHUB_OAUTH_CLIENT_SECRET) {
throw new ApiException(
'GitHub auth is not configured, please provide GITHUB_OAUTH_CLIENT_ID and GITHUB_OAUTH_CLIENT_SECRET as env variables'
);
}
return {
success: true,
};
}
@Get('/github/callback')
@UseGuards(AuthGuard('github'))
async githubCallback(
@Res({ passthrough: true }) response: Response,
@StrategyUser() strategyUser: IStrategyResponse
) {
try {
if (!strategyUser || !strategyUser.token) {
return response.redirect(`${process.env.WEB_BASE_URL}/auth/signin?error=AuthenticationError`);
}
let url = process.env.WEB_BASE_URL + '/auth/signin';
const queryObj: Record<string, any> = {
token: strategyUser.token,
};
if (strategyUser.showAddProject) {
queryObj.showAddProject = true;
}
url += constructQueryString(queryObj);
response.cookie(CONSTANTS.AUTH_COOKIE_NAME, strategyUser.token, {
...COOKIE_CONFIG,
domain: process.env.COOKIE_DOMAIN,
});
return response.redirect(url);
} catch (error) {
this.logger.error(`GitHub OAuth callback failed: ${error?.message || error}`);
return response.redirect(`${process.env.WEB_BASE_URL}/auth/signin?error=AuthenticationError`);
}
}
@Get('/me')
async user(@UserSession() user: IJwtPayload) {
return user;
}
@Put('/me')
async updateUserRoute(@UserSession() user: IJwtPayload, @Body() body: UpdateUserDto, @Res() response: Response) {
const { success, token } = await this.updateUser.execute(user._id, body);
if (token)
response.cookie(CONSTANTS.AUTH_COOKIE_NAME, token, {
...COOKIE_CONFIG,
domain: process.env.COOKIE_DOMAIN,
});
response.send({ success });
}
@Get('/logout')
logout(@Res() response: Response) {
response.clearCookie(CONSTANTS.AUTH_COOKIE_NAME, {
httpOnly: true,
secure: true,
sameSite: 'none',
domain: process.env.COOKIE_DOMAIN,
});
response.contentType('text').send();
}
@Post('/register')
async register(@Body() body: RegisterUserDto, @Res() response: Response) {
const registeredUser = await this.registerUser.execute(body);
response.cookie(CONSTANTS.AUTH_COOKIE_NAME, registeredUser.token, {
...COOKIE_CONFIG,
domain: process.env.COOKIE_DOMAIN,
});
response.send(registeredUser);
}
@Post('/verify')
async verifyRoute(@Body() body: VerifyDto, @UserSession() user: IJwtPayload, @Res() response: Response) {
const { token, screen } = await this.verify.execute(user._id, { code: body.otp });
response.cookie(CONSTANTS.AUTH_COOKIE_NAME, token, {
...COOKIE_CONFIG,
domain: process.env.COOKIE_DOMAIN,
});
response.send({ screen });
}
@Post('/onboard')
async onboardUserRoute(
@Body() body: OnboardUserDto,
@UserSession() user: IJwtPayload,
@Res({ passthrough: true }) res: Response
) {
const projectWithEnvironment = await this.onboardUser.execute({
_userId: user._id,
projectName: body.projectName,
role: body.role,
companySize: body.companySize,
source: body.source,
});
const userApiKey = projectWithEnvironment.environment.apiKeys.find(
(apiKey) => apiKey._userId.toString() === user._id
);
const token = this.authService.getSignedToken(
{
_id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
role: userApiKey.role as UserRolesEnum,
profilePicture: user.profilePicture,
isEmailVerified: user.isEmailVerified,
accessToken: projectWithEnvironment.environment.key,
},
projectWithEnvironment.project._id
);
res.cookie(CONSTANTS.AUTH_COOKIE_NAME, token, {
...COOKIE_CONFIG,
domain: process.env.COOKIE_DOMAIN,
});
return projectWithEnvironment;
}
@Post('/login')
async login(@Body() body: LoginUserDto, @Res() response: Response) {
const loginUser = await this.loginUser.execute({
email: body.email,
password: body.password,
invitationId: body.invitationId,
});
response.cookie(CONSTANTS.AUTH_COOKIE_NAME, loginUser.token, {
...COOKIE_CONFIG,
domain: process.env.COOKIE_DOMAIN,
});
response.send(loginUser);
}
@Post('/forgot-password/request')
async requestForgotPasswordRoute(@Body() body: RequestForgotPasswordDto) {
return this.requestForgotPassword.execute(RequestForgotPasswordCommand.create(body));
}
@Post('/forgot-password/reset')
async resetPasswordRoute(@Body() body: ResetPasswordDto, @Res() response: Response) {
const resetPassword = await this.resetPassword.execute(ResetPasswordCommand.create(body));
response.cookie(CONSTANTS.AUTH_COOKIE_NAME, resetPassword.token, {
...COOKIE_CONFIG,
domain: process.env.COOKIE_DOMAIN,
});
response.send(resetPassword);
}
@Post('verify/resend')
async resendOTPRoute(@UserSession() user: IJwtPayload) {
return await this.resendOTP.execute(user._id);
}
}