Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ export default function Navbar() {
{session ? (
<>
<span>Welcome, {session.user.name}</span>
<button onClick={() => signOut()}>Signout</button>
<button onClick={() => signOut()}>Signout</button>;
</>
) :
(
<button onClick={() => signIn()}>Sign In</button>
<button onClick={() => signIn()}>Sign In</button>;
)}
</nav>
)
}
}
4 changes: 2 additions & 2 deletions lib/ratelimit.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ export const ratelimit = new Ratelimit({
* - reset (unix timestamp when the window resets)
*/
export async function checkRateLimit(identifier) {
if (!identifier) identifier = "anon";
if (!identifier) return { success: false, limit: 0, remaining: 0, reset: 0 };
return await ratelimit.limit(identifier);
}
}
6 changes: 3 additions & 3 deletions pages/_app.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { SessionProvider } from "next-auth/react"
import { SessionProvider } from "next-auth/react";
import Head from 'next/head'
import '../styles/globals.css'


export default function app({
export default function App({
Component, pageProps: { session, ...pageProps }
}) {
return (
Expand All @@ -24,4 +24,4 @@ export default function app({
<Component {...pageProps} />
</SessionProvider>
)
}
}
23 changes: 11 additions & 12 deletions pages/api/auth/[...nextauth].js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import CredentialsProvider from "next-auth/providers/credentials";
import connectDb from '../../../lib/mongoDb';
import User from '../../../model/User';
import bcrypt from "bcryptjs";
import dotenv from "dotenv"
// import dotenv from "dotenv"
// import EmailProvider from 'next-auth/providers/email'
dotenv.config();

export const authOptions = {
secret: process.env.NEXTAUTH_SECRET || "your-secret-key-min-32-characters-long-for-development",
Expand Down Expand Up @@ -36,15 +35,15 @@ export const authOptions = {
},
async authorize(credentials) {
try {
console.log("=== Credentials Login Attempt ===");
console.log("Email:", credentials.email);
// console.log("=== Credentials Login Attempt ===");
// console.log("Email:", credentials.email);

await connectDb();
let user = await User.findOne({ email: credentials.email });

if (!user) {
// Register a new User
console.log("Creating new user:", credentials.email);
// console.log("Creating new user:", credentials.email);
const hashedPassword = await bcrypt.hash(credentials.password, 10);
user = await User.create({
name: credentials.name,
Expand All @@ -53,7 +52,7 @@ export const authOptions = {
provider: "credentials"
});

console.log("New user created successfully");
// console.log("New user created successfully");

// Return the newly created user
return {
Expand All @@ -66,21 +65,21 @@ export const authOptions = {
}
else {
// Login: compare password
console.log("User found, verifying password");
// console.log("User found, verifying password");

// Check if user has a password (OAuth users won't have one)
if (!user.password) {
console.log("User registered via OAuth, no password set");
// console.log("User registered via OAuth, no password set");
return null;
}

const valid = await bcrypt.compare(credentials.password, user.password);
if (!valid) {
console.log("Invalid password for user:", credentials.email);
// console.log("Invalid password for user:", credentials.email);
return null;
}

console.log("Login successful for:", credentials.email);
// console.log("Login successful for:", credentials.email);
return {
id: user._id.toString(),
name: user.name,
Expand All @@ -101,7 +100,7 @@ export const authOptions = {
async signIn({ user, account}) {
// Only handle OAuth providers (Google, GitHub, Twitter)
// Skip credentials provider as user is already created in authorize()
if (account.provider !== "credentials") {
if (account && account.provider !== "credentials") {
await connectDb();
const existing = await User.findOne({ email: user.email });

Expand Down Expand Up @@ -139,4 +138,4 @@ export const authOptions = {
}
}

export default NextAuth(authOptions)
export default NextAuth(authOptions)
7 changes: 2 additions & 5 deletions pages/api/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,9 @@ const generateAnswerWithGemini = async (question, contextChunks, retries = 3) =>
});

const data = await res.json();
console.log('Gemini API Response:', JSON.stringify(data, null, 2));


if (!res.ok) {
console.error('API Error Response:', data);
// If 503 error (overloaded) and retries remaining, wait and retry
if (res.status === 503 && retries > 0) {
await new Promise(resolve => setTimeout(resolve, 1000));
Expand All @@ -95,7 +94,7 @@ const generateAnswerWithGemini = async (question, contextChunks, retries = 3) =>
}
}

console.log('No valid response structure found, full data:', data);

return "No answer generated. Please try again.";

} catch (error) {
Expand Down Expand Up @@ -156,5 +155,3 @@ const handleAnswer = async (req, res) => {
}

export default handleAnswer;


11 changes: 7 additions & 4 deletions pages/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default function ChatPage() {
const data = await res.json();
if (res.ok && data.messages) setMessages(data.messages);
} catch (error) {
console.error("Error loading chat history:", error);
// console.error("Error loading chat history:", error);
Comment on lines 43 to +44
} finally {
setLoadingHistory(false);
}
Expand All @@ -66,7 +66,9 @@ export default function ChatPage() {
? "Invalid email or password. Please try again."
: "An error occurred during sign in. Please try again."
);
} else if (result?.ok) setError("");
} else {
setError("");
}
}

async function handleOAuthSignIn(provider) {
Expand Down Expand Up @@ -226,7 +228,8 @@ export default function ChatPage() {
: data.error || "Sorry, something went wrong.",
},
]);
} catch {
} catch (error) {
// console.error("An error occurred:", error);
Comment on lines +231 to +232
setMessages((prev) => [
...prev,
{ role: "bot", content: "Network error. Try again later." },
Expand All @@ -250,7 +253,7 @@ export default function ChatPage() {
</h1>
</a>
<p className="text-xs text-[#5A4E4A]">
Welcome, {session.user.name.split(" ")[0]}
Welcome, {session?.user?.name?.split(" ")[0]}
</p>
</div>
</div>
Expand Down
31 changes: 18 additions & 13 deletions scripts/chunkText.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,22 @@ const chunkText = (text, chunkSize = 300) => {
}


for (const file of fs.readdirSync('./data')) {
if(file.startsWith("chunks-")||file.startsWith("embed-")){
continue;
async function processFiles() {
const files = await fs.promises.readdir('./data');
for (const file of files) {
if (file.startsWith("chunks-") || file.startsWith("embed-")) {
continue;
}
const filePath = path.join('./data', file);
const text = await fs.promises.readFile(filePath, 'utf-8');
const chunks = chunkText(text);
await fs.promises.writeFile(
`./data/chunks-${file}`,
JSON.stringify(chunks, null, 2),
'utf-8'
);
console.log(`Chunked ${file} into ${chunks.length} chunks`);
}
const filePath = path.join('./data', file);
const text = fs.readFileSync(filePath, 'utf-8')
const chunks = chunkText(text);
fs.writeFileSync(
`./data/chunks-${file}`,
JSON.stringify(chunks, null, 2),
'utf-8'
);
console.log(`Chunked ${file} into ${chunks.length} chunks`);
}
}

processFiles();