-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.tsx
104 lines (90 loc) · 1.76 KB
/
auth.tsx
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
import React from 'react';
import { BrowserRouter as Router, useHistory } from 'react-router-dom';
import { RouteConfig, AWRouter } from 'aw-react-router-helper';
let logged = Number(window.localStorage.getItem('login')) || 0;
interface RouteMeta {
auth: boolean;
}
function login() {
logged = 1;
window.localStorage.setItem('login', '1');
}
function logout() {
logged = 0;
window.localStorage.setItem('login', '0');
}
function checkAuth() {
if (!logged) {
return '/login';
}
}
const Login = () => {
const history = useHistory();
return (
<>
<button type="button" onClick={_ => {
login();
history.push('/home');
}}>登录</button>
</>
);
}
const Home = () => {
const history = useHistory();
return (
<>
<h1>HOME</h1>
<button type="button" onClick={_ => {
logout();
history.push('/login');
}}>登出</button>
</>
);
}
const configs: RouteConfig<RouteMeta>[] = [
{
path: '/',
middlewares: [
() => {
// 未登录默认首页为 login,登录默认首页为 home
return checkAuth() || '/home';
},
],
},
{
path: '/login',
component: Login,
middlewares: [
() => {
// 已登录跳转 home
if (logged) return '/home';
},
],
},
{
path: '/home',
meta: {
auth: true, // 需要登录才能访问
},
component: Home,
},
];
export const routerManager = AWRouter.instance<AWRouter<RouteMeta>>().load({
configs,
middlewares: [
state => {
console.log(state);
if (state.meta && state.meta.auth) {
return checkAuth();
}
},
],
});
function App() {
return (
<Router>
{routerManager.render()}
</Router>
);
}
export default App;