Skip to content

Commit

Permalink
Fix: Admin create model, validation price for payment
Browse files Browse the repository at this point in the history
  • Loading branch information
nuuxcode committed Dec 19, 2023
1 parent b6ae11d commit c322c8b
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 25 deletions.
2 changes: 1 addition & 1 deletion admin/src/layouts/auth/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function Auth() {
<div className="mx-auto flex min-h-full w-full flex-col justify-start pt-12 md:max-w-[75%] lg:h-screen lg:max-w-[1013px] lg:px-8 lg:pt-0 xl:h-[100vh] xl:max-w-[1383px] xl:px-0 xl:pl-[70px]">
<div className="mb-auto flex flex-col pl-5 pr-5 md:pl-12 md:pr-0 lg:max-w-[48%] lg:pl-0 xl:max-w-full">
<Link to="/admin" className="mt-0 w-max lg:pt-10">
<h1 className="text-3xl font-bold text-black">Bike Hub Admin</h1>
<h1 className="mb-2.5 text-4xl font-bold text-navy-700 dark:text-white">Bike Hub Admin</h1>
{/* <div className="mx-auto flex h-fit w-fit items-center hover:cursor-pointer">
<svg
width="8"
Expand Down
36 changes: 28 additions & 8 deletions admin/src/views/admin/user/components/ModelCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,16 @@ const ModalCreate: React.FC<{ module: string; children: React.ReactNode }> = ({
const getFields = async (module: string): Promise<string[]> => {
console.log("getFields")
try {
console.log(`${process.env.REACT_APP_API_URL}${module}s${
module === "user" ? "" : "/" + module
}/2`)
console.log(`${process.env.REACT_APP_API_URL}${module}s${module === "user" ? "" : "/" + module
}/2`)
const response = await axios.get(
`${process.env.REACT_APP_API_URL}${module}s${
module === "user" ? "" : "/" + module
`${process.env.REACT_APP_API_URL}${module}s${module === "user" ? "" : "/" + module
}/check`,
{
withCredentials: true,
}
);
console.log("response ",response)
console.log("response ", response)
if (response.status !== 200) {
throw new Error("Network response was not ok");
}
Expand All @@ -37,7 +35,7 @@ const ModalCreate: React.FC<{ module: string; children: React.ReactNode }> = ({

const excludedFields = ["created_at", "updated_at", "id"];
fields = fields.filter((field) => !excludedFields.includes(field));
console.log("fields",fields)
console.log("fields", fields)
return fields;
} catch (error) {
console.error(error);
Expand All @@ -62,6 +60,10 @@ const ModalCreate: React.FC<{ module: string; children: React.ReactNode }> = ({
value = Number(value);
} else if (event.target.name.endsWith("time")) {
value = new Date(value).toISOString().slice(0, 16);
} else if (event.target.name === "birthdate") {
value = new Date(value).toISOString().slice(0, 10);
} else if (event.target.name === "price") {
value = parseFloat(value);
}
setFormValues({
...formValues,
Expand All @@ -73,7 +75,7 @@ const ModalCreate: React.FC<{ module: string; children: React.ReactNode }> = ({
// Convert date-time strings into Date instances
const data = Object.fromEntries(
Object.entries(formValues).map(([key, value]) => {
if (key.endsWith("time")) {
if (key.endsWith("time") || key === "birthdate") {
console.log(value);
value = new Date(value).toISOString();
console.log(value);
Expand All @@ -83,6 +85,7 @@ const ModalCreate: React.FC<{ module: string; children: React.ReactNode }> = ({
);

const createItem = async (module: string, data: { [key: string]: any }) => {
console.log("birthdate", data.birthdate)
const response = await fetch(
`${process.env.REACT_APP_API_URL}${module}s/${module}`,
{
Expand Down Expand Up @@ -165,6 +168,23 @@ const ModalCreate: React.FC<{ module: string; children: React.ReactNode }> = ({
onChange={handleChange}
color="blue"
/>
) : field === "price" ? (
<input
type="number"
step="0.01"
name={field}
value={formValues[field]}
onChange={handleChange}
className="mt-1 block w-full rounded-md border-b-2 pl-1 shadow-md outline-none focus:border-indigo-300"
/>
) : field === "birthdate" ? (
<input
type="date"
name={field}
value={formValues[field]}
onChange={handleChange}
className="mt-1 block w-full rounded-md border-b-2 pl-1 shadow-md outline-none focus:border-indigo-300"
/>
) : (
<input
type={field.endsWith("id") ? "number" : "text"}
Expand Down
31 changes: 19 additions & 12 deletions api/src/modules/auth/auth.jwt.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ 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[];
Expand All @@ -20,20 +21,21 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
console.log("--- canactivate")
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> {
console.log("--- validateRental")
const { params } = request;
const rental = await this.rentalService.findOne({ id: Number(params.id) });
console.log("rental",rental)
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);
const isSelfUser = (user_id == rental.user_id);
if (!isSelfUser) {
if (!rental) {
console.log("rental not exist")
Expand All @@ -46,35 +48,40 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
return true;
}

ashandleRequest(
handleRequest(
err: Error,
user: User,
info: any,
context: ExecutionContext,
): any {
console.log("user",user)
console.log("--- handleRequest")
const request = context.switchToHttp().getRequest();
console.log("xxxx")
console.log(request.body)
console.log("request.body",request.body)
console.log("------")
console.log(request.headers)
console.log("request.headers",request.headers)
console.log("+++++")
console.log("request.params",request.params)
console.log("+++++")
console.log(request.params)
console.log("request.route.path",request.route.path, request.method)
console.log("+++++")
console.log(request.route.path, request.method)
const { params } = request;
if (err || !user) {
throw err || new UnauthorizedException();
}
if (!this.roles) {
return user;
}
console.log("pass")
const hasRole = () => this.roles.includes(user.role);
let isSelfUser = () => user.id === Number(params.id) || user.id === Number(request.body.user_id);

console.log("hasRole",hasRole())
const isSelfUser = () => user.id === Number(params.id) || user.id === Number(request.body.user_id);

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

if (!hasPermission) {
console.log("no perm")
throw new ForbiddenException();
}

Expand Down
11 changes: 10 additions & 1 deletion api/src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { JwtAuthGuard } from '../auth/auth.jwt.guard';
import { Roles } from '../auth/auth.roles.decorator';
import { UpdateUser } from './../auth/auth.dto';
import { UserService } from './user.service';

import { RegisterUserDTO } from '../auth/auth.dto';
@ApiTags('users')
@Controller('/users')
export class UserController {
Expand All @@ -36,6 +36,15 @@ export class UserController {
return this.userService.findFirst();
}


@Post('user')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
async register(@Body() user: RegisterUserDTO): Promise<User> {
return this.userService.createUser(user);
}


@Get(':id')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/pages/booking/booking.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,10 @@ const BookingPage = () => {

const [isTotalPriceValid, setIsTotalPriceValid] = useState(true);
useEffect(() => {
if (TotalPrice < 2) {
setIsTotalPriceValid(false);
} else {
if (Math.floor(calculateTimeDifference(data.start_time, data.end_time)) > 1) {
setIsTotalPriceValid(true);
} else {
setIsTotalPriceValid(false);
}
}, [TotalPrice]);

Expand Down

0 comments on commit c322c8b

Please sign in to comment.