LocChat/server/controllers/users.controller.ts

58 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-11-23 16:04:12 -05:00
import { Body, Controller, Get, HttpException, HttpStatus, Post, Res, UseGuards } from '@nestjs/common';
2021-11-20 21:34:10 -05:00
import * as bcrypt from 'bcrypt';
2021-11-20 20:18:58 -05:00
import { Response } from 'express';
2021-11-23 16:04:12 -05:00
import { JwtBody } from 'server/decorators/jwt_body.decorator';
2021-11-20 20:18:58 -05:00
import { CreateUserDto } from 'server/dto/create_user.dto';
2021-11-23 16:04:12 -05:00
import { JwtBodyDto } from 'server/dto/jwt_body.dto';
import { RefreshToken } from 'server/entities/refresh_token.entity';
2021-11-20 20:18:58 -05:00
import { User } from 'server/entities/user.entity';
2021-11-23 16:04:12 -05:00
import { AuthGuard } from 'server/providers/guards/auth.guard';
import { JwtService } from 'server/providers/services/jwt.service';
import { RefreshTokensService } from 'server/providers/services/refresh_tokens.service';
2021-11-20 20:18:58 -05:00
import { UsersService } from 'server/providers/services/users.service';
@Controller()
export class UsersController {
2021-11-23 16:04:12 -05:00
constructor(
private usersService: UsersService,
private jwtService: JwtService,
private refreshTokenService: RefreshTokensService,
) {}
@Get('/users/me')
@UseGuards(AuthGuard)
async getCurrentUser(@JwtBody() jwtBody: JwtBodyDto) {
const user = await this.usersService.find(jwtBody.userId);
return { user };
}
2021-11-20 20:18:58 -05:00
@Post('/users')
2021-11-23 16:04:12 -05:00
async create(@Body() userPayload: CreateUserDto, @Res({ passthrough: true }) res: Response) {
2021-11-20 20:18:58 -05:00
const newUser = new User();
newUser.email = userPayload.email;
newUser.name = userPayload.name;
2021-11-23 16:04:12 -05:00
newUser.passwordHash = await bcrypt.hash(userPayload.password, 10);
2021-11-20 20:18:58 -05:00
try {
const user = await this.usersService.create(newUser);
2021-11-23 16:04:12 -05:00
// create refresh token in database for user
const newRefreshToken = new RefreshToken();
newRefreshToken.user = user;
const refreshToken = await this.refreshTokenService.create(newRefreshToken);
// issue jwt and refreshJwtToken
const token = this.jwtService.issueToken({ userId: user.id });
const refreshJwtToken = this.jwtService.issueRefreshToken({ id: refreshToken.id, userId: user.id });
// only refresh token should go in the cookie
res.cookie('_refresh_token', refreshJwtToken, {
httpOnly: true, // prevents javascript code from accessing cookie (helps protect against XSS attacks)
});
2021-11-20 20:18:58 -05:00
return { user, token };
} catch (e) {
2021-11-23 16:04:12 -05:00
throw new HttpException(`User creation failed. ${e.message}`, HttpStatus.BAD_REQUEST);
2021-11-20 20:18:58 -05:00
}
}
}