Skip to content

Commit

Permalink
fixed all code to work with nextauth only
Browse files Browse the repository at this point in the history
  • Loading branch information
Tabish1511 committed Dec 19, 2024
1 parent 614e409 commit 59b5a8f
Show file tree
Hide file tree
Showing 7 changed files with 148 additions and 35 deletions.
3 changes: 1 addition & 2 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ app.use(cors({
callback(new Error('Not allowed by CORS'));
}
},
methods: 'GET,POST,PUT,DELETE',
credentials: true, // Keep it for cross-origin credential sharing if needed
methods: 'GET,POST,PUT,DELETE'
}));

// Setup routes
Expand Down
10 changes: 8 additions & 2 deletions apps/api/src/routes/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,14 @@ messageRouter.get('/test', (req, res) => {

messageRouter.get('/messages', async (req, res) => {
try {
// Fetch all messages (no authentication needed)
const messages = await prisma.message.findMany();
const userId = parseInt(req.query.userId as string, 10);
if (isNaN(userId)) {
return res.status(400).send("Invalid user ID");
}

const messages = await prisma.message.findMany({
where: { userId: userId },
});

console.log("Messages fetched successfully");
res.status(200).json(messages);
Expand Down
39 changes: 20 additions & 19 deletions apps/web/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";
import { PrismaClient } from "@prisma/client";

const baseEndpoint = process.env.NEXT_PUBLIC_API_URL as string;
const prisma = new PrismaClient();

const handler = NextAuth({
providers: [
Expand All @@ -14,24 +16,15 @@ const handler = NextAuth({
},
async authorize(credentials: any) {
try {
console.log("'CREDS' CODE REACHED BEFORE THE SIGNIN AXIOS REQ");
const user = await prisma.user.findUnique({
where: { email: credentials.email },
});

const response = await axios.post(
`${baseEndpoint}/api/v1/user/signin`,
{
email: credentials.email,
password: credentials.password,
});

console.log("'CREDS' CODE REACHED AFTER THE SIGNIN AXIOS REQ");

const user = response.data;

if (!user || !user.id || !user.email) {
throw new Error("Invalid user data received from the server.");
if(user && user.password === credentials.password){
return { id: user.id.toString(), email: user.email }
}

return { id: user.id, email: user.email };
return null;
} catch (error: any) {
console.error("Authorization error:", error);
throw new Error(error.response?.data?.message || "Authorization failed.");
Expand All @@ -41,10 +34,18 @@ const handler = NextAuth({
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async redirect({ baseUrl }) {
console.log("CALLBACK RUNNING");
return `${baseUrl}/chat`;
},
jwt: async ({ user, token }: any) => {
if (user) {
token.uid = token.sub;
}
return token;
},
session: ({ session, token, user }: any) => {
if (session.user) {
session.user.id = token.sub;
}
return session
}
},
});

Expand Down
4 changes: 3 additions & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@
"private": true,
"scripts": {
"dev": "next dev --turbo",
"build": "next build",
"build": "next build && npx prisma generate",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@prisma/client": "^6.1.0",
"@repo/ui": "*",
"@types/js-cookie": "^3.0.6",
"js-cookie": "^3.0.5",
"next": "15.0.0-rc.0",
"next-auth": "^4.24.7",
"prisma": "^6.1.0",
"react": "19.0.0-rc-f994737d14-20240522",
"react-dom": "19.0.0-rc-f994737d14-20240522"
},
Expand Down
29 changes: 29 additions & 0 deletions apps/web/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model User {
id Int @id @default(autoincrement()) // Unique identifier for each user.
email String @unique // Email address (must be unique).
password String // User's password.
messages Message[] // One-to-many relationship with Message.
}

model Message {
id Int @id @default(autoincrement()) // Unique identifier for each message.
content String // Message content.
createdAt DateTime @default(now()) // Timestamp for message creation.
userId Int? @default(1) // Foreign key referencing User.
user User? @relation(fields: [userId], references: [id]) // Relationship with User.
}
78 changes: 77 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 10 additions & 10 deletions packages/ui/src/chatComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import axios from "axios";
import Cookies from "js-cookie";
import { useRouter } from "next/navigation";
import { AllMessagesComponent } from "@repo/ui/allMessagesComponent";
import { useSession } from 'next-auth/react';

export default function ChatComponent() {
const [socket, setSocket] = useState<WebSocket | null>(null);
Expand All @@ -14,22 +15,20 @@ export default function ChatComponent() {
const baseEndpoint = process.env.NEXT_PUBLIC_API_URL as string;
const inputRef = useRef<HTMLInputElement>(null);
const router = useRouter();
const { data: session } = useSession();

useEffect(() => {
// const token = Cookies.get("token");

// if (!token) {
// console.log("NO TOKEN FOUND FROM /CHAT");
// router.push("/");
// return;
// }

const fetchMessages = async () => {
try {
//@ts-ignore
const userId = session?.user?.id;
if(!userId){
throw new Error("UserId not available in session");
}

const messagesResponse = await axios.get(
`${baseEndpoint}/api/v1/message/messages`,
{ withCredentials: true }
);
`${baseEndpoint}/api/v1/message/messages?userId=${userId}`);
const prevMessages = messagesResponse.data.map(
(message: any) => message.content
);
Expand Down Expand Up @@ -71,6 +70,7 @@ export default function ChatComponent() {

return (
<div className="h-screen flex justify-center">
{session?.user?.email}
<div className="w-2/6 flex flex-col justify-center">
<AllMessagesComponent messagesObject={allMessages} />
<div className="flex justify-center">
Expand Down

0 comments on commit 59b5a8f

Please sign in to comment.