Skip to content
Merged
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ Calculus visualizer for UCF Knight Hacks. A website with interactive graphs for

## Learn useful git commands
Check out the GIT_COMMANDS.md file. It has all the git commands a beginner (or veteran) should know.

## Make changes here to trigger deployment

change b
18 changes: 9 additions & 9 deletions calc-backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

generator client {
provider = "prisma-client-js"
output = "./client"
output = "./client"
}

datasource db {
Expand Down Expand Up @@ -65,14 +65,14 @@ model Account {
}

model Verification {
id String @id @default(cuid()) @map("_id")
identifier String
value String
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("verification")
id String @id @default(cuid()) @map("_id")
identifier String
value String
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

@@map("verification")
}

model Func {
Expand Down
9 changes: 1 addition & 8 deletions calc-backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import express from "express";
import cors from "cors";
import routes from "./server.routes";
import errorMiddleware from "./middlewares/errorHandler.middleware";
import { toNodeHandler, fromNodeHeaders} from "better-auth/node";
import { toNodeHandler } from "better-auth/node";
import { auth } from "./lib/auth";

const PORT = process.env.PORT || 3000;
Expand All @@ -18,13 +18,6 @@ app.use(cors({

app.all("/api/auth/*", toNodeHandler(auth));

app.get("/api/session", async (req, res) => {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});
return res.json(session);
});

app.use(express.json()) // use this after better auth

// Prefixes the endpoint with /
Expand Down
26 changes: 16 additions & 10 deletions calc-backend/src/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
import { betterAuth, BetterAuthOptions } from "better-auth";
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import prisma from "./prisma";

export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "mongodb",
}),
trustedOrigins: ["http://localhost:5173", 'https://calcvisualizer.netlify.app'],
trustedOrigins: ["http://localhost:5173",
"https://calcvisualizer.speedrunyourknowledge.com",
"https://calcvisualizer.netlify.app"
],
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
}
},
session: {
cookieCache: {
enabled: true,
maxAge: 60 * 60 // Cache duration in seconds
}
},
advanced: {
cookiePrefix: "calcvis"
crossSubDomainCookies: {
enabled: true,
domain: ".speedrunyourknowledge.com", // Domain with a leading period
},
defaultCookieAttributes: {
secure: true,
httpOnly: true,
sameSite: "none", // Allows CORS-based cookie sharing across subdomains
partitioned: true, // New browser standards will mandate this for foreign cookies
},
},
onAPIError: {
throw: true,
Expand All @@ -29,4 +35,4 @@ export const auth = betterAuth({
},
errorURL: process.env.FRONTEND_URL || 'http://localhost:5173' + '/auth-error'
}
} satisfies BetterAuthOptions);
});
3 changes: 2 additions & 1 deletion calc-frontend/src/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ function App() {
// Handles all the routes
// The calc-visualizer path is for github pages
const router = createBrowserRouter(
createRoutesFromElements(RoutesList));
createRoutesFromElements(RoutesList)
);

return (
<>
Expand Down
32 changes: 5 additions & 27 deletions calc-frontend/src/App/RootLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,13 @@ import CalcLogo from "../components/CalcLogo"

import { authClient } from "../lib/auth-client";
import { Avatar, AvatarFallback, AvatarImage } from "../components/ui/avatar"
import { useEffect } from "react";
import axios from "axios";

function RootLayout() {

const serverUrl = import.meta.env.VITE_SERVER_URL || 'http://localhost:3000'

const session = authClient.useSession();


const requestSession = async () => {

try{
const response = await axios.get(serverUrl + '/api/session', { withCredentials: true })

console.log(response)
}
catch(e){
console.error("session error: ", e)
}
}

useEffect(() => {

requestSession()

}, [])


console.log('useSession: ' + session.data)

return (
<>
<ScrollRestoration />
Expand All @@ -54,11 +32,11 @@ function RootLayout() {

</div>
{session.data?.session ? (
session.data?.user.image ? (
session.data.user.image ? (
<Link to="/dashboard">
<Avatar className="mr-5 cursor-pointer w-12 h-12">
<AvatarImage src={session.data?.user.image} />
<AvatarFallback>{session.data?.user.name.charAt(0)}</AvatarFallback>
<AvatarImage src={session.data.user.image} />
<AvatarFallback>{session.data.user.name.charAt(0)}</AvatarFallback>
</Avatar>
</Link>
) : (
Expand Down
1 change: 0 additions & 1 deletion calc-frontend/src/components/Custom/DerivCustomGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ function DerivCustomGraph({func, lowerBound, upperBound, handleSave, onAIRespons
'upperBound': upperBound

}
// { withCredentials:true}
)

// add loading circle when ready is false
Expand Down
1 change: 0 additions & 1 deletion calc-frontend/src/components/Custom/IntCustomGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ function IntCustomGraph({func, lowerBound, upperBound, handleSave, onAIResponseC
'upperBound': upperBound

}
// { withCredentials:true}
)

// add loading circle when ready is false
Expand Down
16 changes: 3 additions & 13 deletions calc-frontend/src/components/ui/SaveFunctionButton.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
import { useNavigate } from "react-router";
import { authClient } from "../../lib/auth-client";
import { Session } from "../../lib/auth-client";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TooltipArrow } from "@radix-ui/react-tooltip";


function SaveFunctionButton({onSave, saving, enableSave}: {onSave: (session: Session) => void,
function SaveFunctionButton({onSave, saving, enableSave}: {onSave: () => void,
saving: boolean, enableSave: boolean})
{
const navigate = useNavigate();
const session = authClient.useSession();

const handleClick = () => {
if(!session.data?.session ) {
navigate("/sign-in");
return;
}
onSave(session.data);

onSave();
}

if(saving){
Expand Down
17 changes: 12 additions & 5 deletions calc-frontend/src/components/ui/SignOutButton.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import { toast } from "sonner";
import { authClient } from "../../lib/auth-client"
import { useNavigate } from "react-router";

function SignOutButton()
{
const navigate = useNavigate()

const handleSignOut = async () => {
try {
await authClient.signOut();

await authClient.signOut({
fetchOptions: {
onSuccess: () => {
navigate("/"); // redirect to home
},
withCredentials:true
}
});
} catch (error) {
toast.error("Something went wrong signing out");
console.error("Error signing out:", error);
console.error("Error signing out: ", error);
}
}

Expand Down
17 changes: 9 additions & 8 deletions calc-frontend/src/pages/CustomDerivative.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { useLocation } from "react-router"
import {generateFunction, validateBounds} from "../functions/mathOutput";
import DerivCustomGraph from "../components/Custom/DerivCustomGraph";

import { Session } from "../lib/auth-client.ts";
import axios from "axios";
import SaveFunctionButton from "../components/ui/SaveFunctionButton.tsx";
import AskAIButtonDerivative from "@/components/ui/AskAIButtonDerivative.tsx";
import { toast } from "sonner";
import { authClient } from "../lib/auth-client";

function CustomDeriv() {

Expand All @@ -26,6 +26,8 @@ function CustomDeriv() {
state = {func: 'x^2', bounds: [0, 5]}
}

const session = authClient.useSession();

const container = useRef<HTMLDivElement>(null);
const MQ = useRef<any>(null);
const containerMF = useRef<any>(null);
Expand Down Expand Up @@ -55,7 +57,7 @@ function CustomDeriv() {
}

// need to check if func is unique first
const saveFunction = async (session: Session) => {
const saveFunction = async () => {

// check if function has been graphed
if(func === ''){
Expand All @@ -68,7 +70,7 @@ function CustomDeriv() {
const lowerBound = bounds[0];
const upperBound = bounds[1];
const topic = "Derivative";
const userId = session.user.id;
const userId = session.data?.user.id;

try {
setSaving(true) // show loading while saving
Expand All @@ -79,11 +81,10 @@ function CustomDeriv() {
lowerBound,
upperBound,
topic,
},{
headers: {
Authorization: `Bearer ${session.session.token}`
}
})
},
{ withCredentials:true}
)

toast.success("Function Saved Successfully!");
}
catch (error) {
Expand Down
16 changes: 8 additions & 8 deletions calc-frontend/src/pages/CustomIntegral.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { useLocation } from "react-router"
import IntCustomGraph from "../components/Custom/IntCustomGraph.tsx"
import {generateFunction, validateBounds} from "../functions/mathOutput";

import { Session } from "../lib/auth-client.ts";
import axios from "axios";
import SaveFunctionButton from "../components/ui/SaveFunctionButton.tsx";
import AskAIButton from "../components/ui/AskAIButtonIntegral.tsx";

import { toast } from "sonner";
import { authClient } from "../lib/auth-client";

function CustomInt() {

Expand All @@ -27,6 +27,8 @@ function CustomInt() {
state = {func: 'x^2', bounds: [0, 5]}
}

const session = authClient.useSession();

const container = useRef<HTMLDivElement>(null);
const MQ = useRef<any>(null);
const containerMF = useRef<any>(null);
Expand Down Expand Up @@ -57,7 +59,7 @@ function CustomInt() {
}

// need to check if func is unique first
const saveFunction = async (session: Session) => {
const saveFunction = async () => {

// check if function has been graphed
if(func === ''){
Expand All @@ -70,7 +72,7 @@ function CustomInt() {
const lowerBound = bounds[0];
const upperBound = bounds[1];
const topic = "Integral";
const userId = session.user.id;
const userId = session.data?.user.id;

try {
setSaving(true) // show loading while saving
Expand All @@ -80,11 +82,9 @@ function CustomInt() {
lowerBound,
upperBound,
topic,
},{
headers: {
Authorization: `Bearer ${session.session.token}`
}
})
},
{ withCredentials:true}
)

toast.success("Function Saved Successfully!");
}
Expand Down
2 changes: 1 addition & 1 deletion calc-frontend/src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ function Home() {
{session.isPending === true?
null
:
!session.data?.session ? <SignInButton/> : <SignOutButton/>
session.data?.session ? <SignOutButton/> : <SignInButton/>
}
</div>

Expand Down