Skip to content

Commit

Permalink
Some security updates and new features
Browse files Browse the repository at this point in the history
  • Loading branch information
LakshayBabbar committed Sep 22, 2024
1 parent b150a37 commit 0d58d51
Show file tree
Hide file tree
Showing 22 changed files with 256 additions and 65 deletions.
15 changes: 10 additions & 5 deletions compiler/python/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
]

def is_code_safe(code):

for pattern in DANGEROUS_KEYWORDS:
if re.search(pattern, code):
return False
Expand All @@ -39,16 +38,14 @@ def execute_python_safely():

try:
input_data = iter(inputs)

output_capture = io.StringIO()
sys.stdout = output_capture #
sys.stdout = output_capture

exec_env = {
'input': lambda prompt: next(input_data, ''),
}

exec(code, exec_env)

output = output_capture.getvalue()

return jsonify({
Expand All @@ -61,5 +58,13 @@ def execute_python_safely():
shutil.rmtree(temp_dir)
sys.stdout = sys.__stdout__


@app.route('/status', methods=['GET'])
def get_status():
return jsonify({
"status": "running",
"message": "Server is up and running!"
}), 200

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
app.run(host='0.0.0.0', port=5000, debug=True)
8 changes: 7 additions & 1 deletion src/app/api/auth/login/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,16 @@ export async function POST(request) {
{
message: "Logged in successfully",
username: user.username,
authToken,
},
{ status: 200 }
);
response.cookies.set("authToken", authToken, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
});
return response;
} else {
return NextResponse.json(
Expand Down
31 changes: 31 additions & 0 deletions src/app/api/auth/logout/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server";

export async function GET(request) {
try {
const res = NextResponse.json(
{
message: "Logged out successfully",
},
{
status: 200,
}
);
res.cookies.set("authToken", "", {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
expires: new Date(0),
});
return res;
} catch (error) {
return NextResponse.json(
{
error: error.message,
},
{
status: 500,
}
);
}
}
2 changes: 1 addition & 1 deletion src/app/api/compile/python/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NextResponse } from "next/server";
export async function POST(req) {
try {
const { code, inputs } = await req.json();
const response = await fetch(process.env.COMPILER_URL, {
const response = await fetch(process.env.COMPILER_URL+"/execute", {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand Down
16 changes: 10 additions & 6 deletions src/app/api/projects/[pid]/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,19 @@ export async function GET(req, { params }) {
if (!projectData) {
return NextResponse.json(
{
message: "Project not found",
error: "Project not found",
},
{ status: 404 }
);
}
return NextResponse.json(projectData);
return NextResponse.json(projectData, { status: 200 });
} catch (error) {
return NextResponse.json({
message: error.message,
});
return NextResponse.json(
{
error: error.message,
},
{ status: 500 }
);
}
}
export async function DELETE(req, { params }) {
Expand Down Expand Up @@ -73,7 +76,8 @@ export async function PUT(req, { params }) {
{ status: 404 }
);
}
projectData[reqBody] = reqBody;
console.log(reqBody);
projectData.languages = await reqBody.languages;
await projectData.save();
return NextResponse.json({
message: "Project is updated successfully",
Expand Down
11 changes: 1 addition & 10 deletions src/app/api/projects/all/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,7 @@ export async function GET() {
try {
const Headers = headers();
const authData = await JSON.parse(Headers.get("authData"));
const projects = await Project.find({ userId: authData.id })
.select("name description _id createdAt");
if (projects.length === 0) {
return NextResponse.json(
{
message: "You have not created any project yet",
},
{ status: 404 }
);
}
const projects = await Project.find({ userId: authData.id });
return NextResponse.json(projects);
} catch (error) {
return NextResponse.json(
Expand Down
29 changes: 29 additions & 0 deletions src/app/api/projects/create/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,35 @@ export async function POST(req) {
try {
const reqBody = await req.json();
const projectData = await reqBody;
if (!projectData.name || !projectData.type) {
return NextResponse.json(
{
message: "Please provide all the required fields",
success: false,
},
{ status: 400 }
);
}
if (projectData.type === "compiler" && !projectData.language) {
return NextResponse.json(
{
message: "Please provide all the required fields",
success: false,
},
{ status: 400 }
);
}
if (projectData.type === "compiler") {
projectData.languages = projectData.languages || {};
projectData.languages[projectData.language] = " ";
}
if (projectData.type === "web") {
projectData.languages = {
html: "<h1 id='heading'>Welcome to your first project</h1>",
css: "#heading {\n\tcolor: blue;\n\tfont-size: 24px;\n}",
js: "",
};
}
const headersList = headers();
const authData = await JSON.parse(headersList.get("authData"));

Expand Down
4 changes: 3 additions & 1 deletion src/app/api/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { verifyToken } from "@/utils/authToken";

export async function GET(req) {
try {
const token = req.headers.get("Authorization")?.split(" ")[1];
const token = req.cookies?.get("authToken")?.value;
const res = {
message: "Welcome to CodeFramer",
};
Expand All @@ -26,5 +26,7 @@ export async function GET(req) {
},
{ status: 500 }
);
} finally {
fetch(process.env.COMPILER_URL + "/status");
}
}
1 change: 0 additions & 1 deletion src/app/auth/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ function Auth() {
if (res?.success) {
if (isLogin) {
dispatch(authState({ isAuth: true, username: res.username }));
localStorage.setItem("authToken", res?.authToken);
} else {
navigate.push("/auth?mode=login");
}
Expand Down
59 changes: 59 additions & 0 deletions src/app/compiler/[...slug]/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import CompilerEditor from "@/components/Editor/Compiler";

const getData = async (id) => {
try {
if (!process.env.BASE_URL) {
throw new Error("BASE_URL is not defined in environment variables");
}
const req = await fetch(`${process.env.BASE_URL}/api/projects/${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
});
if (!req.ok) {
const errorText = (await req.json()) || { error: "Failed to fetch data" };
throw new Error(`Error ${req.status}: ${errorText?.error}`);
}
const res = await req.json();
return res;
} catch (error) {
return {
error: error.message,
};
}
};

export async function generateMetadata({ params }) {
const { slug } = params;
return {
title: `Codeframer | online ${slug[0]} compiler`,
description: `codeframer provides online ${slug[0]} compiler to compile and run your code online`,
};
}

const Compiler = async ({ params }) => {
const { slug } = params;
fetch(`${process.env.COMPILER_URL}/status`);
if (slug[0] !== "python") {
return (
<main className="flex h-screen w-full items-center justify-center text-3xl font-light">
Language not supported
</main>
);
}
if (slug[1]) {
const data = await getData(slug[1]);
if (data.error)
return (
<main className="flex h-screen w-full items-center justify-center text-3xl font-light">
{data?.error}
</main>
);
return <CompilerEditor language={slug[0]} data={data} />;
}
return <CompilerEditor language={slug[0]} />;
};

export default Compiler;
12 changes: 7 additions & 5 deletions src/app/dashboard/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,16 @@ const Page = () => {
</div>
{!loading ? (
<>
<div className="w-full grid xl:grid-cols-2 2xl:grid-cols-3 gap-5 justify-items-center xl:justify-items-start">
{!isError &&
data &&
data.map((item) => {
<div className="w-full flex flex-wrap gap-4">
{data?.length > 0 ? (
data?.map((item) => {
return (
<ProjectCard key={item._id} data={{ ...item, refetch }} />
);
})}
})
) : (
<p className="text-center w-full">No project found.</p>
)}
</div>
<p className="text-center mb-36">{isError && error.message}</p>
</>
Expand Down
4 changes: 2 additions & 2 deletions src/app/web-editor/page.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import WebEditor from "@/components/Editor/WebEditor";

const Page = () => {
const data = {
const languages = {
html: `<div class="container">
<h1>Welcome to <br/><span>CodeFramer</span></h1>
<p>CodeFramer is a versatile code editor built to enhance your coding experience with its intuitive interface and
Expand Down Expand Up @@ -57,6 +57,6 @@ const Page = () => {
}`,
js: "",
};
return <WebEditor data={data} />;
return <WebEditor data={{ languages }} />;
};
export default Page;
Loading

0 comments on commit 0d58d51

Please sign in to comment.