Create DTO for login route and refactor related routes

master
nicekid1 2 months ago
parent 435083a682
commit 86ce21487a
  1. 15
      src/users/dto/login-user.dto.ts
  2. 11
      src/users/users.controller.ts
  3. 9
      src/users/users.service.ts

@ -0,0 +1,15 @@
import { IsString, IsEmail, IsEnum, IsNotEmpty, IsOptional, Matches } from "class-validator";
export class LoginUserDto {
@IsEmail({}, { message: "Invalid email format" })
email: string;
@IsString()
@IsNotEmpty({ message: "Password is required" })
password: string;
@IsString()
@IsNotEmpty({ message: "Username is required" })
username: string;
}

@ -2,19 +2,20 @@ import { Controller, Post, Body} 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";
@Controller("user")
export class UsersController {
constructor(private readonly usersService: UsersService) {}
//register as user
@Post("register")
async register(@Body() createUserDto: CreateUserDto):Promise<User> {
return this.usersService.register(createUserDto);
}
//login as user
@Post("login")
async login(@Body() body: { email: string; password: string }):Promise<{token}> {
const { email, password } = body;
return this.usersService.login(email, password);
async login(@Body() loginUserDto:LoginUserDto):Promise<{token}> {
return this.usersService.login(loginUserDto);
}
}

@ -5,6 +5,7 @@ import * as bcrypt from "bcrypt";
import { JwtService } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
import { CreateUserDto } from "./dto/create-user.dto";
import { LoginUserDto } from "./dto/login-user.dto";
@Injectable()
export class UsersService {
@ -41,18 +42,16 @@ export class UsersService {
// Login method
async login(email: string, password: string): Promise<{ token: string }> {
if (!email) throw new BadRequestException("Email should be entered");
if (!password) throw new BadRequestException("Password should be entered");
async login(loginUserDto:LoginUserDto): Promise<{ token: string }> {
const user = await this.userModel.findOne({
where: { email },
where: { email:loginUserDto.email },
});
if (!user) {
throw new UnauthorizedException("Invalid email or password");
}
const passwordMatch = await bcrypt.compare(password, user.password);
const passwordMatch = await bcrypt.compare(loginUserDto.password, user.password);
if (!passwordMatch) {
throw new UnauthorizedException("Invalid email or password");
}

Loading…
Cancel
Save