Update try-catch handling in user register and login functionality

master
nicekid1 2 months ago
parent 3c216fa12a
commit 69c0a65ad5
  1. 13
      src/users/users.controller.ts
  2. 71
      src/users/users.service.ts

@ -1,21 +1,20 @@
import { Controller, Post, Body, Res, UseGuards, Get } from "@nestjs/common";
import { UsersService } from "./users.service";
import { Response } from "express";
import { JwtAuthGuard } from "src/guard/auth.guard";
import { User } from "./entities/user.entity";
@Controller("users")
@Controller("user")
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post("register")
async register(@Body() body: { email: string; password: string }, @Res() res: Response): Promise<Response> {
async register(@Body() body: { email: string; password: string }):Promise<User> {
const { email, password } = body;
return this.usersService.register(email, password, res);
return this.usersService.register(email, password);
}
@Post("login")
async login(@Body() body: { email: string; password: string }, @Res() res: Response): Promise<Response> {
async login(@Body() body: { email: string; password: string }):Promise<{token}> {
const { email, password } = body;
return this.usersService.login(email, password, res);
return this.usersService.login(email, password);
}
}

@ -1,8 +1,7 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { HttpException, HttpStatus, Injectable, UnauthorizedException, BadRequestException } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { User } from "./entities/user.entity";
import * as bcrypt from "bcrypt";
import { Response } from "express";
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
@ -15,13 +14,16 @@ export class UsersService {
) {}
// Register method
async register(email: string, password: string, res: Response): Promise<Response> {
async register(email: string, password: string): Promise<User> {
if (!email) throw new BadRequestException("Email should be entered");
if (!password) throw new BadRequestException("Password should be entered");
try {
const hashedPassword = await bcrypt.hash(password, 10);
const userExists = await this.userModel.findOne({ where: { email } });
if (userExists) {
return res.status(400).json({ message: "Email is already taken" });
throw new BadRequestException('Email already exists');
}
const user = await this.userModel.create({
@ -29,50 +31,37 @@ export class UsersService {
password: hashedPassword,
});
return res.status(201).json({
message: "Account created successfully!",
user: { id: user.id, email: user.email },
});
return user;
} catch (error) {
return res.status(500).json({
message: "Failed to create account. Please try again later.",
error: error.message,
});
throw new HttpException(`An error occurred: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// Login method
async login(email: string, password: string, res: Response): Promise<Response> {
try {
const user = await this.userModel.findOne({
where: { email },
});
if (!user) {
throw new UnauthorizedException("Invalid email or password");
}
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
throw new UnauthorizedException("Invalid email or password");
}
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");
const token = await this.jwtService.sign(
{ id: user.id },
{
secret: this.configService.get<string>("JWT_SECRET"),
expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h",
},
);
const user = await this.userModel.findOne({
where: { email },
});
if (!user) {
throw new UnauthorizedException("Invalid email or password");
}
return res.status(200).json({
message: "Login successful",
token,
});
} catch (error) {
return res.status(500).json({
message: "Internal server error",
error: error.message,
});
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
throw new UnauthorizedException("Invalid email or password");
}
const token = this.jwtService.sign(
{ id: user.id },
{
secret: this.configService.get<string>("JWT_SECRET"),
expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h",
},
);
return { token };
}
}

Loading…
Cancel
Save