import { Controller, Post, Body, UseGuards, Get, Request, Put, Param, HttpException, HttpStatus, Delete } from "@nestjs/common"; import { UsersService } from "./users.service"; import { User } from "./entities/user.entity"; import { CreateUserDto } from "./dto/create-user.dto"; import { LoginUserDto } from "./dto/login-user.dto"; import { JwtAuthGuard } from "src/guard/auth.guard"; import { UpdateUserDto } from "./dto/update-user.dto"; import { RoleGuard } from "src/guard/role.guard"; import { plainToInstance } from "class-transformer"; @Controller("user") export class UsersController { constructor(private readonly usersService: UsersService) {} //register as user @Post("register") async register(@Body() createUserDto: CreateUserDto) { return this.usersService.register(createUserDto); } //login as user @Post("login") async login(@Body() loginUserDto: LoginUserDto) { return this.usersService.login(loginUserDto); } //get access token @Post("new-token") async newAccessToken(@Body("token") token: string) { return this.usersService.newAccessToken(token); } //logout user @UseGuards(JwtAuthGuard) @Get("logout") async logout(@Request() req) { const userId = req.user.id; return this.usersService.logout(userId); } //retrieve a user information @UseGuards(JwtAuthGuard) @Get() async getProfile(@Request() req): Promise { const userId = req.user.id; return this.usersService.getProfile(userId); } //edit user profile @UseGuards(JwtAuthGuard) @Put() async editProfile(@Request() req, @Body() updateUserDto: UpdateUserDto) { const userId = req.user.id; const { refreshToken, ...sanitizedDto } = updateUserDto; return this.usersService.editProfile(userId, sanitizedDto); } /////////////////////////////////////admin access endpoints///////////////////////////////////////////////////////// //get users list (admin) @UseGuards(RoleGuard) @Get("users") async findAll(): Promise { return this.usersService.findAll(); } // get a specific user info (admin) @UseGuards(RoleGuard) @Get("users/:id") async findSpecificUserInfoByUser(@Param("id") id) { return this.usersService.findSpecificUserInfoByUser(id); } // delete a specific user (admin) @UseGuards(RoleGuard) @Delete(":id?") async deleteUser(@Param("id") id) { if (!id) { throw new HttpException("User ID is required.", HttpStatus.BAD_REQUEST); } return this.usersService.deleteUser(id); } }