improved database updates for assignment creation

This commit is contained in:
JBB0807 2025-05-07 11:43:16 -07:00
parent fd993102a0
commit e2d728265b
8 changed files with 211 additions and 92 deletions

View file

@ -192,13 +192,17 @@ app.get("/assignments/appname/:appName", async (req, res) => {
app.put("/assignments/:id", async (req, res) => { app.put("/assignments/:id", async (req, res) => {
try { try {
const { id } = req.params; const { id } = req.params;
console.log("Updating assignment with ID:", id);
const assignment = await convertToAssignment(req); const assignment = await convertToAssignment(req);
console.log("Converted assignment object for update:", assignment);
const existingAssignment = await prisma.assignments.findUnique({ const existingAssignment = await prisma.assignments.findUnique({
where: { assignmentid: parseInt(id) }, where: { assignmentid: parseInt(id) },
}); });
if (!existingAssignment) { if (!existingAssignment) {
console.log("No existing assignment found for ID:", id);
return res.status(404).json({ message: "Assignment not found" }); return res.status(404).json({ message: "Assignment not found" });
} }
@ -216,6 +220,8 @@ app.put("/assignments/:id", async (req, res) => {
data: existingAssignment, data: existingAssignment,
}); });
console.log("Assignment updated successfully:", updatedAssignment);
res.json({ res.json({
message: "Assignment updated successfully", message: "Assignment updated successfully",
assignment: updatedAssignment, assignment: updatedAssignment,

View file

@ -29,12 +29,17 @@ intructorRouter.post(
return res.status(400).send("No file uploaded."); return res.status(400).send("No file uploaded.");
} }
//insert the initial assignment data into the database
console.log("Creating a new assignment with data:", req.body); console.log("Creating a new assignment with data:", req.body);
const response = await axios.post( const dbResponse = await axios.post(
`${DB_ASSIGNMENT_SERVICE_URL}/assignments`, `${DB_ASSIGNMENT_SERVICE_URL}/assignments`,
req.body req.body
); );
console.log("Response from DB_ASSIGNMENT_SERVICE_URL:", response.data);
const assignmentId = dbResponse.data.assignment.assignmentid;
console.log("Assignment created with ID:", assignmentId);
console.log("Response from DB_ASSIGNMENT_SERVICE_URL:", dbResponse.data);
// call upload api to upload the file to S3 // call upload api to upload the file to S3
console.log("Uploading file to:", `${DEPLOY_API_URL}/${assignmentData.appname}/upload`); console.log("Uploading file to:", `${DEPLOY_API_URL}/${assignmentData.appname}/upload`);
@ -53,9 +58,48 @@ intructorRouter.post(
}); });
console.log('Response from DEPLOY_API_URL:', deployResponse.data); console.log('Response from DEPLOY_API_URL:', deployResponse.data);
res.status(response.status).json(response.data); const ipv6 = deployResponse.data.ipv6;
console.log("Deployed Battlesnake API IPv6:", ipv6);
// Update the assignment with the deployment details
const updatedAssignmentData = {
assignmenturl: ipv6,
}
console.log("Updating assignment with deployment details:", updatedAssignmentData);
const updateRespone = await axios.put(
`${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}`,
updatedAssignmentData
);
console.log("Response from DB_ASSIGNMENT_SERVICE_URL:", updateRespone.data);
res.status(deployResponse.status).json(deployResponse.data);
} catch (error) { } catch (error) {
console.error("Error creating assignment:", error.message); console.error("Error creating assignment:", error.message);
//delete the file from s3 and the database if the assignment creation fails
try {
console.log("Deleting file from S3 due to error in assignment creation");
await axios.post(`${DEPLOY_API_URL}/${req.body.appname}/delete`, {
"appName": req.body.appname
});
console.log('Response from DEPLOY_API_URL:', error.response.data);
} catch (deleteError) {
console.error("Error deleting file from S3:", deleteError.message);
}
//delete the assignment from the database
try {
console.log("Deleting assignment from database due to error in assignment creation");
await axios.delete(
`${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}`
);
} catch (deleteError) {
console.error("Error deleting assignment from database:", deleteError.message);
}
//send the error response to the client
console.error("Error response from DB_ASSIGNMENT_SERVICE_URL:", error.response.data);
console.error("Error response status:", error.response.status);
res.status(error.response?.status || 500).json({ error: error.message }); res.status(error.response?.status || 500).json({ error: error.message });
} }
} }
@ -148,17 +192,20 @@ intructorRouter.delete(
} }
// Delete the Battlesnake API // Delete the Battlesnake API
console.log('Deploying a new Battlesnake API'); if(assignmentData.appname){
console.log("DEPLOY_API_URL:", DEPLOY_API_URL, assignmentData.appname); console.log(`Deleting Battlesnake API: ${assignmentData.appname}`);
const deployResponse = await axios.post(`${DEPLOY_API_URL}/${assignmentData.appname}/delete`, { console.log("DEPLOY_API_URL:", DEPLOY_API_URL, assignmentData.appname);
"appName": assignmentData.appname const deployResponse = await axios.post(`${DEPLOY_API_URL}/${assignmentData.appname}/delete`, {
}); "appName": assignmentData.appname
//throw error if the response is not 200 });
if (deployResponse.status !== 200) { //throw error if the response is not 200
throw new Error(`Failed to delete Battlesnake API: ${deployResponse.statusText}`); console.log('Response from DEPLOY_API_URL:', deployResponse.data);
if (deployResponse.status !== 200) {
throw new Error(`Failed to delete Battlesnake API: ${deployResponse.statusText}`);
}
console.log('Response from DEPLOY_API_URL:', deployResponse.data);
} }
console.log('Response from DEPLOY_API_URL:', deployResponse.data);
const response = await axios.delete( const response = await axios.delete(
`${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}` `${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}`
); );

View file

@ -2,10 +2,11 @@ GOOGLE_CLIENT_ID = "485880105639-1in8tvb6ondnn198rasuj2d8ank06ntp.apps.googleuse
GOOGLE_CLIENT_SECRET = "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" GOOGLE_CLIENT_SECRET = "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"
GOOGLE_CALLBACK_URL = "https://byte-camp-auth-service.fly.dev/auth/google/callback" GOOGLE_CALLBACK_URL = "https://byte-camp-auth-service.fly.dev/auth/google/callback"
LOGIN_REDIRECT_URL = "https://bytecamp-web.fly.dev/" LOGIN_REDIRECT_URL = "https://bytecamp-web.fly.dev/"
ACCEPTED_ORIGINS ="https://bytecamp-web.fly.dev,https://byte-camp-auth-service.fly.dev,http://localhost:5173" ACCEPTED_ORIGINS ="https://bytecamp-web.fly.dev,https://byte-camp-auth-service.fly.dev,https://bytecamp-web.fly.dev/"
#DB_USER_SERVICE_URL = "http://localhost:3000/" #DB_USER_SERVICE_URL = "http://localhost:3000/"
DB_USER_SERVICE_URL = "http://db-user-service.internal:3000/" DB_USER_SERVICE_URL = "http://db-user-service.internal:3000/"
AUTH_SESSION_KEY = "f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42" AUTH_SESSION_KEY = "f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42"
AUTH_URL = "https://byte-camp-auth-service.fly"
ASSIGNMENT_SERVICE_URL="http://assignment-service.internal:8080" ASSIGNMENT_SERVICE_URL="http://assignment-service.internal:8080"
# fly secrets set GOOGLE_CALLBACK_URL=https://byte-camp-auth-service.fly.dev/auth/google/callback # fly secrets set GOOGLE_CALLBACK_URL=https://byte-camp-auth-service.fly.dev/auth/google/callback

View file

@ -8,4 +8,5 @@ ACCEPTED_ORIGINS=http://localhost:3000,http://localhost:8081,http://localhost:30
ASSIGNMENT_SERVICE_URL="http://localhost:8082" ASSIGNMENT_SERVICE_URL="http://localhost:8082"
DB_USER_SERVICE_URL="http://localhost:3100/" DB_USER_SERVICE_URL="http://localhost:3100/"
AUTH_SESSION_KEY="f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42" AUTH_SESSION_KEY="f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42"
AUTH_URL = "http://localhost:8080"
PORT=8080 PORT=8080

View file

@ -5,6 +5,8 @@ const passport = require("passport");
const CustomStrategy = require("passport-custom").Strategy; const CustomStrategy = require("passport-custom").Strategy;
const axios = require("axios"); const axios = require("axios");
passport.use( passport.use(
new GoogleStrategy( new GoogleStrategy(
{ {
@ -14,7 +16,11 @@ passport.use(
scope: ["profile", "email"], scope: ["profile", "email"],
}, },
function (accessToken, refreshToken, profile, callback) { function (accessToken, refreshToken, profile, callback) {
callback(null, {...profile, role: "instructor"}); // console.log("Google Strategy invoked");
// console.log("Access Token:", accessToken);
// console.log("Refresh Token:", refreshToken);
// console.log("Profile:", profile);
callback(null, { ...profile, role: "instructor" });
} }
) )
); );
@ -57,19 +63,19 @@ passport.use(
); );
passport.serializeUser((user, done) => { passport.serializeUser((user, done) => {
// done(null, user);
console.log("Serializing user:", user); console.log("Serializing user:", user);
// done(null, user);
done(null, { done(null, {
userId: user.qrcodenumber || user.id, userId: user.qrcodenumber || user.id,
displayName: user.studentname || user.displayName, displayName: user.studentname || user.displayName,
role: user.role, role: user.role,
emails: user.emails || "none", // emails: user.emails || "none",
}); });
}); });
passport.deserializeUser(async (user, done) => { passport.deserializeUser((user, done) => {
console.log("Deserializing user:", user);
try { try {
console.log("Deserializing user:", user);
done(null, user); done(null, user);
} catch (err) { } catch (err) {
console.error("Error during deserialization:", err); console.error("Error during deserialization:", err);

View file

@ -2,12 +2,43 @@ const router = require("express").Router();
const passport = require("passport"); const passport = require("passport");
const axios = require("axios"); const axios = require("axios");
const AUTH_URL = process.env.AUTH_URL || "http://localhost:8080";
router.get( router.get(
"/google/callback", "/google/callback",
passport.authenticate("google", { passport.authenticate("google", {
successRedirect: "/auth/google/login",
failureRedirect: "/auth/login/failed", failureRedirect: "/auth/login/failed",
}) keepSessionInfo: true,
}),
async (req, res) => {
console.log("Google callback endpoint hit");
if (req.user) {
console.log(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`);
axios
.post(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`, {
user: req.user,
})
.then((response) => {
req.user.userId = response.data.user.userid;
console.log("User ID:", response.data.user.userid);
req.user.role = "instructor";
console.log("User registration response:", response.data);
req.login(req.user, (err) => {
if (err) {
console.error("Login error:", err);
return res.status(500).send("Login failed");
}
return res.redirect(process.env.LOGIN_REDIRECT_URL);
});
})
.catch((error) => {
console.error("Error registering user:", error.message);
res.status(500).json({ error: true, message: "User login failed" });
});
} else {
res.status(403).json({ error: true, message: "Not Authorized" });
}
}
); );
router.get("/current_user", (req, res) => { router.get("/current_user", (req, res) => {
@ -22,28 +53,28 @@ router.get("/current_user", (req, res) => {
} }
}); });
router.get("/google/login", (req, res) => { // router.get("/google/login", (req, res) => {
if (req.user) { // if (req.user) {
console.log(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`); // console.log(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`);
axios // axios
.post(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`, { // .post(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`, {
user: req.user, // user: req.user,
}) // })
.then((response) => { // .then((response) => {
req.user.userId = response.data.user.userid; // req.user.userId = response.data.user.userid;
console.log("User ID:", response.data.user.userid); // console.log("User ID:", response.data.user.userid);
req.user.role = "instructor"; // req.user.role = "instructor";
console.log("User registration response:", response.data); // console.log("User registration response:", response.data);
res.redirect(process.env.LOGIN_REDIRECT_URL); // res.redirect(process.env.LOGIN_REDIRECT_URL);
}) // })
.catch((error) => { // .catch((error) => {
console.error("Error registering user:", error.message); // console.error("Error registering user:", error.message);
res.status(500).json({ error: true, message: "User login failed" }); // res.status(500).json({ error: true, message: "User login failed" });
}); // });
} else { // } else {
res.status(403).json({ error: true, message: "Not Authorized" }); // res.status(403).json({ error: true, message: "Not Authorized" });
} // }
}); // });
router.get("/login/failed", (req, res) => { router.get("/login/failed", (req, res) => {
res.status(401).json({ res.status(401).json({
@ -56,7 +87,7 @@ router.get("/google", passport.authenticate("google", ["profile", "email"]));
router.post( router.post(
"/student/login", "/student/login",
passport.authenticate("student-auth"), passport.authenticate("student-auth", { keepSessionInfo: true }),
(req, res) => { (req, res) => {
console.log("Student login endpoint hit"); console.log("Student login endpoint hit");
@ -68,18 +99,17 @@ router.post(
req.user.userId = req.user.assignmentid; req.user.userId = req.user.assignmentid;
req.user.role = "student"; req.user.role = "student";
req.logIn(req.user, function(err) { req.logIn(req.user, function (err) {
if (err) return next(err); if (err) return next(err);
console.log('is authenticated?: ' + req.isAuthenticated()); console.log("is authenticated?: " + req.isAuthenticated());
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
message: 'Successful Login', message: "Successful Login",
user: req.user user: req.user,
}); });
}); });
} else { } else {
console.log("Authentication failed"); console.log("Authentication failed");
res.status(401).json({ error: true, message: "Authentication failed" }); res.status(401).json({ error: true, message: "Authentication failed" });
@ -88,7 +118,6 @@ router.post(
); );
router.get("/logout", (req, res) => { router.get("/logout", (req, res) => {
req.logout((err) => { req.logout((err) => {
if (err) { if (err) {
return next(err); return next(err);

View file

@ -1,4 +1,4 @@
require('dotenv').config(); require("dotenv").config();
const cors = require("cors"); const cors = require("cors");
const express = require("express"); const express = require("express");
@ -9,35 +9,46 @@ const session = require("express-session");
const bodyParser = require("body-parser"); const bodyParser = require("body-parser");
const app = express(); const app = express();
app.use(bodyParser.json()); // or express.json() app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded({ extended: true }));
// console.log("AUTH_URL:", process.env.AUTH_URL);
const isProduction = process.env.NODE_ENV === "production";
app.use( app.use(
session({
session({ secret: process.env.AUTH_SESSION_KEY,
secret: process.env.AUTH_SESSION_KEY, resave: false,
resave: false, saveUninitialized: false,
saveUninitialized: false, cookie: {
cookie: { maxAge: 24 * 60 * 60 * 1000, // 1 day
maxAge: 24 * 60 * 60 * 1000, // 1 day //keep production security settings below disable for the mean-time because we need to integrate redis session for cross-origin to work properly
}, //sameSite: isProduction ? "none" : "lax", // or 'none' if using cross-origin
}) //secure: isProduction, // only true in production over HTTPS
},
})
); );
app.use(passport.initialize()); app.use(passport.initialize());
app.use(passport.session()); app.use(passport.session());
app.use( const allowedOrigins = process.env.ACCEPTED_ORIGINS.split(",");
cors({
origin: process.env.ACCEPTED_ORIGINS.split(","),
methods: ["GET", "POST"],
credentials: true,
})
)
app.use(express.json()); const corsOptions = {
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, origin); // allow the request
} else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
};
app.use(cors(corsOptions));
app.use("/auth", authRoute); app.use("/auth", authRoute);
const port = process.env.PORT || 8080; const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}...`)); app.listen(port, () => console.log(`Listening on port ${port}...`));

View file

@ -91,13 +91,6 @@ app.post("/deploy", async (req, res) => {
return res.status(400).json({ error: "appName required" }); return res.status(400).json({ error: "appName required" });
} }
// const notebookPath = path.join(__dirname, '../snakeapi_service/notebooks', notebookName);
// console.log('Resolved notebookPath:', notebookPath);
// if (!fs.existsSync(notebookPath)) {
// console.error('Notebook not found at:', notebookPath);
// return res.status(500).json({ error: `Notebook not found: ${notebookPath}` });
// }
try { try {
const fly = createFlyClient(); const fly = createFlyClient();
@ -108,17 +101,6 @@ app.post("/deploy", async (req, res) => {
primary_region: "sea", primary_region: "sea",
}); });
// console.log('Uploading notebook to S3');
// const data = fs.readFileSync(notebookPath);
// const key = `${appName}/notebooks/${Date.now()}-notebook.ipynb`;
// console.log('S3 key:', key);
// await s3.putObject({
// Bucket: COMMON_BUCKET,
// Key: key,
// Body: data,
// ContentType: 'application/json'
// }).promise();
console.log("Creating machine"); console.log("Creating machine");
const machineConfig = { const machineConfig = {
name: `${appName}-machine`, name: `${appName}-machine`,
@ -237,12 +219,23 @@ app.post("/:appName/delete", async (req, res) => {
try { try {
const fly = createFlyClient(); const fly = createFlyClient();
console.log("Destroying Fly app:", appName); console.log("Destroying Fly app:", appName);
//check if the app exists
console.log("Checking if app exists:", appName);
const appCheck = await fly.get(`/apps/${appName}`);
console.log("App check response:", appCheck.status);
if (appCheck.status !== 200) {
console.log("App not found:", appName);
return res.json({ status: "App not found", app: appName });
}
await fly.delete(`/apps/${appName}`); await fly.delete(`/apps/${appName}`);
return res.json({ status: "deleted", app: appName }); return res.json({ status: "deleted", app: appName });
} catch (err) { } catch (err) {
console.error("App deletion error:", err.response?.data || err.message); const errorData = err.response?.data || err.stack || err.message;
return res.status(500).json({ error: err.response?.data || err.message }); console.error("App deletion error:", errorData);
return res.status(500).json({ errorData });
} }
}); });
@ -250,3 +243,28 @@ const LISTEN_PORT = process.env.PORT || 3006;
app.listen(LISTEN_PORT, "0.0.0.0", () => { app.listen(LISTEN_PORT, "0.0.0.0", () => {
console.log(`Deployment service listening on port ${LISTEN_PORT}`); console.log(`Deployment service listening on port ${LISTEN_PORT}`);
}); });
//deploy fly app based on appname
app.post("/deploy/:appName", async (req, res) => {
const { appName } = req.params;
const { region } = req.body;
if (!appName || !region) {
return res.status(400).json({ error: "appName and region are required" });
}
try {
const fly = createFlyClient();
console.log("Creating Fly app:", appName);
await fly.post("/apps", {
app_name: appName,
org_slug: FLY_ORG,
primary_region: region,
});
return res.json({ status: "created", app: appName });
} catch (err) {
console.error("App creation error:", err.response?.data || err.message);
return res.status(500).json({ error: err.response?.data || err.message });
}
});