From 8f60af2ec5978df9a5190ac2a346037165f4a75c Mon Sep 17 00:00:00 2001 From: Roberto Milla Martinez Date: Sun, 10 Nov 2024 00:09:58 +0100 Subject: [PATCH] feat: authed request address --- src/app/api/address/route.ts | 24 +++++++----------------- src/lib/service.ts | 4 ++-- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/app/api/address/route.ts b/src/app/api/address/route.ts index 7a14748..b36f2e3 100644 --- a/src/app/api/address/route.ts +++ b/src/app/api/address/route.ts @@ -1,5 +1,5 @@ import { NextRequest } from 'next/server'; -import { supabase } from '../../../lib/supabase/client'; +import { createClient } from '@/lib/supabase/server'; const mapsTranslationToDbTowns: { [key: string]: string } = { Aldaya: 'Aldaia', @@ -23,22 +23,12 @@ const GOOGLE_URL = `https://maps.googleapis.com/maps/api/geocode/json?key=${proc export type AddressAndTown = { address: string; town: string }; -async function checkAuthentication(request: NextRequest) { - // Extract the Supabase token from the authorization header - const authHeader = request.headers.get('authorization') || ''; - const token = authHeader.split('Bearer ')[1]; - - if (!token) { - return Response.json({ - error: 'Unauthorized: No token provided in authorization headers!', - }); - } - - // Validate the token - const { error } = await supabase.auth.getUser(token); - if (error) { +async function checkAuthentication() { + const supabase = await createClient(); + const { data, error } = await supabase.auth.getUser(); + if (error || !data?.user) { return Response.json({ - error: "Unauthorized: Couldn't decode the token correctly!", + error: 'Unauthenticated: User must be logged in', }); } } @@ -80,7 +70,7 @@ function extractAddressAndTown(googleResponse: any) { export async function POST(request: NextRequest) { // will return Response object on error - const response = await checkAuthentication(request); + const response = await checkAuthentication(); if (response) { return response; } diff --git a/src/lib/service.ts b/src/lib/service.ts index 7894735..ccdd9c2 100644 --- a/src/lib/service.ts +++ b/src/lib/service.ts @@ -194,10 +194,10 @@ export const helpRequestService = { export const locationService = { // if token is not provided it will get it from session - async getFormattedAddress(longitude: string, latitude: string, token: string) { + async getFormattedAddress(longitude: string, latitude: string) { return await fetch('/api/address', { method: 'POST', - headers: { 'Content-Type': 'application/json', authorization: `Bearer ${token}` }, + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ longitude, latitude,