auth.controller.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { Body, Controller, Get, Post, Req } from "@nestjs/common";
  2. import { LoginDto } from "./login.dto";
  3. import { AuthService } from "../../auth/auth.service";
  4. import { RolesGuard } from "../../auth/roles-guard";
  5. import { Role } from "../../auth/role";
  6. import { UserEntity } from "../../entity/user/user.entity";
  7. @Controller('auth')
  8. export class AuthController {
  9. constructor(private authService: AuthService) {}
  10. /**
  11. * Attempts a login given the username and password of a user. If successful, returns
  12. * the user data and a token to be used by Bearer auth.
  13. */
  14. @Post('login')
  15. async login(@Body() loginDto: LoginDto) {
  16. const { user, token } = await this.authService.createToken(loginDto.username, loginDto.password);
  17. if (token) {
  18. return {
  19. token,
  20. user: this.publiclyAccessibleUser(user)
  21. };
  22. }
  23. }
  24. /**
  25. * Returns information about the current authenticated user.
  26. */
  27. @RolesGuard([Role.Authenticated])
  28. @Get('me')
  29. async me(@Req() request) {
  30. const user = request.user as UserEntity;
  31. return this.publiclyAccessibleUser(user);
  32. }
  33. /**
  34. * Exposes a subset of the UserEntity properties which we want to expose to the public API.
  35. */
  36. private publiclyAccessibleUser(user: UserEntity): Pick<UserEntity, 'id' | 'identifier' | 'roles'> {
  37. return {
  38. id: user.id,
  39. identifier: user.identifier,
  40. roles: user.roles
  41. };
  42. }
  43. }