Remove .env.local file and update middleware, page, and auth callback files to enhance logging and user experience. Translate comments and console logs to English for better clarity. Refactor Create Short URL form and Debug page for improved user feedback and error handling.

This commit is contained in:
2025-04-23 18:17:41 +08:00
parent ebb1e77ecc
commit bee8369a6b
9 changed files with 196 additions and 192 deletions

View File

@@ -9,38 +9,38 @@ export async function GET(request: NextRequest) {
console.log('Auth callback received:', { url: request.url, hasCode: !!code });
// 如果没有code参数则重定向到登录页面
// If no code parameter found, redirect to login page
if (!code) {
console.log('没有找到code参数重定向到登录页面');
console.log('No code parameter found, redirecting to login page');
return NextResponse.redirect(new URL('/login', request.url));
}
try {
// 创建supabase客户端
// Create Supabase client
const cookieStore = cookies();
const supabaseRouteHandler = createRouteHandlerClient({ cookies: () => cookieStore });
// 交换code获取会话
console.log('开始交换code获取会话');
// Exchange code for session
console.log('Starting code exchange for session');
const { data, error } = await supabaseRouteHandler.auth.exchangeCodeForSession(code);
if (error) {
console.error('交换会话时出错:', error);
console.error('Error exchanging code for session:', error);
throw error;
}
console.log('成功获取会话,用户:', data.session?.user.email);
console.log('Successfully retrieved session, user:', data.session?.user.email);
// 检查会话是否成功创建
// Check if session was successfully created
if (data.session) {
console.log('会话创建成功:', {
console.log('Session created successfully:', {
userId: data.session.user.id,
email: data.session.user.email,
expiresAt: data.session.expires_at ? new Date(data.session.expires_at * 1000).toISOString() : 'unknown'
});
// 设置额外的cookie以确保客户端能检测到登录状态
// 使用Next.jsResponse来设置cookie
// Set additional cookie to ensure client can detect login status
// Use Next.js Response to set cookie
const response = NextResponse.redirect(new URL('/', request.url));
response.cookies.set({
name: 'sb-auth-token',
@@ -51,16 +51,16 @@ export async function GET(request: NextRequest) {
secure: process.env.NODE_ENV === 'production',
httpOnly: false,
});
console.log('设置了备用cookie: sb-auth-token');
console.log('Set backup cookie: sb-auth-token');
return response;
}
// 优先使用应用程序根路径重定向
console.log('重定向到首页');
// Redirect to home page by default
console.log('Redirecting to home page');
return NextResponse.redirect(new URL('/', request.url));
} catch (error) {
console.error('Auth callback error:', error);
// 出错时重定向到登录页面
// Redirect to login page on error
return NextResponse.redirect(
new URL('/login?message=Authentication failed. Please try again.', request.url)
);

View File

@@ -47,11 +47,11 @@ function CreateShortUrlForm() {
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
// 使用 useEffect 在加载时添加用户信息到表单数据中
// Use useEffect to add user information to form data when loading
useEffect(() => {
if (user) {
console.log('当前用户:', user.email);
// 可以在这里添加用户相关数据到表单中
console.log('Current user:', user.email);
// Can add user-related data to the form here
}
}, [user]);
@@ -93,32 +93,32 @@ function CreateShortUrlForm() {
setError(null);
try {
// 验证必填字段
// Validate required fields
if (!formData.originalUrl) {
throw new Error('原始 URL 是必填项');
throw new Error('Original URL is required');
}
if (!formData.title) {
throw new Error('标题是必填项');
throw new Error('Title is required');
}
if (!formData.teamId) {
throw new Error('团队是必填项');
throw new Error('Team is required');
}
if (!formData.projectId) {
throw new Error('项目是必填项');
throw new Error('Project is required');
}
if (!formData.domain) {
throw new Error('域名是必填项');
throw new Error('Domain is required');
}
// 按照API要求构建请求数据
// Build request data according to API requirements
const requestData = {
type: "shorturl",
attributes: {
// 可以添加任何额外属性但attributes不能为空
// Can add any additional attributes, but attributes cannot be empty
icon: ""
},
shortUrl: {
@@ -134,20 +134,20 @@ function CreateShortUrlForm() {
tagIds: formData.tags && formData.tags.length > 0 ? formData.tags : undefined
};
// 调用 API 创建 shorturl 资源
// Call API to create shorturl resource
const response = await limqRequest('resource/shorturl', 'POST', requestData as unknown as Record<string, unknown>);
console.log('创建成功:', response);
console.log('Creation successful:', response);
setSuccess(true);
// 2秒后跳转到链接列表页面
// Redirect to links list page after 2 seconds
setTimeout(() => {
router.push('/links');
}, 2000);
} catch (err) {
console.error('创建短链接失败:', err);
setError(err instanceof Error ? err.message : '创建短链接失败,请稍后重试');
console.error('Failed to create short URL:', err);
setError(err instanceof Error ? err.message : 'Failed to create short URL, please try again later');
} finally {
setIsSubmitting(false);
}
@@ -188,7 +188,7 @@ function CreateShortUrlForm() {
</div>
<div className="ml-3">
<p className="text-sm text-green-700">
...
Short URL created successfully! Redirecting...
</p>
</div>
</div>
@@ -196,10 +196,10 @@ function CreateShortUrlForm() {
)}
<form onSubmit={handleSubmit} className="p-6 space-y-6">
{/* 标题 */}
{/* Title */}
<div>
<label htmlFor="title" className="block text-sm font-medium text-gray-700">
<span className="text-red-500">*</span>
Title <span className="text-red-500">*</span>
</label>
<input
type="text"
@@ -207,16 +207,16 @@ function CreateShortUrlForm() {
name="title"
value={formData.title}
onChange={handleChange}
placeholder="例如:产品发布活动"
placeholder="e.g.: Product Launch Campaign"
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
required
/>
</div>
{/* 原始 URL */}
{/* Original URL */}
<div>
<label htmlFor="originalUrl" className="block text-sm font-medium text-gray-700">
URL <span className="text-red-500">*</span>
Original URL <span className="text-red-500">*</span>
</label>
<input
type="url"
@@ -230,10 +230,10 @@ function CreateShortUrlForm() {
/>
</div>
{/* 自定义短链接 */}
{/* Custom Short Link */}
<div>
<label htmlFor="customSlug" className="block text-sm font-medium text-gray-700">
<span className="text-gray-500">()</span>
Custom Short Link <span className="text-gray-500">(Optional)</span>
</label>
<div className="flex mt-1 rounded-md shadow-sm">
<span className="inline-flex items-center px-3 py-2 text-sm text-gray-500 border border-r-0 border-gray-300 rounded-l-md bg-gray-50">
@@ -250,14 +250,14 @@ function CreateShortUrlForm() {
/>
</div>
<p className="mt-1 text-xs text-gray-500">
Leave blank to generate a random short link
</p>
</div>
{/* 域名 */}
{/* Domain */}
<div>
<label htmlFor="domain" className="block text-sm font-medium text-gray-700">
<span className="text-red-500">*</span>
Domain <span className="text-red-500">*</span>
</label>
<input
type="text"
@@ -265,16 +265,16 @@ function CreateShortUrlForm() {
name="domain"
value={formData.domain}
onChange={handleChange}
placeholder="例如:googleads.link"
placeholder="e.g.: googleads.link"
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
required
/>
</div>
{/* 团队选择 */}
{/* Team Selection */}
<div>
<label htmlFor="teamId" className="block text-sm font-medium text-gray-700">
<span className="text-red-500">*</span>
Team <span className="text-red-500">*</span>
</label>
<div className="mt-1">
<TeamSelector
@@ -283,7 +283,7 @@ function CreateShortUrlForm() {
setFormData(prev => ({
...prev,
teamId: teamId as string,
// 当团队变更时清除已选项目
// Clear selected project when team changes
projectId: ''
}));
}}
@@ -291,10 +291,10 @@ function CreateShortUrlForm() {
</div>
</div>
{/* 项目选择 */}
{/* Project Selection */}
<div>
<label htmlFor="projectId" className="block text-sm font-medium text-gray-700">
<span className="text-red-500">*</span>
Project <span className="text-red-500">*</span>
</label>
<div className="mt-1">
<ProjectSelector
@@ -310,10 +310,10 @@ function CreateShortUrlForm() {
</div>
</div>
{/* 描述 */}
{/* Description */}
<div>
<label htmlFor="description" className="block text-sm font-medium text-gray-700">
<span className="text-gray-500">()</span>
Description <span className="text-gray-500">(Optional)</span>
</label>
<textarea
id="description"
@@ -321,15 +321,15 @@ function CreateShortUrlForm() {
value={formData.description}
onChange={handleChange}
rows={3}
placeholder="对此链接的简短描述"
placeholder="A brief description of this link"
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
/>
</div>
{/* 标签 */}
{/* Tags */}
<div>
<label htmlFor="tagInput" className="block text-sm font-medium text-gray-700">
<span className="text-gray-500">()</span>
Tags <span className="text-gray-500">(Optional)</span>
</label>
<div className="flex mt-1 rounded-md shadow-sm">
<input
@@ -338,7 +338,7 @@ function CreateShortUrlForm() {
value={tagInput}
onChange={(e) => setTagInput(e.target.value)}
onKeyDown={handleTagKeyDown}
placeholder="添加标签并按 Enter"
placeholder="Add a tag and press Enter"
className="flex-1 block w-full min-w-0 px-3 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
/>
<button
@@ -346,7 +346,7 @@ function CreateShortUrlForm() {
onClick={addTag}
className="inline-flex items-center px-3 py-2 text-sm font-medium text-white border border-transparent rounded-r-md shadow-sm bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Add
</button>
</div>
@@ -360,7 +360,7 @@ function CreateShortUrlForm() {
onClick={() => removeTag(tag)}
className="flex-shrink-0 ml-1 text-blue-500 rounded-full hover:text-blue-700 focus:outline-none"
>
<span className="sr-only"> {tag}</span>
<span className="sr-only">Remove tag {tag}</span>
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
@@ -371,14 +371,14 @@ function CreateShortUrlForm() {
)}
</div>
{/* 提交按钮 */}
{/* Submit Button */}
<div className="flex justify-end pt-4 border-t border-gray-200">
<button
type="button"
onClick={() => router.back()}
className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 mr-3"
>
Cancel
</button>
<button
type="submit"
@@ -391,9 +391,9 @@ function CreateShortUrlForm() {
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
...
Processing...
</>
) : '创建短链接'}
) : 'Create Short URL'}
</button>
</div>
</form>

View File

@@ -3,16 +3,22 @@
import { useState, useEffect } from 'react';
import { useAuth } from '@/lib/auth';
import supabase from '@/lib/supabase';
import { Session, User } from '@supabase/supabase-js';
interface SessionData {
session: Session | null;
user?: User | null;
}
export default function DebugPage() {
const { user, session, isLoading } = useAuth();
const [cookies, setCookies] = useState<Record<string, string>>({});
const [rawCookies, setRawCookies] = useState('');
const [sessionData, setSessionData] = useState<{ session: any; user: any } | null>(null);
const [sessionData, setSessionData] = useState<SessionData | null>(null);
const [redirectTarget, setRedirectTarget] = useState('/analytics');
useEffect(() => {
// 获取所有cookie
// Get all cookies
const allCookies = document.cookie.split(';').reduce((acc, cookie) => {
const [key, value] = cookie.trim().split('=');
if (key) acc[key] = value || '';
@@ -22,10 +28,10 @@ export default function DebugPage() {
setCookies(allCookies);
setRawCookies(document.cookie);
// 测试supabase会话
// Test Supabase session
const testSession = async () => {
try {
console.log('正在获取Supabase会话');
console.log('Getting Supabase session');
const { data, error } = await supabase.auth.getSession();
console.log('Supabase session result:', { data, error });
@@ -35,7 +41,7 @@ export default function DebugPage() {
setSessionData(data);
}
} catch (err) {
console.error('获取会话出错:', err);
console.error('Error getting session:', err);
}
};
@@ -44,17 +50,17 @@ export default function DebugPage() {
const refreshSession = async () => {
try {
console.log('手动刷新会话');
console.log('Manually refreshing session');
const { data, error } = await supabase.auth.refreshSession();
console.log('刷新结果:', { data, error });
alert('会话刷新完成,请查看控制台日志');
console.log('Refresh result:', { data, error });
alert('Session refresh complete, please check console logs');
if (!error && data.session) {
window.location.reload();
}
} catch (err) {
console.error('刷新会话出错:', err);
alert('刷新会话出错: ' + String(err));
console.error('Error refreshing session:', err);
alert('Error refreshing session: ' + String(err));
}
};
@@ -66,58 +72,58 @@ export default function DebugPage() {
return (
<div className="container mx-auto p-8">
<h1 className="text-3xl font-bold mb-6"></h1>
<h1 className="text-3xl font-bold mb-6">Authentication Debug Page</h1>
<div className="bg-gray-100 p-6 rounded-lg mb-6">
<h2 className="text-xl font-semibold mb-4"></h2>
<h2 className="text-xl font-semibold mb-4">User Status</h2>
<div className="space-y-2">
<p>: {isLoading ? '加载中...' : '已加载'}</p>
<p>: {user ? '' : ''}</p>
<p>: {user?.email || '未登录'}</p>
<p>ID: {user?.id || '未登录'}</p>
<p>: {session ? '' : ''}</p>
<p>: {session?.expires_at ? new Date(session.expires_at * 1000).toLocaleString() : '无会话'}</p>
<p>Loading status: {isLoading ? 'Loading...' : 'Loaded'}</p>
<p>Logged in: {user ? 'Yes' : 'No'}</p>
<p>User email: {user?.email || 'Not logged in'}</p>
<p>User ID: {user?.id || 'Not logged in'}</p>
<p>Session valid: {session ? 'Yes' : 'No'}</p>
<p>Session expires: {session?.expires_at ? new Date(session.expires_at * 1000).toLocaleString() : 'No session'}</p>
</div>
</div>
<div className="bg-gray-100 p-6 rounded-lg mb-6">
<h2 className="text-xl font-semibold mb-4">Supabase </h2>
<h2 className="text-xl font-semibold mb-4">Supabase Session Data</h2>
<pre className="bg-gray-200 p-4 rounded text-xs overflow-auto max-h-60">
{sessionData ? JSON.stringify(sessionData, null, 2) : '加载中...'}
{sessionData ? JSON.stringify(sessionData, null, 2) : 'Loading...'}
</pre>
<button
onClick={refreshSession}
className="mt-4 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
>
Refresh Session
</button>
</div>
<div className="bg-gray-100 p-6 rounded-lg mb-6">
<h2 className="text-xl font-semibold mb-4">Cookies </h2>
<h2 className="text-xl font-semibold mb-4">Cookie Information</h2>
<div className="space-y-2">
<p className="text-sm mb-2">Cookie字符串:</p>
<p className="text-sm mb-2">Raw cookie string:</p>
<pre className="bg-gray-200 p-4 rounded overflow-x-auto text-xs">
{rawCookies || '(empty)'}
</pre>
<p className="text-sm mt-4 mb-2">Cookies:</p>
<p className="text-sm mt-4 mb-2">Parsed cookies:</p>
<pre className="bg-gray-200 p-4 rounded overflow-x-auto text-xs">
{JSON.stringify(cookies, null, 2) || '{}'}
</pre>
<p className="text-sm mt-4 mb-2">Supabase相关Cookies:</p>
<p className="text-sm mt-4 mb-2">Supabase-related cookies:</p>
<div className="space-y-1">
<p>sb-access-token: {cookies['sb-access-token'] ? '存在' : '不存在'}</p>
<p>sb-refresh-token: {cookies['sb-refresh-token'] ? '存在' : '不存在'}</p>
<p>supabase-auth-token: {cookies['supabase-auth-token'] ? '存在' : '不存在'}</p>
<p>sb-access-token: {cookies['sb-access-token'] ? 'Exists' : 'Not found'}</p>
<p>sb-refresh-token: {cookies['sb-refresh-token'] ? 'Exists' : 'Not found'}</p>
<p>supabase-auth-token: {cookies['supabase-auth-token'] ? 'Exists' : 'Not found'}</p>
</div>
</div>
</div>
<div className="bg-gray-100 p-6 rounded-lg mb-6">
<h2 className="text-xl font-semibold mb-4"></h2>
<h2 className="text-xl font-semibold mb-4">Manual Redirect</h2>
<div className="flex space-x-2 items-center">
<input
type="text"
@@ -130,7 +136,7 @@ export default function DebugPage() {
onClick={forceRedirect}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
Force Redirect
</button>
</div>
</div>
@@ -140,21 +146,21 @@ export default function DebugPage() {
onClick={() => window.location.href = '/login'}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
Go to Login
</button>
<button
onClick={async () => {
try {
await supabase.auth.signOut();
alert('已登出,刷新页面中...');
alert('Signed out, refreshing page...');
window.location.reload();
} catch (err) {
alert('登出出错: ' + String(err));
alert('Error signing out: ' + String(err));
}
}}
className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
>
Sign Out
</button>
</div>
</div>

View File

@@ -29,7 +29,7 @@ export default function LoginPage() {
const [message, setMessage] = useState({ type: '', content: '' });
const [redirectUrl, setRedirectUrl] = useState<string | null>(null);
// 获取重定向URL
// Get redirect URL
useEffect(() => {
if (searchParams) {
const redirect = searchParams.get('redirect');
@@ -39,19 +39,19 @@ export default function LoginPage() {
}
}, [searchParams]);
// 如果用户已登录,重定向到原始页面或首页
// If user is logged in, redirect to original page or home page
useEffect(() => {
if (user) {
console.log('用户已登录,准备重定向', { redirectUrl });
console.log('User is logged in, preparing to redirect', { redirectUrl });
// 添加短暂延时确保状态更新完成
// Add a short delay to ensure state updates are complete
setTimeout(() => {
if (redirectUrl) {
// 使用硬重定向替代router.push
console.log('重定向到原始URL:', redirectUrl);
// Use hard redirect instead of router.push
console.log('Redirecting to original URL:', redirectUrl);
window.location.href = redirectUrl;
} else {
console.log('重定向到首页');
console.log('Redirecting to home page');
window.location.href = '/';
}
}, 100);
@@ -79,7 +79,7 @@ export default function LoginPage() {
throw new Error(error instanceof Error ? error.message : 'Unknown error');
}
// 登录成功后,会通过 useEffect 重定向
// After successful login, redirect via useEffect
} catch (error) {
console.error('Login error:', error);
setMessage({

View File

@@ -6,32 +6,32 @@ import { useAuth } from '@/lib/auth';
export default function Home() {
const { user, isLoading } = useAuth();
// 添加调试日志
console.log('根页面状态:', { isLoading, userAuthenticated: !!user });
// Add debug logs
console.log('Root page state:', { isLoading, userAuthenticated: !!user });
useEffect(() => {
if (!isLoading) {
console.log('准备从根页面重定向', { isLoggedIn: !!user });
console.log('Preparing to redirect from root page', { isLoggedIn: !!user });
// 使用硬重定向确保页面完全刷新
// Use hard redirect to ensure full page refresh
if (user) {
console.log('用户已登录,重定向到分析页面');
console.log('User is logged in, redirecting to analytics page');
window.location.href = '/analytics';
} else {
console.log('用户未登录,重定向到登录页面');
console.log('User is not logged in, redirecting to login page');
window.location.href = '/login';
}
}
}, [isLoading, user]);
// 显示加载指示器,并包含状态信息
// Display loading indicator with status information
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500 mx-auto"></div>
<p className="mt-4 text-lg text-gray-700">...</p>
<p className="mt-4 text-lg text-gray-700">Loading...</p>
<p className="mt-2 text-sm text-gray-500">
: {isLoading ? '检查登录中' : (user ? '已登录' : '未登录')}
Status: {isLoading ? 'Checking login status' : (user ? 'Logged in' : 'Not logged in')}
</p>
</div>
</div>