Skip to content

Commit e2b4868

Browse files
fixing auth redirect
1 parent cf89522 commit e2b4868

File tree

7 files changed

+66
-465
lines changed

7 files changed

+66
-465
lines changed

app/controllers/auth_controller.rb

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,25 @@ class AuthController < ApplicationController
55
skip_before_action :require_login, only: [:get_token, :validate_token]
66

77
# GET /auth/get_token
8-
# Generate and display API token for authenticated SSO user (for Chrome extensions)
9-
# For chrome, we don't need to generate a token, we just need to know the user is authenticated
8+
# Return user email for authenticated SSO user (for Chrome extensions)
109
def get_token
1110
Rails.logger.info '=== AUTH GET_TOKEN CALLED ==='
11+
Rails.logger.info "Session user_id: #{session[:user_id]}"
1212
Rails.logger.info "Current user: #{current_user&.email || 'NOT AUTHENTICATED'}"
13+
Rails.logger.info "Request path: #{request.fullpath}"
1314

14-
# User is authenticated via SSO session, generate token
15+
# User is authenticated via SSO session, return email
1516
if current_user
16-
Rails.logger.info "User authenticated for browser. #{current_user.email}"
17+
Rails.logger.info "✅ User authenticated successfully: #{current_user.email}"
18+
# Render the page with current_user available
1719
else
20+
Rails.logger.info "❌ User not authenticated, redirecting to login"
1821
# User not authenticated, redirect to login with return URL
1922
redirect_to new_session_path(redirect_to: request.fullpath)
2023
end
2124
rescue StandardError => e
2225
Rails.logger.error "Auth error: #{e.message}"
26+
Rails.logger.error e.backtrace.join("\n")
2327
redirect_to root_path, alert: 'Authentication failed. Please try again.'
2428
end
2529

app/controllers/sessions_controller.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,19 @@ def new
88
def create
99
user = User.find_by_email(params[:session][:email])
1010

11-
# Debug logging
12-
Rails.logger.info "Login attempt for: #{params[:session][:email]}"
13-
1411
if user&.authenticate(params[:session][:password])
1512
login_user(user)
13+
Rails.logger.info "User logged in: #{user.email}"
1614

1715
# Use redirect_to parameter if provided, otherwise fallback to previous page or root
1816
if params[:redirect_to].present?
17+
Rails.logger.info "Redirecting to: #{params[:redirect_to]}"
1918
redirect_to params[:redirect_to]
2019
else
2120
redirect_to(root_path)
2221
end
2322
else
23+
Rails.logger.info "Login failed for: #{params[:session][:email]}"
2424
# Preserve redirect_to parameter on failed login
2525
redirect_params = params[:redirect_to].present? ? { redirect_to: params[:redirect_to] } : {}
2626
redirect_to new_session_url(redirect_params), notice: 'Error logging in.'

app/views/auth/get_token.html.erb

Lines changed: 21 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -5,123 +5,40 @@
55
<div class="text-5xl text-green-500 mb-5"></div>
66
<h1 class="text-gray-800 mb-5 text-2xl font-semibold">Authentication Successful</h1>
77

8-
<p class="mb-5">Your API token has been generated for the Chrome extension:</p>
8+
<p class="mb-5">Your user email for the Chrome extension:</p>
99

1010
<div class="bg-gray-50 border-2 border-dashed border-gray-300 rounded-lg p-5 my-5 break-all font-mono text-sm min-h-15 flex items-center justify-center">
11-
<div id="token-display" data-token="<%= current_user.email %>" class="text-gray-500 italic">
12-
<% if current_user.email %>
13-
Loading token...
14-
<% else %>
15-
No token available. Please try again.
16-
<% end %>
11+
<div id="token-display" data-token="<%= current_user&.email %>" class="text-sky-600 font-semibold">
12+
<%= current_user&.email || 'No email available. Please try again.' %>
1713
</div>
1814
</div>
1915

20-
<button id="copy-btn" class="bg-sky-600 text-white border-none py-2 px-5 rounded cursor-pointer mt-4 text-sm disabled:bg-gray-400 disabled:cursor-not-allowed hover:bg-sky-700" disabled>Copy Token</button>
21-
2216
<div class="text-gray-600 text-sm leading-relaxed mt-5">
2317
<strong>Instructions:</strong><br>
24-
1. The token above will be automatically captured by your Chrome extension<br>
25-
2. If using manually, copy the token and paste it into your extension<br>
26-
3. You can safely close this window after the token is captured
18+
Your email above will be automatically captured by your Chrome extension.<br>
19+
You can safely close this window after the email is captured.
2720
</div>
28-
29-
<div class="bg-yellow-50 border border-yellow-200 rounded p-4 mt-5 text-yellow-700 text-sm">
30-
<strong>Note:</strong> This window will automatically close in 10 seconds, or you can close it manually once the extension has captured the token.
21+
<!-- Debug info (remove in production) -->
22+
<div class="bg-gray-100 border border-gray-300 rounded p-3 mt-3 text-xs text-gray-600">
23+
<strong>Debug:</strong> User: <%= current_user&.email || 'NOT AUTHENTICATED' %> |
24+
Session: <%= session[:user_id] || 'NO SESSION' %>
3125
</div>
3226
</div>
3327
</div>
3428

3529
<script>
36-
// Extract token from data attribute
37-
function extractToken() {
38-
const tokenDisplay = document.getElementById('token-display');
39-
const token = tokenDisplay.getAttribute('data-token');
40-
return token && token.length > 0 ? token : null;
41-
}
42-
43-
// Display the token
44-
function displayToken() {
45-
const token = extractToken();
46-
const tokenDisplay = document.getElementById('token-display');
47-
const copyBtn = document.getElementById('copy-btn');
48-
49-
if (token) {
50-
tokenDisplay.textContent = token;
51-
tokenDisplay.className = 'text-sky-600 font-semibold';
52-
copyBtn.disabled = false;
53-
54-
// Post message to parent window (for Chrome extension)
55-
if (window.opener) {
56-
window.opener.postMessage({
57-
type: 'FACK_AUTH_TOKEN',
58-
token: token,
59-
success: true
60-
}, '*');
61-
}
62-
63-
// Also try posting to parent frame
64-
if (window.parent && window.parent !== window) {
65-
window.parent.postMessage({
66-
type: 'FACK_AUTH_TOKEN',
67-
token: token,
68-
success: true
69-
}, '*');
70-
}
71-
} else {
72-
tokenDisplay.textContent = 'No token found. Please try again.';
73-
tokenDisplay.className = 'text-gray-500 italic';
74-
}
75-
}
76-
77-
// Copy token to clipboard
78-
function copyToken() {
79-
const token = extractToken();
80-
if (token) {
81-
navigator.clipboard.writeText(token).then(() => {
82-
const btn = document.getElementById('copy-btn');
83-
const originalText = btn.textContent;
84-
btn.textContent = 'Copied!';
85-
btn.className = btn.className.replace('bg-sky-600', 'bg-green-500').replace('hover:bg-sky-700', '');
86-
87-
setTimeout(() => {
88-
btn.textContent = originalText;
89-
btn.className = btn.className.replace('bg-green-500', 'bg-sky-600') + ' hover:bg-sky-700';
90-
}, 2000);
91-
}).catch(err => {
92-
console.error('Could not copy token:', err);
93-
// Fallback: select text
94-
const tokenDisplay = document.getElementById('token-display');
95-
const range = document.createRange();
96-
range.selectNode(tokenDisplay);
97-
window.getSelection().removeAllRanges();
98-
window.getSelection().addRange(range);
99-
});
100-
}
101-
}
102-
103-
// Auto-close window after delay
104-
function scheduleAutoClose() {
105-
setTimeout(() => {
106-
if (window.opener || window.parent !== window) {
30+
console.log('Auth page loaded - email should be captured by Chrome extension content script');
31+
console.log('Email in data-token:', document.getElementById('token-display')?.getAttribute('data-token'));
32+
33+
// Auto-close window after extension captures token
34+
setTimeout(() => {
35+
console.log('Auto-closing window...');
36+
if (window.opener || window.parent !== window) {
37+
try {
10738
window.close();
39+
} catch (e) {
40+
console.log('Could not close window automatically');
10841
}
109-
}, 10000); // 10 seconds
110-
}
111-
112-
// Initialize
113-
document.addEventListener('DOMContentLoaded', () => {
114-
displayToken();
115-
scheduleAutoClose();
116-
117-
document.getElementById('copy-btn').addEventListener('click', copyToken);
118-
119-
// Listen for messages from Chrome extension
120-
window.addEventListener('message', (event) => {
121-
if (event.data.type === 'FACK_TOKEN_CAPTURED') {
122-
// Extension has captured the token, can close window
123-
setTimeout(() => window.close(), 1000);
124-
}
125-
});
126-
});
42+
}
43+
}, 5000); // Reduced to 5 seconds
12744
</script>

chrome-extension/auth-content.js

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ function checkForToken() {
4848

4949
// Note: The auth page handles postMessage communication directly, so no listener needed here
5050

51-
// Main initialization
51+
// Main initialization with better redirect handling
5252
function init() {
5353
console.log('Initializing auth content script');
5454

@@ -57,15 +57,38 @@ function init() {
5757
return;
5858
}
5959

60-
// If not found immediately, wait for DOM to be ready
61-
if (document.readyState === 'loading') {
62-
document.addEventListener('DOMContentLoaded', () => {
63-
setTimeout(() => checkForToken(), 100);
64-
});
65-
} else {
66-
// DOM is already ready, try again after a short delay
60+
// Set up polling with multiple attempts
61+
let attempts = 0;
62+
const maxAttempts = 30; // 15 seconds total (500ms * 30)
63+
64+
const pollForToken = () => {
65+
attempts++;
66+
console.log(`Polling for token, attempt ${attempts}/${maxAttempts}`);
67+
68+
if (checkForToken() || attempts >= maxAttempts) {
69+
if (attempts >= maxAttempts && !tokenSent) {
70+
console.log('❌ Token polling timeout - token not found after 15 seconds');
71+
}
72+
return;
73+
}
74+
75+
setTimeout(pollForToken, 500);
76+
};
77+
78+
// Start polling immediately
79+
setTimeout(pollForToken, 100);
80+
81+
// Also listen for DOM changes (Turbo redirects)
82+
document.addEventListener('DOMContentLoaded', () => {
83+
console.log('DOM ready - checking for token again');
6784
setTimeout(() => checkForToken(), 100);
68-
}
85+
});
86+
87+
// Listen for Turbo redirects specifically
88+
document.addEventListener('turbo:load', () => {
89+
console.log('Turbo load detected - checking for token again');
90+
setTimeout(() => checkForToken(), 100);
91+
});
6992
}
7093

7194
// Start the initialization

chrome-extension/manifest.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,13 @@
2222
},
2323
{
2424
"matches": [
25+
"http://localhost:3000/auth/get_token",
2526
"http://localhost:3000/auth/*",
2627
"http://*/auth/*",
2728
"https://*/auth/*"
2829
],
2930
"js": ["auth-content.js"],
30-
"run_at": "document_start"
31+
"run_at": "document_end"
3132
}
3233
],
3334
"action": {

0 commit comments

Comments
 (0)