Skip to content

Added export to github functionality #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
4 changes: 4 additions & 0 deletions mobile-magic/apps/frontend/components/Appbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Header } from '@/components/Header'
import { motion } from 'motion/react'
import { containerVariants, itemVariants } from '@/lib/animation-variants'
import { ThemeButton } from '@/components/theme-button'
import GitHubRepoCard from './Githubcard'

export function Appbar() {
return (
Expand Down Expand Up @@ -46,6 +47,9 @@ export function Appbar() {
<SignedIn>
<UserButton />
</SignedIn>

<GitHubRepoCard />

</motion.div>
</motion.div>
);
Expand Down
87 changes: 87 additions & 0 deletions mobile-magic/apps/frontend/components/Githubcard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
'use client'
import { useState } from "react";
import { ChevronDown, ChevronUp, ExternalLink } from "lucide-react";
import { BACKEND_URL } from "@/config";
import axios from "axios";


export default function GitHubRepoCard() {
const [isOpen, setIsOpen] = useState(false);


const handleGithubClick = async () => {
try {

const githubToken = localStorage.getItem("githubToken");
const githubUsername = localStorage.getItem("githubUsername");

if (!githubToken) {
return (window.location.href = `${BACKEND_URL}/auth/github`);
}
const response = await axios.post(`${BACKEND_URL}/createrepo`,
{
githubToken,
githubUsername,
files: [
{
name: "myFile.txt",
content: "This is the content of my file."
},
{
name: "anotherFile.js",
content: "console.log('Hello from another file!');"
}
]
},
);

if (response.data.repoUrl) {
window.open(response.data.repoUrl, "_blank");
}
} catch {
alert("Failed to clone repository");
}
};

return (
<div className="relative">

<button
className="flex items-center gap-2 bg-gray-900 text-white px-4 py-2 rounded-lg shadow-md"
onClick={() => setIsOpen(!isOpen)}
>
GitHub
{isOpen ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
</button>

{isOpen && (
<div className="absolute right-4 mt-2 bg-black text-white p-4 rounded-lg shadow-lg w-80">
<h2 className="text-lg font-bold">GitHub</h2>
<p className="text-sm mt-2">
This project is connected to <br />
<span className="font-semibold">{`mobile-magic`}</span>.
<br /> Changes will be committed to the <b>main</b> branch.
</p>


<div className="mt-4 flex flex-col">
<button
className="bg-blue-500 text-white text-sm text-center p-2 rounded mb-2 flex items-center justify-center gap-2"
onClick={() => {
alert("not avilable yet")
}}
>
Edit in VS Code <ExternalLink size={14} />
</button>
<button
className="text-white text-sm text-center border border-gray-600 p-2 rounded flex items-center justify-center gap-2"
onClick={handleGithubClick}
>
View on GitHub <ExternalLink size={14} />
</button>
</div>
</div>
)}
</div>
);
}
18 changes: 18 additions & 0 deletions mobile-magic/apps/frontend/components/hero.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,26 @@

import { motion } from 'motion/react'
import { containerVariants, itemVariants } from '@/lib/animation-variants'
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';

export const Hero = () => {
const router = useRouter();

useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const githubToken = urlParams.get("githubToken");
const githubId = urlParams.get("githubId");
const githubUsername = urlParams.get("githubUsername");

if (githubToken && githubId && githubUsername) {
localStorage.setItem("githubToken", githubToken);
localStorage.setItem("githubId", githubId);
localStorage.setItem("githubUsername", githubUsername);
}
router.push("/");
}, [router]);

return (
<motion.div
variants={containerVariants}
Expand Down
4 changes: 3 additions & 1 deletion mobile-magic/apps/primary-backend/.env.example
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
JWT_PUBLIC_KEY=
JWT_PUBLIC_KEY=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
92 changes: 91 additions & 1 deletion mobile-magic/apps/primary-backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import { prismaClient } from "db/client";
import express from "express";
import cors from "cors";
import { authMiddleware } from "common/middleware";
import axios from 'axios';

const app = express();
const CLIENT_ID = process.env.GITHUB_CLIENT_ID;
const CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET;
const BACKEND_URL = process.env.BACKEND_URL || "http://localhost:9090";

app.use(express.json());
app.use(cors());
Expand Down Expand Up @@ -40,6 +44,92 @@ app.get("/prompts/:projectId", authMiddleware, async (req, res) => {
res.json({ prompts });
});

app.post("/createrepo", async (req, res) => {
const { githubToken, githubUsername, files } = req.body;

if (!githubToken || !githubUsername) {
res.status(400).json({ error: "Missing parameters: githubToken and githubUsername are required." });
return;
}

if (!files || !Array.isArray(files) || files.length === 0) {
res.status(400).json({ error: "Missing or empty 'files' array." });
return;
}

try {
const newRepoName = `from-magic-mobile-${Date.now()}`;

const createRepoRes = await axios.post(
"https://api.github.com/user/repos",
{ name: newRepoName, private: false },
{ headers: { Authorization: `Bearer ${githubToken}` } }
);

const newRepoUrl = createRepoRes.data.html_url;

for (const file of files) {
if (file && file.name && file.content) {
const encodedContent = Buffer.from(file.content).toString("base64");
console.log(`Uploading ${file.name} from system to ${newRepoName}`);

await axios.put(
`https://api.github.com/repos/${githubUsername}/${newRepoName}/contents/${file.name}`,
{
message: `Added ${file.name} from system`,
content: encodedContent,
branch: "main",
},
{ headers: { Authorization: `Bearer ${githubToken}` } }
);
} else {
console.warn("Invalid file object in 'files' array.");
}
}

res.status(200).json({ message: "Repository created successfully!", repoUrl: newRepoUrl });
} catch (error) {
console.error("Error creating repository:", error.response?.data || error.message);
res.status(500).json({ error: "Failed to create repository" });
}
});

app.get("/auth/github", (req, res) => {
const githubAuthUrl = `https://github.com/login/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${BACKEND_URL}/auth/github/callback&scope=repo,user`;
res.redirect(githubAuthUrl);
});

app.get("/auth/github/callback", async (req, res) => {
const code = req.query.code;
if (!code) res.status(400).send("GitHub OAuth failed!");

try {

const tokenRes = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code,
},
{ headers: { Accept: "application/json" } }
);

const accessToken = tokenRes.data.access_token;

const userRes = await axios.get("https://api.github.com/user", {
headers: { Authorization: `Bearer ${accessToken}` },
});

const { login, id } = userRes.data;

res.redirect(`http://localhost:3000?githubToken=${accessToken}&githubId=${id}&githubUsername=${login}`); // Redirect to frontend after linking GitHub
} catch (error) {
console.error("GitHub OAuth Error:", error);
res.status(500).send("GitHub authentication failed");
}
});

app.listen(9090, () => {
console.log("Server is running on port 9090");
});
});