Skip to content

Commit

Permalink
Merge pull request #57 from FacundoInza/feat/set-user
Browse files Browse the repository at this point in the history
feat: Middleware without user/me
  • Loading branch information
FacundoInza authored Sep 22, 2023
2 parents 8a25b66 + 70a9fa1 commit 8b4e198
Show file tree
Hide file tree
Showing 17 changed files with 2,405 additions and 79 deletions.
3 changes: 2 additions & 1 deletion adapters/deliveryAdapters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { FilterDelivery, IDelivery, ResponsePaginated } from '@/interfaces';

export async function getDeliveries({
status,
userId,
}: FilterDelivery): Promise<ResponsePaginated<IDelivery>> {
const response = await axiosInstance.get(
`/api/delivery/all?status=${status}`
`/api/delivery/all?status=${status}&userId=${userId}`
);

if (response.status !== 200) {
Expand Down
14 changes: 14 additions & 0 deletions adapters/userAdapters.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { axiosInstance } from '@/interceptors';
import { validateToken } from '@/utils';
import { cookies } from 'next/dist/client/components/headers';

export async function userAuth() {
const response = await axiosInstance.post('/api/user/me');
Expand All @@ -9,3 +11,15 @@ export async function userAuth() {

return response.data;
}

export async function getUser() {
const token = cookies().get('token');

const payload = await validateToken(token?.value as string);

if (!payload) {
throw new Error('No se pudo obtener el token');
}

return payload.user;
}
3 changes: 2 additions & 1 deletion api/axiosInstance.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import currentEnv from '@/config';
import axios from 'axios';

export const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_BASE_URL,
baseURL: currentEnv.BASE_URL,
headers: {
'Content-Type': 'application/json',
},
Expand Down
7 changes: 5 additions & 2 deletions app/dealer/home/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ import React, { FC } from 'react';
import { DropdownCard } from '@/components/ui/cards/DropdownCard';
import MainButton from '@/components/commons/buttons/MainButton';
import { DeliveryList } from '@/components/ui/lists';
import { getDeliveries } from '@/adapters';
import { getDeliveries, getUser } from '@/adapters';
import { IDelivery, ResponsePaginated } from '@/interfaces';

const Home: FC = async () => {
const user = await getUser();

let res: ResponsePaginated<IDelivery> = await getDeliveries({
status: 'pending',
userId: user.id,
});
const pendingDeliveries = res.data;
const pendingTotalItems = res.totalItems;
res = await getDeliveries({ status: 'delivered' });
res = await getDeliveries({ status: 'delivered', userId: user.id });

const deliveredDeliveries = res.data;
const deliveredTotalItems = res.totalItems;
Expand Down
7 changes: 6 additions & 1 deletion components/ui/forms/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import { api } from '../../../api/axiosInstance';
import { useRouter } from 'next/navigation';
import Notification from '../modal/Notification';
import { setCookie } from 'cookies-next';
import { useDispatch } from 'react-redux';
import { setUser } from '@/redux/features/user/userSlice';

interface FormInputs {
email: string;
Expand Down Expand Up @@ -50,7 +52,7 @@ export const LoginForm: FC = () => {
handleSubmit,
formState: { errors },
} = useForm<FormInputs>({ mode: 'onBlur' });

const dispatch = useDispatch();
const [showPassword, setShowPassword] = useState(false);
const [showModal, setShowModal] = useState(false);
const [modalMessage, setModalMessage] = useState('');
Expand All @@ -62,9 +64,12 @@ export const LoginForm: FC = () => {
const response = await loginUser(data);

setModalMessage(`${response.message}...Setting up deliveries...`);

setIsModalSuccess(true);
setShowModal(true);

dispatch(setUser(response.data));

setTimeout(() => {
router.push('/auth/home');
}, 2000);
Expand Down
6 changes: 6 additions & 0 deletions config/development.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default {
NODE_ENV: process.env.NODE_ENV || 'development',
PORT: process.env.PORT || 3000,
BASE_URL: process.env.DELIVERIT_API_BASE_URL || 'http://localhost:5000',
ACCESS_TOKEN_SECRET: process.env.ACCESS_TOKEN_SECRET || 'mysecrettoken',
};
12 changes: 12 additions & 0 deletions config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import DEVELOPMENT from './development';
import PRODUCTION from './production';

const { NODE_ENV } = process.env;

let currentEnv = DEVELOPMENT;

if (NODE_ENV === 'production') {
currentEnv = PRODUCTION;
}

export default currentEnv;
6 changes: 6 additions & 0 deletions config/production.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default {
NODE_ENV: process.env.NODE_ENV || 'production',
PORT: process.env.PORT || 3000,
BASE_URL: process.env.DELIVERIT_API_BASE_URL || 'http://deliverit.tech',
ACCESS_TOKEN_SECRET: process.env.ACCESS_TOKEN_SECRET || 'mysecrettoken',
};
2 changes: 1 addition & 1 deletion interceptors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function handleNetworkErrors(error: Error) {

// Configuración de Axios con los interceptores
export const axiosInstance = axios.create({
baseURL: process.env.NEXT_PUBLIC_BASE_URL,
baseURL: process.env.DELIVERIT_API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
Expand Down
1 change: 1 addition & 0 deletions interfaces/IDelivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ export interface OrderID {

export interface FilterDelivery {
status: string;
userId: string;
}
7 changes: 7 additions & 0 deletions interfaces/IPayload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { IUser } from './IUser';

export interface IPayload {
user: IUser;
iat: number;
exp: number;
}
17 changes: 4 additions & 13 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,18 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { validateToken } from './utils';

export async function middleware(request: NextRequest) {
const token = request.cookies.get('token');

if (token) {
const res = await fetch('http://localhost:5000/api/user/me', {
headers: {
Authorization: `Bearer ${token?.value}`,
},
});
const payload = await validateToken(token.value);

if (
request.nextUrl.pathname.startsWith('/auth') &&
res.status === 200
) {
if (request.nextUrl.pathname.startsWith('/auth') && payload) {
return NextResponse.redirect(new URL('/dealer/home', request.url));
}

if (
request.nextUrl.pathname.startsWith('/dealer') &&
res.status !== 200
) {
if (request.nextUrl.pathname.startsWith('/dealer') && !payload) {
return NextResponse.redirect(new URL('/auth', request.url));
}
} else {
Expand Down
Loading

0 comments on commit 8b4e198

Please sign in to comment.