-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.js
More file actions
148 lines (130 loc) · 5.67 KB
/
auth.js
File metadata and controls
148 lines (130 loc) · 5.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/**
* auth.js
* Handles GitHub OAuth Login and User State
*/
const Auth = {
// Configuration will be loaded from config.json
config: null,
init: async function() {
// Load config if not already loaded available globally
if (typeof config === 'undefined' || !config) {
console.error("Config not found. Make sure config is loaded before Auth.");
return;
}
this.config = config; // Assumes global 'config' object from index.html logic
// Check for code in URL (Callback)
const code = this.getQueryVariable("code");
if (code) {
await this.handleCallback(code);
// Clean URL
window.history.replaceState({}, document.title, "/");
}
this.updateUI();
},
login: function() {
if (!this.config) return;
const clientId = this.config.clientId;
// Scope 'public_repo' for reading/writing public repos if needed, or just 'read:user' for login
// 'public_repo' is needed if we want to create issues later as the user
const scope = "public_repo";
const redirectUri = window.location.href.split('?')[0]; // Current page
const authUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}`;
window.location.href = authUrl;
},
logout: function() {
localStorage.removeItem("github_access_token");
localStorage.removeItem("github_user");
this.updateUI();
},
handleCallback: async function(code) {
if (!this.config) return;
// NOTE: This is the client-side exchange.
// GitHub DOES NOT support CORS for this endpoint.
// This will likely fail without a proxy.
// We will try it, but be prepared for CORS errors.
const clientId = this.config.clientId;
const clientSecret = this.config.clientSecret; // WARNING: Exposed in client code
// Try direct fetch (will likely fail CORS)
try {
// Using a CORS proxy service if available or fallback to direct
// Since User has 'bless.taontech.workers.dev' in config, maybe that is a proxy?
// Let's try to construct a url that might work if they have a proxy set up,
// otherwise we try the direct GitHub one which will fail.
// For now, attempting the standard flow, catching error to alert user.
const tokenUrl = "https://github.com/login/oauth/access_token";
// const tokenUrl = "https://cors-anywhere.herokuapp.com/https://github.com/login/oauth/access_token"; // Example proxy
const response = await fetch(tokenUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code: code
})
});
if (response.ok) {
const data = await response.json();
if (data.access_token) {
localStorage.setItem("github_access_token", data.access_token);
await this.fetchUserProfile(data.access_token);
} else {
console.error("Auth failed:", data);
alert("Authentication failed: " + (data.error_description || "Unknown error"));
}
} else {
console.error("Network response not ok during Auth");
alert("Failed to connect to GitHub for token exchange. Possible CORS issue.");
}
} catch (error) {
console.error("Auth Error:", error);
alert("Authentication Error. Check console. (Likely CORS on client-side token exchange)");
}
},
fetchUserProfile: async function(token) {
try {
const response = await fetch("https://api.github.com/user", {
headers: {
"Authorization": `token ${token}`
}
});
if (response.ok) {
const user = await response.json();
localStorage.setItem("github_user", JSON.stringify(user));
this.updateUI();
}
} catch (e) {
console.error("Failed to fetch user profile", e);
}
},
updateUI: function() {
const userJson = localStorage.getItem("github_user");
const loginBtn = document.getElementById("login-btn");
const userDisplay = document.getElementById("user-display");
const userAvatar = document.getElementById("user-avatar-login");
const userName = document.getElementById("user-name-login");
if (userJson) {
const user = JSON.parse(userJson);
if (loginBtn) loginBtn.style.display = "none";
if (userDisplay) {
userDisplay.style.display = "flex";
if(userAvatar) userAvatar.src = user.avatar_url;
if(userName) userName.innerText = user.login;
}
} else {
if (loginBtn) loginBtn.style.display = "block";
if (userDisplay) userDisplay.style.display = "none";
}
},
getQueryVariable: function(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
};