Skip to content

Commit

Permalink
Removed all compilers except python
Browse files Browse the repository at this point in the history
  • Loading branch information
LakshayBabbar committed Sep 21, 2024
1 parent 086f4c8 commit b150a37
Show file tree
Hide file tree
Showing 12 changed files with 219 additions and 202 deletions.
11 changes: 0 additions & 11 deletions .dockerignore

This file was deleted.

21 changes: 0 additions & 21 deletions Dockerfile

This file was deleted.

41 changes: 30 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ CodeFramer is a versatile code editor built to enhance your coding experience wi

## Tech Stack

- **FullStack Framework:** Next.js 14
- **Frontend:** Next.js 14
- **Backend** Next.js 14 API Routes, flask
- **Database:** MongoDB
- **Authentication:** Jose (JWT)
- **Styling:** Tailwind CSS, ShadCn, Aceternity UI
- **Other Libraries:** React Query, Redux Toolkit, Nodemailer, React-Markdown, Monaco Editor, UUID, Bcryptjs, React Icons, Mongoose

- **Other Libraries:** React Query, Redux Toolkit, Monaco Editor, React-Markdown, Bcryptjs, Mongoose

## Installation

Expand All @@ -32,26 +32,45 @@ CodeFramer is a versatile code editor built to enhance your coding experience wi

```bash
git clone https://github.com/lakshaybabbar/codeframer.git
```

2. Navigate to the project directory:
```bash
```bash
cd codeframer
```
3. Install dependencies:
```bash
```bash
npm install
```
4. Configure Environment Variables:
- `ACCESS_SECRET_KEY`: User-defined access secret key
- `URI`: MongoDB URI address
- `BASE_URL`: Hosting address
- `NEXT_PUBLIC_AI_API`: Google AI Studio API
5. Start the development server:
```bash

- `ACCESS_SECRET_KEY`: User-defined access secret key
- `URI`: MongoDB URI address
- `BASE_URL`: Hosting address
- `NEXT_PUBLIC_AI_API`: Google AI Studio API
- `COMPILER_URL`: Path of python compiler

5. Start docker container for compiling python code:

```bash
cd compiler/python
docker build -t pycompiler .
docker run -p 5000:5000 --name compiler pycompiler
```

6. Start the development server:
```bash
npm run dev
```

## Contributing

We welcome contributions from the community! If you have ideas for improvements or bug fixes, please feel free to submit a pull request.

## Bug Reports

If you encounter any bugs or issues while using CodeFramer, please open an issue on GitHub with detailed information about the problem.

## License

CodeFramer is licensed under the MIT License.
17 changes: 17 additions & 0 deletions compiler/python/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
FROM python:3.10-slim

RUN adduser --disabled-password --gecos '' appuser

WORKDIR /app

COPY app.py .

RUN pip install flask gunicorn RestrictedPython

RUN chown -R appuser:appuser /app

USER appuser

EXPOSE 5000

CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:app"]
65 changes: 65 additions & 0 deletions compiler/python/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from flask import Flask, request, jsonify
import tempfile
import shutil
import re
import sys
import io

app = Flask(__name__)

DANGEROUS_KEYWORDS = [
r'\bos\b',
r'\bsys\b',
r'\bimport\b',
r'\beval\b',
r'\bexec\b',
r'\bopen\b',
r'\bsubprocess\b'
]

def is_code_safe(code):

for pattern in DANGEROUS_KEYWORDS:
if re.search(pattern, code):
return False
return True

@app.route('/execute', methods=['POST'])
def execute_python_safely():
code = request.json.get('code')
inputs = request.json.get('inputs', [])

if not code:
return jsonify({"error": "No code provided."}), 400

if not is_code_safe(code):
return jsonify({"error": "Code contains unsafe operations."}), 400

temp_dir = tempfile.mkdtemp(prefix="user_code_")

try:
input_data = iter(inputs)

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

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

exec(code, exec_env)

output = output_capture.getvalue()

return jsonify({
"output": output,
"status": 0
})
except Exception as e:
return jsonify({"error": str(e)}), 500
finally:
shutil.rmtree(temp_dir)
sys.stdout = sys.__stdout__

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
24 changes: 24 additions & 0 deletions src/app/api/compile/python/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ code, inputs }),
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
if (!response.ok) {
throw new Error("Failed to compile code");
}
return NextResponse.json(data, { status: 200 });
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
82 changes: 0 additions & 82 deletions src/app/api/compile/route.js

This file was deleted.

7 changes: 2 additions & 5 deletions src/app/api/projects/[pid]/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function GET(req, { params }) {
const projectData = await Project.findOne({
_id: pid,
userId: authData.id,
}).select("html css js _id");
}).select("-userId -__v -createdAt -updatedAt");
if (!projectData) {
return NextResponse.json(
{
Expand Down Expand Up @@ -59,7 +59,6 @@ export async function PUT(req, { params }) {
try {
const { pid } = params;
const reqBody = await req.json();
const { html, css, js } = await reqBody;
const Headers = headers();
const authData = await JSON.parse(Headers.get("authData"));
const projectData = await Project.findOne({
Expand All @@ -74,9 +73,7 @@ export async function PUT(req, { params }) {
{ status: 404 }
);
}
projectData.html = html;
projectData.css = css;
projectData.js = js;
projectData[reqBody] = reqBody;
await projectData.save();
return NextResponse.json({
message: "Project is updated successfully",
Expand Down
Loading

0 comments on commit b150a37

Please sign in to comment.