Skip to content

Commit

Permalink
Update middleware to support AllowAny (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
ltan02 authored Mar 25, 2024
1 parent be00e59 commit 5cc4a7f
Show file tree
Hide file tree
Showing 12 changed files with 162 additions and 102 deletions.
2 changes: 1 addition & 1 deletion backend/auction/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
AddToAuctionApiView,
AuctionDetailApiView,
AuctionListApiView,
AuctionVehiclesApiView,
GetSavedUnitApiView,
SaveUnitApiView,
AuctionVehiclesApiView,
)

urlpatterns = [
Expand Down
12 changes: 9 additions & 3 deletions backend/auction/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from core.permissions import IsAdminUser, IsAuthenticated
from services.AWSCognitoService import AWSCognitoService
from vehicle.models import SavedUnits, Vehicle, Equipment, Trailer
from vehicle.models import Equipment, SavedUnits, Trailer, Vehicle

from .models import Auction, AuctionItem
from .serializers import AuctionSerializer
Expand Down Expand Up @@ -243,5 +243,11 @@ def get(self, request, **kwargs):
equipment_data = [{"id": equipment.id} for equipment in equipment_list]
trailer_data = [{"id": trailer.id} for trailer in trailer_list]

return Response({"vehicles": vehicle_data, "equipment": equipment_data,
"trailers": trailer_data}, status=status.HTTP_200_OK)
return Response(
{
"vehicles": vehicle_data,
"equipment": equipment_data,
"trailers": trailer_data,
},
status=status.HTTP_200_OK,
)
6 changes: 5 additions & 1 deletion backend/util/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ def authenticate(self, request):
if not token:
return (unauthenticated_user, None)

if request.path.startswith("/api/v1/auth"):
if (
request.path.startswith("/api/v1/auth")
or request.path == "/api/v1/bidders/"
or request.path == "/api/v1/admins/"
):
return (unauthenticated_user, None)

try:
Expand Down
48 changes: 41 additions & 7 deletions backend/util/middleware.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import jwt
import requests
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from rest_framework import exceptions

from services import AWSCognitoService
from services.AWSCognitoService import AWSCognitoService
from util.jwt import decode_token


class RefreshTokenMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path.startswith("/api/v1/auth"):
if request.path.startswith("/api/v1/auth") or request.path in [
"/api/v1/bidders/",
"/api/v1/admins/",
]:
return

id_token = request.COOKIES.get("idToken")
refresh_token = request.COOKIES.get("refreshToken")
if not refresh_token:
return

try:
access_token = request.COOKIES.get("accessToken")
jwt.decode(access_token, options={"verify_signature": False})
return self.get_response(request)
self.verify_jwt_token(id_token)
except jwt.ExpiredSignatureError:
cognito_service = AWSCognitoService()
decoded_id_token = decode_token(request.COOKIES.get("idToken"))
decoded_id_token = self.decode_jwt_without_validation(id_token)
new_tokens = cognito_service.refresh_tokens(
decoded_id_token.get("sub"), refresh_token
)
Expand All @@ -36,7 +41,7 @@ def process_request(self, request):
httponly=True,
samesite="Lax",
)
if new_tokens.get("RefreshToken"):
if "RefreshToken" in new_tokens:
response.set_cookie(
"refreshToken",
new_tokens.get("RefreshToken"),
Expand All @@ -46,3 +51,32 @@ def process_request(self, request):
return response

return None

def verify_jwt_token(self, token):
jwks_url = settings.SIMPLE_JWT["JWK_URL"]
jwks = requests.get(jwks_url).json()
public_keys = {
jwk["kid"]: jwt.algorithms.RSAAlgorithm.from_jwk(jwk)
for jwk in jwks["keys"]
}

headers = jwt.get_unverified_header(token)
kid = headers["kid"]
key = public_keys.get(kid)
if not key:
raise exceptions.AuthenticationFailed("Public key not found.")

return jwt.decode(
token,
key=key,
algorithms=["RS256"],
audience=settings.SIMPLE_JWT["AUDIENCE"],
issuer=settings.SIMPLE_JWT["ISSUER"],
)

def decode_jwt_without_validation(self, token):
# Decode without validation
decoded = jwt.decode(
token, options={"verify_signature": False, "verify_exp": False}
)
return decoded
4 changes: 2 additions & 2 deletions frontend/sample.env
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
REACT_APP_NODE_ENV="dev"
REACT_APP_DEV_BACKEND_BASE_URL="http://127.0.0.1:8000/api/v1/"
REACT_APP_PROD_BACKEND_BASE_URL="http://api.auction.microvaninc.com/api/v1/"
REACT_APP_DEV_BACKEND_BASE_URL="http://localhost:8000/api/v1"
REACT_APP_PROD_BACKEND_BASE_URL="https://www.api.auction.microvaninc.com/api/v1"
4 changes: 2 additions & 2 deletions frontend/src/components/searchBars/ListingsSearchBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ export default function ListingSearchBar({ setResults }) {
};

return (
<div className="flex items-center w-full h-[56px] px-5 py-4 shrink-0 gap-5 rounded-2xl bg-mv-white shadow-searchBarShadow">
<div className="flex items-center w-full h-[40px] px-5 py-4 shrink-0 gap-5 rounded-2xl bg-mv-white shadow-searchBarShadow">
<SearchIcon className="w-[24px] h-[24px] text-mv-black" />
<input
className="w-full text-base font-normal text-mv-black placeholder-dark-grey outline-none"
className="w-full text-base font-normal text-mv-black placeholder-dark-grey outline-none leading-6 tracking-[0.5px]"
placeholder="Search vehicle"
value={input}
onChange={(e) => handleChange(e.target.value)}
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/timers/CurrentAuctionCountdown.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ export default function CurrentAuctionCountdown({

return (
<div className="float-right text-right" style={{ width: maxWidth }}>
<div className="mb-2 text-mv-black text-xl font-medium">
<div className="mb-2 text-mv-black text-lg font-medium">
{statusString}
</div>
<div
className="h-[11px] bg-progress-bar rounded-lg overflow-hidden"
className="h-[14px] bg-progress-bar rounded-lg overflow-hidden"
style={{ width: maxWidth, float: 'right' }}
>
<div
Expand Down
119 changes: 61 additions & 58 deletions frontend/src/pages/HomePage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default function HomePage() {
endpoint: 'auctions/',
method: 'GET',
});

// get items associated with each auction
const itemsPromises = response.data.map(async (auction) => {
const itemResponse = await fetchData({
Expand All @@ -50,9 +50,9 @@ export default function HomePage() {
});
return { ...auction, items: itemResponse.data };
});

const auctionsWithItems = await Promise.all(itemsPromises);

const auctionList = sortAuctions(auctionsWithItems);
setUpcomingAuctionList(auctionList.upcoming);
setCurrentAuctionList(auctionList.current);
Expand All @@ -67,7 +67,6 @@ export default function HomePage() {
getAuctions();
}, []);


return (
<div className="min-w-screen max-w-screen">
<div className="relative min-h-screen">
Expand Down Expand Up @@ -138,62 +137,66 @@ export default function HomePage() {
</h2>
<AuctionsSearchBar setResults={setSearchedAuctions} />
</div>
{currentAuctionList.length > 0 && <div className="flex flex-col gap-y-[18px] w-[80%] items-start">
<h2 className="text-mv-black text-4xl font-semibold">
Current Auction
</h2>
<CurrentAuctionCard
imageUrls={[image, image, image, image]}
startDate={new Date(currentAuctionList[0].start_date)}
endDate={new Date(currentAuctionList[0].end_date)}
numberOfEquipment={currentAuctionList[0].items.equipment.length}
numberOfTrailers={currentAuctionList[0].items.trailers.length}
numberOfTrucks={currentAuctionList[0].items.vehicles.length}
button={currentAuctionButton}
/>
</div>}
{upcomingAuctionList.length > 0 && <div className="flex flex-col gap-y-[18px] w-[80%] items-start">
<h2 className="text-mv-black text-4xl font-semibold">
Upcoming Auctions
</h2>
<div className="grid grid-cols-3 grid-rows-1 gap-[4.3rem] w-full">
{upcomingAuctionList.map(auction => (
<UpcomingAuctionCard
imageUrls={[image, image, image, image]}
startDate={new Date(auction.start_date)}
endDate={new Date(auction.end_date)}
numberOfEquipment={auction.items.equipment.length}
numberOfTrailers={auction.items.trailers.length}
numberOfTrucks={auction.items.vehicles.length}
button={upcomingAuctionButton}
/>
))}

{currentAuctionList.length > 0 && (
<div className="flex flex-col gap-y-[18px] w-[80%] items-start">
<h2 className="text-mv-black text-4xl font-semibold">
Current Auction
</h2>
<CurrentAuctionCard
imageUrls={[image, image, image, image]}
startDate={new Date(currentAuctionList[0].start_date)}
endDate={new Date(currentAuctionList[0].end_date)}
numberOfEquipment={currentAuctionList[0].items.equipment.length}
numberOfTrailers={currentAuctionList[0].items.trailers.length}
numberOfTrucks={currentAuctionList[0].items.vehicles.length}
button={currentAuctionButton}
/>
</div>
</div>}
{pastAuctionList.length > 0 && <div className="flex flex-col gap-y-[18px] w-[80%] items-start">
<h2 className="text-mv-black text-4xl font-semibold">
Past Auctions
</h2>
<div className="grid grid-cols-3 grid-rows-1 gap-[4.3rem] w-full">
{pastAuctionList.map(auction => (
<PastAuctionCard
imageUrls={[image, image, image, image]}
startDate={new Date(auction.start_date)}
endDate={new Date(auction.end_date)}
numberOfEquipment={auction.items.equipment.length}
numberOfTrailers={auction.items.trailers.length}
numberOfTrucks={auction.items.vehicles.length}
/>
))}

)}
{upcomingAuctionList.length > 0 && (
<div className="flex flex-col gap-y-[18px] w-[80%] items-start">
<h2 className="text-mv-black text-4xl font-semibold">
Upcoming Auctions
</h2>
<div className="grid grid-cols-3 grid-rows-1 gap-[4.3rem] w-full">
{upcomingAuctionList.map((auction) => (
<UpcomingAuctionCard
imageUrls={[image, image, image, image]}
startDate={new Date(auction.start_date)}
endDate={new Date(auction.end_date)}
numberOfEquipment={auction.items.equipment.length}
numberOfTrailers={auction.items.trailers.length}
numberOfTrucks={auction.items.vehicles.length}
button={upcomingAuctionButton}
/>
))}
</div>
</div>
<button type="button" className="flex ml-auto items-end">
<p className="text-mv-black text-base font-normal underline">
view more
</p>
</button>
</div>}
)}
{pastAuctionList.length > 0 && (
<div className="flex flex-col gap-y-[18px] w-[80%] items-start">
<h2 className="text-mv-black text-4xl font-semibold">
Past Auctions
</h2>
<div className="grid grid-cols-3 grid-rows-1 gap-[4.3rem] w-full">
{pastAuctionList.map((auction) => (
<PastAuctionCard
imageUrls={[image, image, image, image]}
startDate={new Date(auction.start_date)}
endDate={new Date(auction.end_date)}
numberOfEquipment={auction.items.equipment.length}
numberOfTrailers={auction.items.trailers.length}
numberOfTrucks={auction.items.vehicles.length}
/>
))}
</div>
<button type="button" className="flex ml-auto items-end">
<p className="text-mv-black text-base font-normal underline">
view more
</p>
</button>
</div>
)}
</div>
<div className="w-full items-center">
<Footer />
Expand Down
12 changes: 6 additions & 6 deletions frontend/src/pages/ListingsPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export default function ListingsPage() {
<NavBar />
<div className="flex flex-col w-[85%] mx-auto">
<div className="flex flex-col gap-y-[48px] mt-[116px]">
<h1 className="text-mv-black text-4xl font-semibold">
<h1 className="text-mv-black text-3xl font-semibold">
Auction Listings (Nov 5-7)
</h1>
<p className="text-mv-black text-xl font-base">
Expand All @@ -94,13 +94,13 @@ export default function ListingsPage() {

<div className="flex flex-col w-[85%] mx-auto">
<div className="mt-[116px]">
<h1 className="text-mv-black text-4xl font-semibold">
<h1 className="text-mv-black text-3xl font-semibold">
Auction Listings (Nov 5-7)
</h1>
</div>

<div className="mt-[75px] flex justify-between items-end">
<h2 className="text-mv-black text-[26px] font-medium">
<h2 className="text-mv-black text-xl font-medium">
Items for Monday, November 6
</h2>

Expand All @@ -111,11 +111,11 @@ export default function ListingsPage() {
/>
</div>

<div className="mt-[23px]">
<div className="mt-[26px]">
<ListingSearchBar setResults={setUnits} />
</div>

<div className="mt-[117px] flex gap-x-9">
<div className="mt-[77px] flex gap-x-9">
<div className="w-[22%] flex flex-col mt-[32px] gap-y-4 sticky top-0">
<h2 className="text-mv-black text-xl font-medium">Filters</h2>
<div className="px-5 pt-5 pb-[80px] bg-light-grey rounded-[20px] flex flex-col gap-y-[36px] shadow-filterBoxShadow">
Expand Down Expand Up @@ -179,7 +179,7 @@ export default function ListingsPage() {
</div>
</div>

<div className="mt-[266px]">
<div className="mt-[101px]">
<Footer />
</div>
</div>
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/pages/auth/bidders/BidderLogInPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export default function BidderLogInPage() {
const handleLogIn = async () => {
try {
const result = await fetchData({
endpoint: 'auth/login/',
endpoint: '/auth/login/',
method: 'POST',
data: { email, password, is_admin: true },
data: { email, password, is_admin: false },
});
localStorage.setItem('userInfo', JSON.stringify(result.data));
navigate('/');
Expand Down
Loading

0 comments on commit 5cc4a7f

Please sign in to comment.