palettehome/server.js
2024-04-08 10:56:01 +02:00

130 lines
3.9 KiB
JavaScript

// Import required modules
const express = require('express');
const axios = require('axios');
// Create Express app
const app = express();
const port = 3000;
// Configuration
const giteaBaseUrl = "https://git.deuxfleurs.fr";
const clientId = "7fff7e96-5ff6-4c16-b6dc-da431dd4f82e";
const clientSecret = "gto_s7aimnk7ihidrcl4yyace6tnddlvoq43apufiho7qewkixllqycq";
const redirectUri = "https%3A%2F%2Fpalette.web.deuxfleurs.fr%2Fcallback";
const path = './hugo.toml';
// Function to fetch file content from the repository
async function getFileContent(owner, repo) {
const apiUrl = `${giteaBaseUrl}/api/v1/repos/${owner}/${repo}/contents/${path}`;
try {
const response = await axios.get(apiUrl, {
headers: {
'Accept': 'application/vnd.github.v3.raw',
},
});
const base64Content = response.data.content;
const decodedContent = Buffer.from(base64Content, 'base64').toString('utf-8');
const baseURLPattern = /baseURL\s*=\s*'(.+?)'/;
const matches = decodedContent.match(baseURLPattern);
const baseURL = matches ? matches[1] : null;
return baseURL;
} catch (error) {
console.error('Error fetching file content:', error);
throw error;
}
}
// Function to fetch repositories of a user
async function getRepos(username) {
try {
const apiUrl = `${giteaBaseUrl}/api/v1/users/${username}/repos`;
const response = await axios.get(apiUrl);
if (response.status === 200) {
const repoNames = response.data.map(repo => repo.name);
return repoNames;
} else {
throw new Error(`Request failed with status: ${response.status}`);
}
} catch (error) {
console.error('Error fetching repositories:', error);
throw error;
}
}
// Handle GET request for login route
app.get('/login', (req, res) => {
const loginUrl = `${giteaBaseUrl}/login/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code`;
res.redirect(loginUrl);
});
// Handle GET request for owner/repos route
app.get('/:owner/repos', async (req, res) => {
try {
const owner = req.params.owner;
const repos = await getRepos(owner);
let links = [];
for (let repo of repos) {
const URL = await getFileContent(owner, repo);
if (URL) {
links.push(`${URL}/admin`);
}
}
res.send(links);
} catch (error) {
res.status(500).send('An error occurred while fetching repositories.');
}
});
// Handle GET request for callback route
app.get('/callback', async (req, res) => {
const code = req.query.code;
try {
const tokenResponse = await axios.post(
`${giteaBaseUrl}/login/oauth/access_token`,
`client_id=${clientId}&client_secret=${clientSecret}&redirect_uri=${redirectUri}&code=${code}&grant_type=authorization_code`,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
const accessToken = tokenResponse.data?.access_token;
if (!accessToken) {
console.error('Access token not found in the response');
res.status(500).send('Error during authentication');
return;
}
const userResponse = await axios.get(`${giteaBaseUrl}/api/v1/user`, {
headers: {
Authorization: `token ${accessToken}`,
},
});
const user = userResponse.data;
const owner = user.username;
res.redirect(`https://palette.web.deuxfleurs.fr/${owner}/repos`);
} catch (error) {
console.error('Error during authentication:', error.response?.data || error.message);
res.status(500).send('Error during authentication');
}
});
// Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});