Skip to content

Commit

Permalink
feat: authed request address
Browse files Browse the repository at this point in the history
  • Loading branch information
Roberto Milla Martinez committed Nov 9, 2024
1 parent 342013d commit 8f60af2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 19 deletions.
24 changes: 7 additions & 17 deletions src/app/api/address/route.ts
Original file line number Diff line number Diff line change
@@ -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',
Expand All @@ -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',
});
}
}
Expand Down Expand Up @@ -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;
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 8f60af2

Please sign in to comment.