Skip to content

Commit

Permalink
Implemented oauth with github and related changes (#1338)
Browse files Browse the repository at this point in the history
  • Loading branch information
medss19 authored Jan 4, 2025
1 parent 0cf91c0 commit 5210bfc
Show file tree
Hide file tree
Showing 6 changed files with 195 additions and 153 deletions.
21 changes: 9 additions & 12 deletions login.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ <h2 class="title">Sign in</h2>
<p class="social-text">Or Sign in with social platforms</p>
<div class="social-media">
<button type="button" class="github-login" id="gh-lg-btn">
<img src="https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg" alt="GitHub" width="40" height="40">
<img src="https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg" alt="GitHub" width="40" height="40" style="margin-left: 5px;">
</button>
</div>
</form>

<form action="#" class="sign-up-form">
<h2 class="title">Sign up</h2>
<div class="input-field">
Expand All @@ -50,18 +50,18 @@ <h2 class="title">Sign up</h2>
<input type="email" placeholder="Email" />
</div>
<div class="input-field">
<i class="fas fa-lock toggle-password" id="toggle-password-signup"></i>
<input type="password" id="password-input-signup" placeholder="Password" minlength="8" />
<i class="fas fa-lock toggle-password" id="toggle-password"></i>
<input type="password" id="password-input" placeholder="Password" minlength="8" />
</div>
<div class="remember-me">
<input type="checkbox" id="remember-me-signup" />
<label for="remember-me-signup">Remember Me</label>
<input type="checkbox" id="remember-me" />
<label for="remember-me">Remember Me</label>
</div>
<input type="submit" class="btn" value="Sign up" />
<p class="social-text">Or Sign up with social platforms</p>
<div class="social-media">
<button type="button" class="github-login" id="gh-sg-btn">
<img src="https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg" alt="GitHub" width="40" height="40">
<img src="https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg" alt="GitHub" width="40" height="40" style="margin-left: 5px;">
</button>
</div>
</form>
Expand All @@ -71,24 +71,21 @@ <h2 class="title">Sign up</h2>
<div class="panels-container">
<a href="index.html" class="homeBtn">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 20" width="30" height="30">
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" fill="#000000"/>
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
</svg>
</a>
<div class="panel left-panel">
<div class="content">
<h3>New here ?</h3>
<p>
Discover new experiences and profiles with awesome-github-profiles<br>
Get access to exclusive content and features.<br>
Create your account.
Discover new experiences and profiles with awesome-github-profiles <br>Get access to exclusive content and features. <br> Create your account.
</p>
<button class="btn transparent" id="sign-up-btn">
Sign up
</button>
</div>
<img src="img/log.svg" class="image" alt="" />
</div>

<div class="panel right-panel">
<div class="content">
<h3>One of us ?</h3>
Expand Down
116 changes: 66 additions & 50 deletions login.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,76 +20,87 @@ document.addEventListener("DOMContentLoaded", () => {
});

// GitHub Authentication Setup
const GITHUB_CLIENT_ID = "your_github_client_id";
const GITHUB_CLIENT_ID = "Ov23liz64bw3989HVcKK";
const BACKEND_URL = "http://localhost:3000";

// Handle GitHub OAuth
// GitHub auth handler
const handleGitHubAuth = () => {
const params = window.location.search;
const urlParams = new URLSearchParams(params);
const code = urlParams.get("code");

const params = new URLSearchParams(window.location.search);
const code = params.get("code");

if (code) {
localStorage.setItem("code", code);
getGhUser();
console.log("OAuth code received:", code);
getGhUser(code);
}
};

// Get GitHub User Data
const getGhUser = () => {
let code = localStorage.getItem("code");
if (!code || code === "null") return;

// Get GitHub user data
const getGhUser = (code) => {
console.log("Starting GitHub user fetch with code:", code);

fetch(`${BACKEND_URL}/api/auth/github?code=${code}`)
.then((res) => res.json())
.then((response) => {
let resData = response.data;
let token = new URLSearchParams(resData).get("access_token");
.then(res => {
console.log("Auth response status:", res.status);
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
return res.json();
})
.then(response => {
console.log("Auth response data:", response);
if (!response.data || !response.data.access_token) {
throw new Error('No access token received');
}

const token = response.data.access_token;
console.log("Received access token, fetching user data");

return fetch(`${BACKEND_URL}/api/auth/github/getUser`, {
headers: {
Authorization: "Bearer " + token,
},
'Authorization': `Bearer ${token}`
}
});
})
.then((res) => res.json())
.then((response) => {
.then(res => {
console.log("User data response status:", res.status);
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
return res.json();
})
.then(response => {
console.log("User data response:", response);
if (!response.user) {
throw new Error('No user data received');
}

const { name, email } = response.user;
localStorage.setItem(
"user-info",
JSON.stringify({
name: name,
email: email,
})
);
localStorage.removeItem("code");
localStorage.setItem('user-info', JSON.stringify({ name, email }));

// Clean up URL
const cleanUrl = window.location.href.split('?')[0];
window.history.replaceState({}, '', cleanUrl);

// Redirect to home page
window.location.href = "/";
})
.catch((error) => {
console.error("GitHub auth error:", error);
.catch(error => {
console.error("Authentication error:", error);
alert("Failed to authenticate with GitHub. Please try again.");
});
};

// Handle initial auth check
if (localStorage.getItem("user-info")) {
window.location.href = "/";
} else if (localStorage.getItem("code")) {
getGhUser();
}

// GitHub button click handlers
github_signIn.onclick = () => {
window.location.assign(
`https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}`
);
};

github_login.onclick = () => {
window.location.assign(
`https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}`
);
const initiateGitHubAuth = () => {
const authUrl = new URL('https://github.com/login/oauth/authorize');
authUrl.searchParams.append('client_id', GITHUB_CLIENT_ID);
authUrl.searchParams.append('scope', 'user');
window.location.href = authUrl.toString();
};

github_signIn.onclick = initiateGitHubAuth;
github_login.onclick = initiateGitHubAuth;

// Email validation function
const isValidEmail = (email) => {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
Expand Down Expand Up @@ -125,7 +136,7 @@ document.addEventListener("DOMContentLoaded", () => {
localStorage.removeItem("rememberedUsername");
}
alert("Login successful!");
window.location.href = "index.html";
window.location.href = "/";
} else {
alert("Invalid username or password");
}
Expand Down Expand Up @@ -161,7 +172,7 @@ document.addEventListener("DOMContentLoaded", () => {
localStorage.setItem("isLoggedIn", "true");

alert("Signup successful!");
window.location.href = "index.html";
window.location.href = "/";
});

// Password visibility toggle
Expand All @@ -188,4 +199,9 @@ document.addEventListener("DOMContentLoaded", () => {
usernameInput.value = localStorage.getItem("rememberedUsername");
rememberMeCheckbox.checked = true;
}

// Handle GitHub auth on page load
if (window.location.search.includes("code")) {
handleGitHubAuth();
}
});
15 changes: 6 additions & 9 deletions node_modules/.package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 8 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
"start": "nodemon server.js"
},
"dependencies": {
"axios": "^1.7.7",
"axios": "^1.7.9",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"puppeteer": "^22.15.0"
},
Expand Down
Loading

0 comments on commit 5210bfc

Please sign in to comment.