improved database updates for assignment creation
This commit is contained in:
parent
fd993102a0
commit
e2d728265b
8 changed files with 211 additions and 92 deletions
|
|
@ -192,13 +192,17 @@ app.get("/assignments/appname/:appName", async (req, res) => {
|
|||
app.put("/assignments/:id", async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
console.log("Updating assignment with ID:", id);
|
||||
|
||||
const assignment = await convertToAssignment(req);
|
||||
console.log("Converted assignment object for update:", assignment);
|
||||
|
||||
const existingAssignment = await prisma.assignments.findUnique({
|
||||
where: { assignmentid: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existingAssignment) {
|
||||
console.log("No existing assignment found for ID:", id);
|
||||
return res.status(404).json({ message: "Assignment not found" });
|
||||
}
|
||||
|
||||
|
|
@ -216,6 +220,8 @@ app.put("/assignments/:id", async (req, res) => {
|
|||
data: existingAssignment,
|
||||
});
|
||||
|
||||
console.log("Assignment updated successfully:", updatedAssignment);
|
||||
|
||||
res.json({
|
||||
message: "Assignment updated successfully",
|
||||
assignment: updatedAssignment,
|
||||
|
|
|
|||
|
|
@ -29,12 +29,17 @@ intructorRouter.post(
|
|||
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);
|
||||
const response = await axios.post(
|
||||
const dbResponse = await axios.post(
|
||||
`${DB_ASSIGNMENT_SERVICE_URL}/assignments`,
|
||||
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
|
||||
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);
|
||||
|
||||
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) {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
|
@ -148,16 +192,19 @@ intructorRouter.delete(
|
|||
}
|
||||
|
||||
// Delete the Battlesnake API
|
||||
console.log('Deploying a new Battlesnake API');
|
||||
if(assignmentData.appname){
|
||||
console.log(`Deleting Battlesnake API: ${assignmentData.appname}`);
|
||||
console.log("DEPLOY_API_URL:", DEPLOY_API_URL, assignmentData.appname);
|
||||
const deployResponse = await axios.post(`${DEPLOY_API_URL}/${assignmentData.appname}/delete`, {
|
||||
"appName": assignmentData.appname
|
||||
});
|
||||
//throw error if the response is not 200
|
||||
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);
|
||||
}
|
||||
|
||||
const response = await axios.delete(
|
||||
`${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}`
|
||||
|
|
|
|||
|
|
@ -2,10 +2,11 @@ GOOGLE_CLIENT_ID = "485880105639-1in8tvb6ondnn198rasuj2d8ank06ntp.apps.googleuse
|
|||
GOOGLE_CLIENT_SECRET = "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"
|
||||
GOOGLE_CALLBACK_URL = "https://byte-camp-auth-service.fly.dev/auth/google/callback"
|
||||
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://db-user-service.internal:3000/"
|
||||
AUTH_SESSION_KEY = "f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42"
|
||||
AUTH_URL = "https://byte-camp-auth-service.fly"
|
||||
ASSIGNMENT_SERVICE_URL="http://assignment-service.internal:8080"
|
||||
|
||||
# fly secrets set GOOGLE_CALLBACK_URL=https://byte-camp-auth-service.fly.dev/auth/google/callback
|
||||
|
|
|
|||
|
|
@ -8,4 +8,5 @@ ACCEPTED_ORIGINS=http://localhost:3000,http://localhost:8081,http://localhost:30
|
|||
ASSIGNMENT_SERVICE_URL="http://localhost:8082"
|
||||
DB_USER_SERVICE_URL="http://localhost:3100/"
|
||||
AUTH_SESSION_KEY="f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42"
|
||||
AUTH_URL = "http://localhost:8080"
|
||||
PORT=8080
|
||||
|
|
@ -5,6 +5,8 @@ const passport = require("passport");
|
|||
const CustomStrategy = require("passport-custom").Strategy;
|
||||
const axios = require("axios");
|
||||
|
||||
|
||||
|
||||
passport.use(
|
||||
new GoogleStrategy(
|
||||
{
|
||||
|
|
@ -14,7 +16,11 @@ passport.use(
|
|||
scope: ["profile", "email"],
|
||||
},
|
||||
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) => {
|
||||
// done(null, user);
|
||||
console.log("Serializing user:", user);
|
||||
// done(null, user);
|
||||
done(null, {
|
||||
userId: user.qrcodenumber || user.id,
|
||||
displayName: user.studentname || user.displayName,
|
||||
role: user.role,
|
||||
emails: user.emails || "none",
|
||||
// emails: user.emails || "none",
|
||||
});
|
||||
});
|
||||
|
||||
passport.deserializeUser(async (user, done) => {
|
||||
try {
|
||||
passport.deserializeUser((user, done) => {
|
||||
console.log("Deserializing user:", user);
|
||||
try {
|
||||
done(null, user);
|
||||
} catch (err) {
|
||||
console.error("Error during deserialization:", err);
|
||||
|
|
|
|||
|
|
@ -2,12 +2,43 @@ const router = require("express").Router();
|
|||
const passport = require("passport");
|
||||
const axios = require("axios");
|
||||
|
||||
const AUTH_URL = process.env.AUTH_URL || "http://localhost:8080";
|
||||
|
||||
router.get(
|
||||
"/google/callback",
|
||||
passport.authenticate("google", {
|
||||
successRedirect: "/auth/google/login",
|
||||
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) => {
|
||||
|
|
@ -22,28 +53,28 @@ router.get("/current_user", (req, res) => {
|
|||
}
|
||||
});
|
||||
|
||||
router.get("/google/login", (req, res) => {
|
||||
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);
|
||||
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("/google/login", (req, res) => {
|
||||
// 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);
|
||||
// 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("/login/failed", (req, res) => {
|
||||
res.status(401).json({
|
||||
|
|
@ -56,7 +87,7 @@ router.get("/google", passport.authenticate("google", ["profile", "email"]));
|
|||
|
||||
router.post(
|
||||
"/student/login",
|
||||
passport.authenticate("student-auth"),
|
||||
passport.authenticate("student-auth", { keepSessionInfo: true }),
|
||||
(req, res) => {
|
||||
console.log("Student login endpoint hit");
|
||||
|
||||
|
|
@ -68,18 +99,17 @@ router.post(
|
|||
req.user.userId = req.user.assignmentid;
|
||||
req.user.role = "student";
|
||||
|
||||
req.logIn(req.user, function(err) {
|
||||
req.logIn(req.user, function (err) {
|
||||
if (err) return next(err);
|
||||
|
||||
console.log('is authenticated?: ' + req.isAuthenticated());
|
||||
console.log("is authenticated?: " + req.isAuthenticated());
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
message: 'Successful Login',
|
||||
user: req.user
|
||||
message: "Successful Login",
|
||||
user: req.user,
|
||||
});
|
||||
});
|
||||
|
||||
} else {
|
||||
console.log("Authentication failed");
|
||||
res.status(401).json({ error: true, message: "Authentication failed" });
|
||||
|
|
@ -88,7 +118,6 @@ router.post(
|
|||
);
|
||||
|
||||
router.get("/logout", (req, res) => {
|
||||
|
||||
req.logout((err) => {
|
||||
if (err) {
|
||||
return next(err);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
require('dotenv').config();
|
||||
require("dotenv").config();
|
||||
|
||||
const cors = require("cors");
|
||||
const express = require("express");
|
||||
|
|
@ -9,17 +9,21 @@ const session = require("express-session");
|
|||
const bodyParser = require("body-parser");
|
||||
|
||||
const app = express();
|
||||
app.use(bodyParser.json()); // or express.json()
|
||||
app.use(express.json());
|
||||
app.use(bodyParser.urlencoded({ extended: true }));
|
||||
|
||||
// console.log("AUTH_URL:", process.env.AUTH_URL);
|
||||
const isProduction = process.env.NODE_ENV === "production";
|
||||
app.use(
|
||||
|
||||
session({
|
||||
secret: process.env.AUTH_SESSION_KEY,
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
cookie: {
|
||||
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
|
||||
},
|
||||
})
|
||||
);
|
||||
|
|
@ -27,15 +31,22 @@ app.use(
|
|||
app.use(passport.initialize());
|
||||
app.use(passport.session());
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin: process.env.ACCEPTED_ORIGINS.split(","),
|
||||
methods: ["GET", "POST"],
|
||||
credentials: true,
|
||||
})
|
||||
)
|
||||
const allowedOrigins = process.env.ACCEPTED_ORIGINS.split(",");
|
||||
|
||||
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);
|
||||
|
||||
|
|
|
|||
|
|
@ -91,13 +91,6 @@ app.post("/deploy", async (req, res) => {
|
|||
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 {
|
||||
const fly = createFlyClient();
|
||||
|
||||
|
|
@ -108,17 +101,6 @@ app.post("/deploy", async (req, res) => {
|
|||
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");
|
||||
const machineConfig = {
|
||||
name: `${appName}-machine`,
|
||||
|
|
@ -237,12 +219,23 @@ app.post("/:appName/delete", async (req, res) => {
|
|||
try {
|
||||
const fly = createFlyClient();
|
||||
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}`);
|
||||
|
||||
return res.json({ status: "deleted", app: appName });
|
||||
} catch (err) {
|
||||
console.error("App deletion error:", err.response?.data || err.message);
|
||||
return res.status(500).json({ error: err.response?.data || err.message });
|
||||
const errorData = err.response?.data || err.stack || 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", () => {
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue