55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
import React, { useEffect } from 'react';
|
|
import { useSelector } from 'react-redux';
|
|
import { Navigate, Outlet, useLocation, useNavigate } from 'react-router-dom';
|
|
|
|
import Cookies from 'js-cookie';
|
|
|
|
const whiteList = ['/login', '/auth-redirect', '/bind', '/register', '/oauthLogin'];
|
|
|
|
export default function ProtectedRoute() {
|
|
const { isAuthenticated } = useSelector((state) => state.user);
|
|
const location = useLocation();
|
|
const navigate = useNavigate();
|
|
const { pathname, search } = location;
|
|
|
|
|
|
|
|
// 白名单
|
|
if (whiteList.includes(pathname)) {
|
|
return <Outlet />;
|
|
}
|
|
|
|
// 未登录
|
|
if (!isAuthenticated) {
|
|
return <Navigate to={`/login?redirect=${pathname}`} replace />;
|
|
}
|
|
|
|
// 已登录,访问登录页 → 跳首页
|
|
if (pathname === '/login') {
|
|
const queryParams = new URLSearchParams(search);
|
|
const goRemote = queryParams.get('goRemote');
|
|
const clear = queryParams.get('clear');
|
|
|
|
if (goRemote) {
|
|
if (clear === '1') {
|
|
Cookies.remove('userId');
|
|
window.location.href = 'http://ri.satabot.com/#/login?goRemote=1';
|
|
return null;
|
|
}
|
|
|
|
const rawUserId = Cookies.get('userId');
|
|
if (!rawUserId) {
|
|
navigate('/');
|
|
} else {
|
|
const encoded = btoa(unescape(encodeURIComponent(rawUserId)));
|
|
window.location.href = `http://ai.satabot.com/?userId=${encoded}`;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
return <Navigate to="/" replace />;
|
|
}
|
|
|
|
return <Outlet />;
|
|
}
|