Files
swiss-datashare/backend/src/user/user.controller.ts

83 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-12-05 10:02:19 +01:00
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
2023-03-04 23:40:02 +01:00
Res,
2022-12-05 10:02:19 +01:00
UseGuards,
} from "@nestjs/common";
import { User } from "@prisma/client";
2023-03-04 23:40:02 +01:00
import { Response } from "express";
import { GetUser } from "src/auth/decorator/getUser.decorator";
2022-12-05 10:02:19 +01:00
import { AdministratorGuard } from "src/auth/guard/isAdmin.guard";
import { JwtGuard } from "src/auth/guard/jwt.guard";
2022-12-05 15:53:24 +01:00
import { CreateUserDTO } from "./dto/createUser.dto";
import { UpdateOwnUserDTO } from "./dto/updateOwnUser.dto";
2022-12-05 10:02:19 +01:00
import { UpdateUserDto } from "./dto/updateUser.dto";
2022-10-10 17:58:42 +02:00
import { UserDTO } from "./dto/user.dto";
2022-12-05 10:02:19 +01:00
import { UserSevice } from "./user.service";
@Controller("users")
export class UserController {
2022-12-05 10:02:19 +01:00
constructor(private userService: UserSevice) {}
// Own user operations
@Get("me")
@UseGuards(JwtGuard)
async getCurrentUser(@GetUser() user: User) {
2022-10-10 17:58:42 +02:00
return new UserDTO().from(user);
}
2022-12-05 10:02:19 +01:00
@Patch("me")
@UseGuards(JwtGuard)
2022-12-05 15:53:24 +01:00
async updateCurrentUser(
@GetUser() user: User,
@Body() data: UpdateOwnUserDTO,
2022-12-05 15:53:24 +01:00
) {
2022-12-05 10:02:19 +01:00
return new UserDTO().from(await this.userService.update(user.id, data));
}
@Delete("me")
@UseGuards(JwtGuard)
2023-03-04 23:40:02 +01:00
async deleteCurrentUser(
@GetUser() user: User,
@Res({ passthrough: true }) response: Response,
2023-03-04 23:40:02 +01:00
) {
response.cookie("access_token", "accessToken", { maxAge: -1 });
response.cookie("refresh_token", "", {
path: "/api/auth/token",
httpOnly: true,
maxAge: -1,
});
2022-12-05 10:02:19 +01:00
return new UserDTO().from(await this.userService.delete(user.id));
}
// Global user operations
@Get()
@UseGuards(JwtGuard, AdministratorGuard)
async list() {
return new UserDTO().fromList(await this.userService.list());
}
@Post()
@UseGuards(JwtGuard, AdministratorGuard)
2022-12-05 15:53:24 +01:00
async create(@Body() user: CreateUserDTO) {
2022-12-05 10:02:19 +01:00
return new UserDTO().from(await this.userService.create(user));
}
@Patch(":id")
@UseGuards(JwtGuard, AdministratorGuard)
async update(@Param("id") id: string, @Body() user: UpdateUserDto) {
return new UserDTO().from(await this.userService.update(id, user));
}
@Delete(":id")
@UseGuards(JwtGuard, AdministratorGuard)
2022-12-05 15:53:24 +01:00
async delete(@Param("id") id: string) {
2022-12-05 10:02:19 +01:00
return new UserDTO().from(await this.userService.delete(id));
}
}