Skip to content

Commit

Permalink
Fix bugs related to QRCODE and rental access on backend and fixing ur…
Browse files Browse the repository at this point in the history
…l for paypal button
  • Loading branch information
nuuxcode committed Dec 19, 2023
1 parent f4d0265 commit 7e85371
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 10 deletions.
39 changes: 35 additions & 4 deletions api/src/modules/auth/auth.jwt.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,59 @@ import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { User } from '@prisma/client';

import { RentalService } from '../rental/rental.service';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
roles: string[];

constructor(private reflector?: Reflector) {
constructor(private reflector?: Reflector, private rentalService?: RentalService) {
super(reflector);
}

canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
this.roles = this.reflector.get<string[]>('roles', context.getHandler());
const request = context.switchToHttp().getRequest();
if (request.route.path === '/api/v1/rentals/rental/:id' && request.method === 'GET') {
return this.validateRental(request);
}
return super.canActivate(context);
}
async validateRental(request): Promise<boolean> {
const { params } = request;
const rental = await this.rentalService.findOne({ id: Number(params.id) });
const user_id = request.headers['user-id'];
console.log("request.headers['user-id']", user_id)
console.log("rentalService.findOne user_id", rental?.user_id)
const isSelfUser = (rental != null && user_id == rental.user_id);
if (!isSelfUser) {
if (!rental) {
console.log("rental not exist")
} else {
console.log("rental not valid")
}
throw new ForbiddenException();
}
console.log("rental valid")
return true;
}

handleRequest(
ashandleRequest(
err: Error,
user: User,
info: any,
context: ExecutionContext,
): any {
const request = context.switchToHttp().getRequest();
console.log("xxxx")
console.log(request.body)
console.log("------")
console.log(request.headers)
console.log("+++++")
console.log(request.params)
console.log("+++++")
console.log(request.route.path, request.method)
const { params } = request;
if (err || !user) {
throw err || new UnauthorizedException();
Expand All @@ -39,7 +69,8 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
return user;
}
const hasRole = () => this.roles.includes(user.role);
const isSelfUser = () => user.id === Number(params.id);
let isSelfUser = () => user.id === Number(params.id) || user.id === Number(request.body.user_id);


const hasPermission = hasRole() || isSelfUser();

Expand Down
3 changes: 2 additions & 1 deletion api/src/modules/rental/rental.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { Module, Global } from '@nestjs/common';

import { PrismaService } from '../prisma/prisma.service';

import { RentalService } from './rental.service';
import { RentalController } from './rental.controller';

@Global()
@Module({
imports: [],
controllers: [RentalController],
Expand Down
7 changes: 5 additions & 2 deletions api/src/modules/rental/rental.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class RentalService {
constructor(private prisma: PrismaService) {}
constructor(private prisma: PrismaService) { }

async findOne(
rentalWhereUniqueInput: Prisma.RentalWhereUniqueInput,
Expand All @@ -21,7 +21,10 @@ export class RentalService {
},
},
});
delete data.User.password;
console.log("data", data)
if (data) {
delete data.User.password;
}
return data;
}

Expand Down
15 changes: 13 additions & 2 deletions frontend/src/components/paypal/PayPalButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@ import React from 'react';
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
import { OnApproveData } from "@paypal/paypal-js/types/components/buttons";

let BACKEND_URL : any;
if (import.meta.env.VITE_MODE === 'prod') {
BACKEND_URL = import.meta.env.VITE_BACK_END_PROD;
}
if (import.meta.env.VITE_MODE === 'dev') {
BACKEND_URL = import.meta.env.VITE_BACK_END_DEV;
}
if (import.meta.env.VITE_MODE === 'local') {
BACKEND_URL = import.meta.env.VITE_BACK_END_LOCAL;
}

interface PayPalButtonProps {
onPaymentSuccess?: () => void;
onPaymentFailure?: () => void;
Expand Down Expand Up @@ -30,7 +41,7 @@ const PayPalButton: React.FC<PayPalButtonProps> = ({ amount, onPaymentSuccess, o
};

try {
const response = await fetch("http://localhost:3300/api/v1/orders/create_order", {
const response = await fetch(`${BACKEND_URL}orders/create_order`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand All @@ -51,7 +62,7 @@ const PayPalButton: React.FC<PayPalButtonProps> = ({ amount, onPaymentSuccess, o
};

const onApprove = (data: OnApproveData) => {
return fetch(`http://localhost:3300/api/v1/orders/complete_order`, {
return fetch(`${BACKEND_URL}orders/complete_order`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand Down
7 changes: 6 additions & 1 deletion frontend/src/components/qrcode/qrcode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ const QRCodeComponent = ({ id }: { id: number }) => {
const qrCodeRef = useRef(null);

useEffect(() => {
axios.get(`/rentals/rental/${id}`, { withCredentials: true })
axios.get(`/rentals/rental/${id}`, {
headers: {
'User-Id': JSON.parse(localStorage.getItem('user') || '').id,
},
withCredentials: true
})
.then(response => {
console.log("response.data", response.data)
const { id, user_id, bike_id, start_time, end_time, status, price, qrcode, payment_id, order_id, User, Bike, Park } = response.data;
Expand Down

0 comments on commit 7e85371

Please sign in to comment.