Skip to content

Commit

Permalink
My profile page shows your profile
Browse files Browse the repository at this point in the history
  • Loading branch information
hnasheralneam committed Jul 16, 2024
1 parent bd7ea05 commit b41faa2
Show file tree
Hide file tree
Showing 10 changed files with 505 additions and 117 deletions.
5 changes: 2 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ app.get("/profile", (req, res) => {
if (!req.session.user) {
return res.render("pages/login", { client_id: process.env.GITHUB_CLIENT_ID });
}
console.log(req.session.user)
return res.render("pages/profile", { userData: req.session.user });
});

Expand Down Expand Up @@ -95,21 +96,19 @@ app.get("/github/login", (req, res) => {

async function githubOAuthLogin(req, res) {
let isAccount = await githubOAuthUserExists(req.session.user.id);
if (isAccount) res.render("pages/profile", { userData: req.session.user });
if (isAccount) res.redirect("/profile");
else createGithubOAuthUser(req.session.user.id, req, res);
}

function createGithubOAuthUser(githubId, req, res) {
const user = new User({ githubId: githubId });
user.save().then((result) => {
console.log("id is " + result.id);
res.render("pages/new-user", { userData: req.session.user });
});
}

async function githubOAuthUserExists(githubId) {
const user = await User.findOne({ githubId: githubId });
console.log(user !== null);
return user !== null;
}

Expand Down
12 changes: 6 additions & 6 deletions public/images/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 1 addition & 11 deletions public/pages/gh-username-search.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<link rel="icon" type="images/svg" href="images/logo.svg">
<link rel="stylesheet" type='text/css' href="https://cdn.jsdelivr.net/gh/devicons/devicon@latest/devicon.min.css">

<title>My Profile | FetchCV</title>
<title>GitHub Username Search | FetchCV</title>
</head>

<body class="px-8 flex justify-center bg-zinc-50 dark:bg-zinc-900 dark:text-white">
Expand Down Expand Up @@ -85,16 +85,6 @@

</div>
</div>
<!-- future settings panel (for use with customizing profile card and accessing account settings) -->
<div class="flex fixed bottom-0 w-screen px-0 py-1 bg-zinc-700 border-[1px] border-zinc-700 border-t-zinc-600">
<div class="absolute bottom-0 -z-10 -left-40 w-[140%] h-full caution-tape"></div>
<a href="">
<div
class="inline-flex justify-center transition-all p-2 mx-1 shadow-lg bg-zinc-800 border-[1px] border-zinc-700 border-t-zinc-600 rounded-md text-black">
<span class="material-symbols-rounded text-private">settings</span>
</div>
</a>
</div>
</body>
<style>
p {
Expand Down
13 changes: 6 additions & 7 deletions public/pages/profile.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@
<span class="material-symbols-rounded text-public">home</span>
</div>
</a>
<!-- User search (will be replaced when accounts are added) -->
<!--<strong>Name</strong>: <%= userData.name %><br>
<strong>Username</strong>: <%= userData.login %><br>
<strong>Company</strong>: <%= userData.company %><br>
<strong>Bio</strong>: <%= userData.bio %> -->
<script>
let userDataWorking = `<%- JSON.stringify(userData) %>`;
let githubUserData = JSON.parse(userDataWorking);
</script>
</div>
<!-- Error box - hidden by default -->
<div
Expand Down Expand Up @@ -99,8 +98,8 @@
}
</style>

<script src="../scripts/main.js"></script>
<script src="../scripts/github.js"></script>
<script src="../scripts/profile.js"></script>
<script src="../scripts/profile-github.js"></script>
<script src="../scripts/gitlab.js"></script>

</html>
207 changes: 207 additions & 0 deletions public/scripts/profile-github.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
let userData; // global variable
let username = "";
let totalStars = 0;
let languages = [];
let TOKEN;
let tokenRecieved = false;
let header = {};
getToken("github");
async function getToken(service) {
console.log("Fetching token...");
const response = await fetch(`/token/${service}`);
if (response.ok) {
const token = await response.text();
tokenRecieved = true;
console.log("Token received.");
TOKEN = token;
header = {
'headers': {
'Authorization': `token ${TOKEN}`
}
};
}
else {
showError("Token Error", "Failed to fetch token. Try reloading the page.", "bg-red-800");
console.error('Error fetching token:', response.statusText);
}
}
async function getUserInfo() {
if (!tokenRecieved) {
console.log('Waiting for token to be received...');
setTimeout(getUserInfo, 200);
return;
}
try {
console.log(header);
const response = await fetch(`https://api.github.com/users/${username}`, header);
if (response.ok) {
userData = await response.json();
updateData();
updateGithubStats();
await getRepoData();
}
else if (response.status === 404) {
showError("Oh no!", "User does not exist. Try another username.", "bg-red-800");
}
else {
showError("Connection Error", "Failed to fetch user data. Try reloading the page.", "bg-red-800");
console.error("Failed to fetch user data. Status:", response.status, response);
}
}
catch (error) {
showError("Connection Error", "Could not request user data.", "bg-red-800");
console.error("Failed to request user data. Error - ", error);
}
}
async function getRepoData() {
try {
const response = await fetch(`https://api.github.com/users/${username}/repos`, header);
const repos = await response.json();
getRepoStars(repos);
getRepoLangs(repos);
}
catch (error) {
showError("Oh no!", "Could not get user repository data.", "bg-red-800");
console.error('Error fetching data:', error);
}
}
function updateData() {
if (!userData) {
showError("Oh no!", "Could get the user data, my bad", "bg-red-800");
return;
}
document.querySelector(".user-info").classList.remove("hidden");
document.querySelector(".profile-picture").src = userData.avatar_url;
document.querySelector(".profile-name").textContent = userData.name;
document.querySelector(".profile-handle").textContent = userData.login;
document.querySelector(".profile-desc").textContent = userData.bio;
document.querySelector(".profile-repos").textContent = userData.public_repos.toString();
document.querySelector(".profile-followers").textContent = userData.followers.toString();
document.querySelector(".profile-following").textContent = userData.following.toString();
document.querySelector(".profile-location").textContent = userData.location;
document.querySelector(".profile-email").textContent = userData.email;
document.querySelector(".profile-website").textContent = "Personal Website";
document.querySelector(".profile-github").textContent = "Github Profile";
document.querySelector(".profile-website").href = userData.blog;
document.querySelector(".profile-github").href = userData.html_url;
}
async function getRepoStars(repos) {
for (const repo of repos) {
const repoResponse = await fetch(`https://api.github.com/repos/${repo.owner.login}/${repo.name}`, header);
const repoData = await repoResponse.json();
totalStars += repoData.stargazers_count;
}
document.querySelector(".profile-stars").textContent = totalStars.toString();
return totalStars;
}
async function getRepoLangs(repos) {
let langs = {};
languages = [];
for (const repo of repos) {
const repoResponse = await fetch(`https://api.github.com/repos/${repo.owner.login}/${repo.name}/languages`, header);
const repoData = await repoResponse.json();
for (const lang in repoData) {
if (langs.hasOwnProperty(lang)) {
langs[lang] += repoData[lang];
}
else {
langs[lang] = repoData[lang];
}
}
}
let sortedLangs = [];
for (let lang in langs) {
languages.push([lang, langs[lang]]);
}
languages.sort(function (a, b) {
return b[1] - a[1];
});
const total = languages.reduce((acc, curr) => acc + curr[1], 0);
const percentLanguages = languages.map(lang => [lang[0], Math.round((lang[1] / total) * 100)]);
generateLanguageElements(percentLanguages);
return languages;
}
function generateLanguageElements(languages) {
const langList = document.querySelector(".profile-langs");
if (langList) {
langList.innerHTML = "";
for (const lang of languages) {
const langElement = document.createElement("li");
langElement.textContent = `${lang[0]}: ${lang[1]}%`;
langElement.classList.add("inline-block", "bg-zinc-200", "dark:bg-zinc-700", "px-2", "m-1", "py-1", "rounded-lg", "border-[1px]", "border-zinc-400", "dark:border-zinc-700", "border-t-zinc-300", "dark:border-t-zinc-600", "inline-flex", "items-center");
langElement.innerHTML = ` <i class="devicon-${getLangIcon(lang[0])}-plain mr-1.5"></i>` + langElement.textContent;
langList.appendChild(langElement);
}
}
function getLangIcon(lang) {
switch (lang) {
case "JavaScript":
return "javascript";
case "TypeScript":
return "typescript";
case "EJS":
case "HTML":
return "html5";
case "CSS":
return "css3";
case "Python":
return "python";
case "Java":
return "java";
case "C":
return "c";
case "C++":
return "cplusplus";
case "Lua":
return "lua";
case "Shell":
return "bash";
case "Ruby":
return "ruby";
case "PHP":
return "php";
case "Swift":
return "swift";
case "Go":
return "go";
case "Rust":
return "rust";
case "Kotlin":
return "kotlin";
case "GDScript":
return "godot";
case "QML":
return "Qt";
default:
return "gimp hidden";
}
}
}
function updateGithubStats() {
console.log(`Username: ${username}`);
const githubStatsElement = document.querySelector(".github-stats");
if (githubStatsElement) {
githubStatsElement.innerHTML = `<picture>
<source
srcset="https://github-readme-stats.vercel.app/api?username=${username}&show_icons=true&theme=slateorange"
media="(prefers-color-scheme: dark)"
/>
<source
srcset="https://github-readme-stats.vercel.app/api?username=${username}&show_icons=true"
media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)"
/>
<img src="https://github-readme-stats.vercel.app/api?username=${username}&show_icons=true" />
</picture>`;
}
}
async function getRateLimit() {
if (header) {
const response = await fetch('https://api.github.com/rate_limit', header);
if (response.ok) {
const data = await response.json();
}
else {
console.error('Error fetching rate limit:', response.statusText);
}
}
}
Loading

0 comments on commit b41faa2

Please sign in to comment.