File size: 10,917 Bytes
a38b26a
 
 
 
 
 
 
 
 
 
e6677f0
 
 
 
 
 
 
a38b26a
 
 
 
 
 
 
 
 
 
 
 
 
e6677f0
a38b26a
 
 
 
 
 
 
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
771a441
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
771a441
e6677f0
 
 
 
 
 
 
771a441
e6677f0
 
 
 
 
 
 
 
 
a38b26a
 
 
 
 
 
 
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
771a441
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
771a441
a38b26a
 
 
 
 
 
 
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a38b26a
 
 
 
 
 
 
 
 
 
 
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a38b26a
 
 
 
 
 
 
 
 
 
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a38b26a
 
 
 
 
 
 
 
 
 
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a38b26a
 
 
 
 
 
 
 
 
 
e6677f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a38b26a
 
 
 
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import {
  Controller,
  Post,
  Get,
  Body,
  UseGuards,
  Req,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiBody,
} from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { RegisterRequestDto } from './dto/register-request.dto';
import { LoginRequestDto } from './dto/login-request.dto';
import {
  ForgotPasswordRequestDto,
  ResetPasswordRequestDto,
  TokenRefreshRequestDto,
} from './dto/other-dtos';
import { Public } from '../../common/decorators/public.decorator';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { User } from './entities/user.entity';

@ApiTags('๐Ÿ” Authentication')
@Controller('api/auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Public()
  @Post('register')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({
    summary: 'Register a new user',
    description: `
## Register New User Account

Creates a new user account in the EduVerse system.

### Access Control
- **Authentication Required**: No (Public endpoint)
- **Roles Required**: None

### Process Flow
1. Validates email format and password strength
2. Checks for existing user with same email
3. Creates user with default STUDENT role (unless specified)
4. Returns user data

### Password Requirements
- Minimum 8 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one number
- At least one special character (@$!%*?&)

### Notes
- Default role is STUDENT if not specified
    `,
  })
  @ApiBody({ type: RegisterRequestDto })
  @ApiResponse({
    status: 201,
    description: 'User successfully registered.',
    schema: {
      example: {
        user: {
          userId: 1,
          email: 'user@example.com',
          firstName: 'John',
          lastName: 'Doe',
          isEmailVerified: true,
          roles: [{ roleName: 'student' }],
        },
        accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
        refreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
      },
    },
  })
  @ApiResponse({ status: 400, description: 'Invalid input data or password requirements not met' })
  @ApiResponse({ status: 409, description: 'User with this email already exists' })
  async register(@Body() registerDto: RegisterRequestDto, @Req() request: any) {
    return this.authService.register(registerDto, request);
  }

  @Public()
  @Post('login')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'User login',
    description: `
## User Authentication

Authenticates a user and returns JWT tokens for API access.

### Access Control
- **Authentication Required**: No (Public endpoint)
- **Roles Required**: None

### Process Flow
1. Validates email and password credentials
2. Checks if user account is active
3. Creates a new session for the user
4. Returns access token (short-lived) and refresh token (long-lived)

### Token Usage
- **Access Token**: Include in Authorization header as \`Bearer <token>\`
- **Refresh Token**: Use with \`/api/auth/refresh-token\` to get new access token
- Access token expires in 15 minutes (default)
- Refresh token expires in 7 days (or 30 days with rememberMe)

### Remember Me Option
When \`rememberMe: true\`, the refresh token will have extended validity.
    `,
  })
  @ApiBody({ type: LoginRequestDto })
  @ApiResponse({
    status: 200,
    description: 'Login successful. Returns JWT tokens.',
    schema: {
      example: {
        user: {
          userId: 1,
          email: 'user@example.com',
          firstName: 'John',
          lastName: 'Doe',
          roles: [{ roleName: 'student' }],
        },
        accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
        refreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
        expiresIn: 900,
      },
    },
  })
  @ApiResponse({ status: 400, description: 'Invalid credentials' })
  @ApiResponse({ status: 401, description: 'Account disabled' })
  async login(@Body() loginDto: LoginRequestDto, @Req() request: any) {
    return this.authService.login(loginDto, request);
  }

  @Post('logout')
  @HttpCode(HttpStatus.OK)
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({
    summary: 'User logout',
    description: `
## Logout Current Session

Invalidates the current user session and refresh token.

### Access Control
- **Authentication Required**: โœ… Yes (Bearer Token)
- **Roles Required**: Any authenticated user

### Process Flow
1. Validates the JWT access token
2. Invalidates the provided refresh token
3. Ends the current session

### Notes
- The access token will remain valid until expiration
- Client should discard both tokens after logout
- For immediate token invalidation, implement token blacklisting
    `,
  })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        refreshToken: {
          type: 'string',
          description: 'The refresh token to invalidate',
          example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
        },
      },
      required: ['refreshToken'],
    },
  })
  @ApiResponse({ status: 200, description: 'Successfully logged out' })
  @ApiResponse({ status: 401, description: 'Unauthorized - Invalid or expired token' })
  async logout(
    @CurrentUser() user: User,
    @Body('refreshToken') refreshToken: string,
  ) {
    await this.authService.logout(user.userId, refreshToken);
    return { message: 'Logged out successfully' };
  }

  @Public()
  @Post('refresh-token')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Refresh access token',
    description: `
## Refresh JWT Access Token

Generates a new access token using a valid refresh token.

### Access Control
- **Authentication Required**: No (Uses refresh token instead)
- **Roles Required**: None

### Process Flow
1. Validates the refresh token
2. Checks if the session is still valid
3. Generates a new access token
4. Optionally rotates the refresh token

### Usage
Call this endpoint when the access token expires (typically after 15 minutes).
The refresh token has a longer validity period (7-30 days).

### Security Notes
- Refresh tokens should be stored securely (httpOnly cookies recommended)
- Each refresh token can only be used once (token rotation)
    `,
  })
  @ApiBody({ type: TokenRefreshRequestDto })
  @ApiResponse({
    status: 200,
    description: 'New access token generated',
    schema: {
      example: {
        accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
        refreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
        expiresIn: 900,
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Invalid or expired refresh token' })
  async refreshToken(
    @Body() tokenRefreshDto: TokenRefreshRequestDto,
    @Req() request: any,
  ) {
    return this.authService.refreshToken(tokenRefreshDto.refreshToken, request);
  }

  @Public()
  @Post('forgot-password')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Request password reset',
    description: `
## Request Password Reset Email

Sends a password reset link to the user's email address.

### Access Control
- **Authentication Required**: No (Public endpoint)
- **Roles Required**: None

### Process Flow
1. Validates the email format
2. Checks if user exists (silently fails if not for security)
3. Generates a secure password reset token
4. Sends reset link via email

### Security Notes
- Always returns success message regardless of email existence
- Reset token expires after 1 hour
- Previous reset tokens are invalidated
    `,
  })
  @ApiBody({ type: ForgotPasswordRequestDto })
  @ApiResponse({
    status: 200,
    description: 'Password reset email sent (if user exists)',
    schema: {
      example: {
        message: 'If the email exists, a password reset link has been sent',
      },
    },
  })
  @ApiResponse({ status: 400, description: 'Invalid email format' })
  async forgotPassword(@Body() forgotPasswordDto: ForgotPasswordRequestDto) {
    await this.authService.forgotPassword(forgotPasswordDto.email);
    return {
      message: 'If the email exists, a password reset link has been sent',
    };
  }

  @Public()
  @Post('reset-password')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Reset password with token',
    description: `
## Reset User Password

Resets the user's password using a valid reset token from email.

### Access Control
- **Authentication Required**: No (Uses reset token)
- **Roles Required**: None

### Process Flow
1. Validates the reset token
2. Verifies token hasn't expired
3. Validates new password meets requirements
4. Updates user password (hashed)
5. Invalidates all existing sessions

### Password Requirements
- Minimum 8 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one number
- At least one special character (@$!%*?&)
    `,
  })
  @ApiBody({ type: ResetPasswordRequestDto })
  @ApiResponse({
    status: 200,
    description: 'Password reset successful',
    schema: {
      example: { message: 'Password reset successfully' },
    },
  })
  @ApiResponse({ status: 400, description: 'Invalid or expired reset token' })
  async resetPassword(@Body() resetPasswordDto: ResetPasswordRequestDto) {
    await this.authService.resetPassword(
      resetPasswordDto.token,
      resetPasswordDto.newPassword,
    );
    return { message: 'Password reset successfully' };
  }

  @Get('me')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({
    summary: 'Get current user profile',
    description: `
## Get Authenticated User Profile

Returns the complete profile of the currently authenticated user.

### Access Control
- **Authentication Required**: โœ… Yes (Bearer Token)
- **Roles Required**: Any authenticated user (STUDENT, INSTRUCTOR, TA, ADMIN, IT_ADMIN)

### Response Includes
- User basic information (name, email, phone)
- Assigned roles and permissions
- Account status and verification state
- Campus association (if applicable)

### Usage
Use this endpoint to:
- Display user profile information
- Check user permissions
- Verify authentication status
    `,
  })
  @ApiResponse({
    status: 200,
    description: 'Current user profile',
    schema: {
      example: {
        userId: 1,
        email: 'user@example.com',
        firstName: 'John',
        lastName: 'Doe',
        phone: '+1234567890',
        isEmailVerified: true,
        status: 'active',
        roles: [
          { roleId: 1, roleName: 'student', roleDescription: 'Regular student user' },
        ],
        createdAt: '2024-01-15T10:30:00Z',
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized - Invalid or expired token' })
  async getCurrentUser(@CurrentUser() user: User) {
    return this.authService.getCurrentUser(user.userId);
  }
}