Skip to content

Commit

Permalink
fix: jwt for current user required for update
Browse files Browse the repository at this point in the history
  • Loading branch information
VASHvic committed Oct 16, 2022
1 parent 46d4ec4 commit ecced5e
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 32 deletions.
1 change: 0 additions & 1 deletion src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { JwtService } from "@nestjs/jwt";
import { getModelToken } from "@nestjs/mongoose";
import { User, UserDocument } from "src/user/schemas/user.schema";
import { Model } from "mongoose";
import { newMockUser, randomMockUser } from "test/e2e.constants";

describe("AuthController", () => {
let controller: AuthController;
Expand Down
2 changes: 1 addition & 1 deletion src/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Observable } from "rxjs";
import { IS_PUBLIC_KEY } from "../decorators/public.decorator";

@Injectable()
export class JwtAuthGuard extends AuthGuard("Jwt") {
export class JwtAuthGuard extends AuthGuard("jwt") {
constructor(private reflector: Reflector) {
super();
}
Expand Down
12 changes: 0 additions & 12 deletions src/auth/services/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,4 @@ describe("AuthService", () => {
it("should be defined", () => {
expect(service).toBeDefined();
});
// it('should return a user doc', async () => {
// // arrange
// const user = new User();
// const userID = '12345';
// const spy = jest
// .spyOn(mockUserModel, 'findById') // <- spy on what you want
// .mockResolvedValue(user as UserDocument); // <- Set your resolved value
// // act
// await mockRepository.findOneById(userID);
// // assert
// expect(spy).toBeCalled();
// });
});
4 changes: 2 additions & 2 deletions src/auth/services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import * as bcrypt from "bcrypt";
import { UserService } from "src/user/user.service";
import { PayloadToken, SafeUserType } from "../types/types";
import { SafeUserType } from "../types/types";

@Injectable()
export class AuthService {
Expand All @@ -21,7 +21,7 @@ export class AuthService {
}

generateJWT(user: SafeUserType) {
const payload: PayloadToken = { sub: user._id };
const payload = { sub: user._id };
return {
access_token: this.jwtService.sign(payload),
user,
Expand Down
2 changes: 2 additions & 0 deletions src/auth/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { User } from "src/user/schemas/user.schema";

export interface PayloadToken {
sub: string;
iat: number;
exp: number;
}
export type UserType = {
_id: string;
Expand Down
4 changes: 2 additions & 2 deletions src/user/user-error.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { BadRequestException, Injectable, HttpException } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { UserErrorDocument } from "./schemas/user-error.schema";
Expand All @@ -13,7 +13,7 @@ export class UserErrorService {
if (e.code === 11000) {
errorMesage = `A User with ${Object.entries(e.keyValue)} already exists`;
}
const error = new BadRequestException(errorMesage ?? "Unknow Error");
const error = new HttpException(errorMesage ?? e.message, e.status);
const newUserError = new this.userErrorModel({ error });
await newUserError.save();
return error;
Expand Down
21 changes: 17 additions & 4 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import {
Controller,
Delete,
Get,
Header,
Headers,
Param,
Patch,
Post,
UseGuards,
} from "@nestjs/common";
import { JwtAuthGuard } from "src/auth/guards/jwt-auth.guard";
import { DeleteUserDto } from "src/dto/deleteUser.dto";
import { Public } from "../auth/decorators/public.decorator";
import { ApiKeyGuard } from "../auth/guards/api-key.guard";
Expand Down Expand Up @@ -53,12 +56,23 @@ export class UserController {
return rta;
}

@UseGuards(JwtAuthGuard)
@UseGuards(LocalAuthGuard)
@Patch("update")
public async updateUser(@Body() dto: UpdateUserDto): Promise<SafeUserType> {
return this.userService.update(dto);
}
public async updateUser(
@Body() dto: UpdateUserDto,
@Headers() headers,
): Promise<SafeUserType> {
const { authorization } = headers;
try {
return await this.userService.update(dto, authorization);
} catch (e) {
const error = await this.userErrorService.saveError(e);

throw error;
}
}
@UseGuards(JwtAuthGuard)
@UseGuards(LocalAuthGuard)
@Delete("delete")
public async deleteUser(@Body() dto: DeleteUserDto): Promise<boolean> {
Expand All @@ -72,7 +86,6 @@ export class UserController {
return await this.userService.signUp(dto);
} catch (e) {
console.log(e);

const error = await this.userErrorService.saveError(e);
throw error;
}
Expand Down
3 changes: 2 additions & 1 deletion src/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Module } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { MongooseModule } from "@nestjs/mongoose";
import { ErrorSchema } from "./schemas/user-error.schema";
import { User, UserSchema } from "./schemas/user.schema";
Expand All @@ -13,7 +14,7 @@ import { UserService } from "./user.service";
{ name: "userError", schema: ErrorSchema },
]),
],
providers: [UserService, UserErrorService],
providers: [UserService, UserErrorService, JwtService],
controllers: [UserController],
exports: [UserService, MongooseModule],
})
Expand Down
31 changes: 24 additions & 7 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from "@nestjs/common";
import { Inject, Injectable, UnauthorizedException } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { createUserDto } from "src/dto/createUser.dto";
Expand All @@ -7,10 +7,14 @@ import { User, UserDocument } from "./schemas/user.schema";
import * as bycript from "bcrypt";
import { SafeUserType, UserType } from "src/auth/types/types";
import { DeleteUserDto } from "src/dto/deleteUser.dto";
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class UserService {
constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}
constructor(
@InjectModel(User.name) private userModel: Model<UserDocument>,
private readonly jwtService: JwtService,
) {}

public async signUp(dto: createUserDto): Promise<SafeUserType> {
const newUser = new this.userModel(dto);
Expand All @@ -33,17 +37,30 @@ export class UserService {
return user ? (user.toJSON() as UserType) : null;
}

public async update(changes: UpdateUserDto) {
const { _id } = (await this.findByEmail(changes.email)) as UserType;
public async update(changes: UpdateUserDto, auth: string) {
const token = auth.split(" ")[1];
const { sub } = this.jwtService.decode(token);
const userFromToken = await this.findById(sub);

const userFromEmail = (await this.findByEmail(changes.email)) as UserType;
if (
JSON.stringify(userFromToken) !== JSON.stringify(userFromEmail) // diuen que millorable
) {
throw new Error("Authorization token doesnt belong to User");
}
const updated = {} as User;
if (changes.newName) updated.name = changes.newName;
if (changes.newPassword)
updated.password = await bycript.hash(changes.newPassword, 10);
if (changes.newEmail) updated.email = changes.newEmail;

const updatedUser = await this.userModel.findByIdAndUpdate(_id, updated, {
returnOriginal: false,
});
const updatedUser = await this.userModel.findByIdAndUpdate(
userFromEmail._id,
updated,
{
returnOriginal: false,
},
);
const { password, __v, ...rta } = updatedUser.toJSON();
return rta as SafeUserType;
}
Expand Down
8 changes: 6 additions & 2 deletions test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
describe("Starting App", () => {
let app: INestApplication;
let httpServer: any;
let token;
//mirar si pug afafar la conexió com michael guay

jest.setTimeout(120000);
Expand Down Expand Up @@ -68,7 +69,7 @@ describe("Starting App", () => {
const response = await request(httpServer)
.post("/auth/login")
.send(newMockUser);

token = response.body.access_token;
expect(response.status).toBe(201);
expect(response.body).toMatchObject({
access_token: expect.any(String),
Expand All @@ -89,10 +90,12 @@ describe("Starting App", () => {
expect(response.body).toMatchObject(newMockUserNoPass);
});
});

describe("USER update the user just created /user/update (PATCH)", () => {
it("should uypdate the user", async () => {
it("should update the user", async () => {
const response = await request(httpServer)
.patch("/user/update")
.set("Authorization", `Bearer ${token}`)
.send(updatedMockUserDto);
expect(response.status).toBe(200);
});
Expand All @@ -107,6 +110,7 @@ describe("Starting App", () => {
it("should delete the user", async () => {
const response = await request(httpServer)
.delete("/user/delete")
.set("Authorization", `Bearer ${token}`)
.send(updatedMockUser);
expect(response.status).toBe(200);
expect(response.text).toBe("true");
Expand Down

0 comments on commit ecced5e

Please sign in to comment.