Skip to content

Commit

Permalink
Adding middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Aayush-Agnihotri committed Dec 21, 2024
1 parent ffb4ec4 commit 2d79d54
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 13 deletions.
6 changes: 0 additions & 6 deletions .prettierrc

This file was deleted.

6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/bui
curl -X POST "http://0.0.0.0:11434/api/pull" -d '{"model":"llama3.2:1b"}'
curl -X POST "http://0.0.0.0:11434/api/generate" -d '{"model":"llama3.2:1b", "prompt":"hello"}'

-H "Content-Type: application/json" \

curl -X POST "http://localhost:3000/api/models" \
-d '{"model":"llama3.2:1b", "messages": [{"role":"user", "content":"Hello"}]}' \
--verbose

curl -H "Origin: https://ai.cornellappdev.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: X-Requested-With" \
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
// import adminAuth from "../../firebase-admin-config";
import adminAuth from "../../../firebase-admin-config";

export async function POST(request: NextRequest) {
const body = await request.json();
Expand All @@ -10,9 +10,10 @@ export async function POST(request: NextRequest) {
}

try {
// const firebaseUser = await adminAuth.verifyIdToken(token);
const firebaseUser = await adminAuth.verifyIdToken(token);

// TODO: Check if in database or special user
console.log(firebaseUser);
// const uid = firebaseUser.uid;
// return NextResponse.json('You must be part of Cornell AppDev to use this app', { status: 403 });

Expand Down
8 changes: 7 additions & 1 deletion src/app/chat/[chatId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import InputField from '@/app/components/InputField';
import ChatMessage from '@/app/components/chat/ChatMessage';

export default function ChatPage() {
const { user } = useAuth();
const { user, idToken, refreshToken } = useAuth();
const { selectedModel } = useModel();
const [isNavbarOpen, setIsNavbarOpen] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
Expand Down Expand Up @@ -81,9 +81,15 @@ export default function ChatPage() {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${idToken}`,
},
body: JSON.stringify(body),
});

if (response.status === 401) {
await refreshToken();
return fetchChatResponse(body);
}

if (!response.ok || !response.body) {
const data = await response.json();
Expand Down
16 changes: 14 additions & 2 deletions src/app/components/modals/ModelModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
PullModelRequest,
PullModelResponse,
} from '@/types/model';
import { useAuth } from '@/contexts/AuthContext';
import { useState, useRef } from 'react';
import Spinner from '../Spinner';

Expand All @@ -27,6 +28,7 @@ const tabOptions: TabOptionConfig[] = [
];

export default function ModelModal({ loading, setLoading }: ModelModalProps) {
const { idToken, refreshToken } = useAuth();
const [activeTab, setActiveTab] = useState<TabOption>('create');
const [success, setSuccess] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
Expand Down Expand Up @@ -60,11 +62,16 @@ export default function ModelModal({ loading, setLoading }: ModelModalProps) {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// TODO: Add Authorization header with token
Authorization: `Bearer ${idToken}`,
},
body: JSON.stringify(body),
});

if (initialResponse.status === 401) {
await refreshToken();
return sendStreamedRequest(body);
}

if (!initialResponse.ok || !initialResponse.body) {
const data = await initialResponse.json();
throw new Error(data.error || `Failed to ${activeTab} the model.`);
Expand Down Expand Up @@ -138,11 +145,16 @@ export default function ModelModal({ loading, setLoading }: ModelModalProps) {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
// TODO: Add Authorization header with token
Authorization: `Bearer ${idToken}`,
},
body: JSON.stringify(body),
});

if (response.status === 401) {
await refreshToken();
return sendDeleteRequest(body);
}

if (!response.ok) {
const data = await response.json();
throw new Error(data.error || 'Failed to delete the model.');
Expand Down
4 changes: 3 additions & 1 deletion src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use client';

import {
createContext,
useContext,
Expand Down Expand Up @@ -95,7 +97,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {

const token = await currentUser.getIdToken();
try {
const response = await fetch('/api/users/authenticate', {
const response = await fetch('/api/authenticate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import * as admin from "firebase-admin";
import * as serviceAccount from "../firebase-service-account.json";

if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert("../../../firebase-service-account.json")
credential: admin.credential.cert(serviceAccount as admin.ServiceAccount)
});
}

Expand Down
32 changes: 32 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { NextRequest, NextResponse } from "next/server";
// import adminAuth from "./firebase-admin-config";

export async function middleware(request: NextRequest) {
try {
const authHeader = request.headers.get('Authorization');
if (!authHeader) {
throw new Error('Authorization header is required');
}

const token = authHeader.split('Bearer ')[1];
if (!token) {
throw new Error('Bearer token is required');
}

// const firebaseUser = await adminAuth.verifyIdToken(token);
// console.log(firebaseUser);
// if (!firebaseUser) {
// return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
// }

// Check if uid in database or special user

return NextResponse.next();
} catch (error) {
return NextResponse.json({ error: (error as Error).message }, { status: 400 });
}
}

export const config = {
matcher: ['/api/models', '/api/models/copy', '/api/models/create', '/api/models/pull', '/api/users/:path', '/api/embed'],
};

0 comments on commit 2d79d54

Please sign in to comment.