-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
167 lines (139 loc) · 4.81 KB
/
Copy pathauth.js
File metadata and controls
167 lines (139 loc) · 4.81 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// auth.js - Google OAuth using chrome.identity API
/**
* Authenticate user with Google using chrome.identity
* @returns {Promise<{token: string, userEmail: string}>}
*/
async function authenticateWithGoogle() {
try {
console.log('[Auth] Starting Google OAuth flow...');
// Launch OAuth flow
const redirectURL = chrome.identity.getRedirectURL();
console.log('[Auth] Redirect URL:', redirectURL);
// Get OAuth token from Google
return new Promise((resolve, reject) => {
chrome.identity.getAuthToken({ interactive: true }, async (token) => {
if (chrome.runtime.lastError) {
console.error('[Auth] OAuth error:', chrome.runtime.lastError);
reject(chrome.runtime.lastError);
return;
}
if (!token) {
reject(new Error('No token received'));
return;
}
console.log('[Auth] Google token received');
try {
// Send token to backend to get JWT
const response = await fetch(`${API_URL}/auth/google`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Backend authentication failed');
}
console.log('[Auth] Backend authentication successful');
// Get user info from Google
const userInfoResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: { 'Authorization': `Bearer ${token}` }
});
const userInfo = await userInfoResponse.json();
// Store in chrome.storage
await chrome.storage.local.set({
token: data.token,
userEmail: userInfo.email,
googleToken: token
});
console.log('[Auth] Credentials stored');
resolve({
token: data.token,
userEmail: userInfo.email
});
} catch (error) {
console.error('[Auth] Backend error:', error);
reject(error);
}
});
});
} catch (error) {
console.error('[Auth] Authentication failed:', error);
throw error;
}
}
/**
* Try silent authentication (if user previously authorized)
* @returns {Promise<{token: string, userEmail: string} | null>}
*/
async function trySilentAuth() {
try {
console.log('[Auth] Trying silent authentication...');
return new Promise((resolve) => {
chrome.identity.getAuthToken({ interactive: false }, async (token) => {
if (chrome.runtime.lastError || !token) {
console.log('[Auth] Silent auth not available');
resolve(null);
return;
}
console.log('[Auth] Silent auth successful');
try {
// Verify token with backend
const response = await fetch(`${API_URL}/auth/google`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token })
});
const data = await response.json();
if (!response.ok) {
resolve(null);
return;
}
// Get user info
const userInfoResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: { 'Authorization': `Bearer ${token}` }
});
const userInfo = await userInfoResponse.json();
// Store credentials
await chrome.storage.local.set({
token: data.token,
userEmail: userInfo.email,
googleToken: token
});
resolve({
token: data.token,
userEmail: userInfo.email
});
} catch (error) {
console.error('[Auth] Silent auth backend error:', error);
resolve(null);
}
});
});
} catch (error) {
console.error('[Auth] Silent auth failed:', error);
return null;
}
}
/**
* Logout user
*/
async function logout() {
try {
const { googleToken } = await chrome.storage.local.get(['googleToken']);
if (googleToken) {
// Revoke Google token
chrome.identity.removeCachedAuthToken({ token: googleToken }, () => {
console.log('[Auth] Google token revoked');
});
}
// Clear storage
await chrome.storage.local.clear();
console.log('[Auth] Logged out');
} catch (error) {
console.error('[Auth] Logout error:', error);
}
}
// Export functions
if (typeof module !== 'undefined' && module.exports) {
module.exports = { authenticateWithGoogle, trySilentAuth, logout };
}