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
34 changes: 31 additions & 3 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,48 @@
import jwt from "jsonwebtoken";
import prisma from "../lib/prisma.js";
import { success } from "zod";

const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";

export const authenticateToken = async (req, res, next) => {
try {
// TODO: Implement the authentication middleware
// 1. Get the token from the request header
const token = req.headers["authorization"]?.split(" ")[1];
if (!token) {
return res.status(401).json({
success: false,
message: "No token provided",
});
}
// 2. Verify the token
const decoded = jwt.verify(token, JWT_SECRET);

// 3. Get the user from the database
const user = await prisma.user.findUnique({
where: { id: decoded.userId },
select: {
id: true,
name: true,
email: true,
role: true
}
})
if (!user) {
return res.status(401).json({
success: false,
message: "No student found."
})
}
// 4. If the user doesn't exist, throw an error
// 5. Attach the user to the request object
req.user = user;
req.role = user.role;
// 6. Call the next middleware



next();
} catch (error) {
console.error("Authentication error:", error);

if (error.name === "JsonWebTokenError") {
return res.status(401).json({
success: false,
Expand All @@ -33,6 +60,7 @@ export const authenticateToken = async (req, res, next) => {
return res.status(500).json({
success: false,
message: "Authentication error",
error: error.message
});
}
};
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2"
"jsonwebtoken": "^9.0.2",
"openai": "^6.10.0",
"zod": "^4.1.13"
},
"devDependencies": {
"nodemon": "^3.0.1",
Expand Down
14 changes: 13 additions & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,19 @@ datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model AI{
id String @id @default(cuid())
input String
output String
createdAt DateTime @default(now())
@@map("AIGeneratedTable")
}

model User {
id String @id @default(cuid())
email String @unique
password String
role Roles
name String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand Down Expand Up @@ -64,4 +72,8 @@ enum Priority {
medium
high
urgent
}
}
enum Roles {
ADMIN
user
}
9 changes: 9 additions & 0 deletions routes/AIPlatform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import OpenAI from "openai";
const OPENAI_KEY = process.env.OPENAI_KEY || "your-openai-key";


const client = new OpenAI({
apiKey: OPENAI_KEY,
});

export { client };
95 changes: 95 additions & 0 deletions routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import prisma from "../lib/prisma.js";
import { authenticateToken } from "../middleware/auth.js";
import { success } from "zod";
import { da, id } from "zod/v4/locales";
import bcryptjs from "bcryptjs";

const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";
Expand All @@ -11,12 +14,60 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";
router.post("/register", async (req, res) => {
try {
// TODO: Implement the registration logic
const { username, email, password, role} = req.body;
// 1. Validate the input
if (!username || !email || !password || !role) {
console.log("Missing fields:", { username, email, password, role});
return res.status(400).json({
success: false,
message: "Must provide username, email, password, and role."
})
}
// 2. Check if the user already exists
const user = await prisma.user.findUnique({
where:{
email: email,
}
})
if (user) {
return res.status(400).json({
success: false,
message: "User already exists."
})
}
// 3. Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// 4. Create the user
const newUser = await prisma.user.create({
data: {
name: username,
email,
password: hashedPassword,
role,
},
select: {
id: true,
name: true,
email: true,
role: true
}
})
// 5. Generate a JWT token
const token = jwt.sign(
{userId: newUser.id},
JWT_SECRET,
{expiresIn: "48h"}
)
// 6. Return the user data and token
res.status(201).json({
success: true,
message: "User has been created!",
data: {
newUser,
token
}
})




Expand All @@ -35,10 +86,54 @@ router.post("/login", async (req, res) => {
try {
// TODO: Implement the login logic
// 1. Validate the input
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({
success: false,
message: "Must provide email and password."
})
}
// 2. Check if the user exists
const user = await prisma.user.findUnique({
where: { email: email
},
select: {
id: true,
name: true,
email: true,
password: true,
role: true,
}
})
if (!user) {
return res.status(400).json({
success: false,
message: "No user could be found."
})
}
// 3. Compare the password
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
return res.status(400).json({
success: false,
message: "Invalid password."
})
}
// 4. Generate a JWT token
const token = jwt.sign(
{userId: user.id},
JWT_SECRET,
{expiresIn: "48h"}
)
// 5. Return the user data and token
res.status(200).json({
success: true,
message: "User has been verified. Welcome.",
data: {
user,
token
}
})


} catch (error) {
Expand Down
Loading