File: //var/dev/shahnamag/back-end/src/user/user.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete, HttpException, HttpStatus } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { createHash } from 'node:crypto';
import { JwtService } from '@nestjs/jwt';
import { Public } from './auth.guard';
@Controller('user')
export class UserController {
constructor(
private readonly userService: UserService,
private jwtService: JwtService) {}
@Public()
@Post('login')
async login(@Body() credentials: {username: string, password: string}) {
let user = await this.userService.findOneByUsername(credentials.username);
if(!user || user.password!=createHash('md5').update(credentials.password).digest('hex'))
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
let {password, ...payload} = user;
return {
data: {token: await this.jwtService.signAsync(payload)},
error: 0
};
}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.userService.create(createUserDto);
}
@Get()
findAll() {
return this.userService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.userService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.userService.update(+id, updateUserDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.userService.remove(+id);
}
}