11import type { AppNotification , AppUser } from './store' ;
22
3+ import { isNull } from 'lodash' ;
4+
35import { useACL } from '@react-devui/hooks' ;
46
57import { ROLE_ACL } from '../config/acl' ;
68import { useHttp } from './http' ;
79import { GlobalStore } from './store' ;
8- import { useRefreshToken } from './token' ;
10+ import { TOKEN , TOKEN_REFRESH , TOKEN_REFRESH_OFFSET } from './token' ;
11+
12+ let CLEAR_TOKEN_REFRESH : ( ( ) => void ) | undefined ;
913
1014export function useInit ( ) {
1115 const http = useHttp ( ) ;
1216 const acl = useACL ( ) ;
1317
14- const refreshToken = useRefreshToken ( ) ;
18+ return ( user : AppUser ) => {
19+ acl . setFull ( user . permission . includes ( ROLE_ACL . super_admin ) ) ;
20+ acl . set ( user . permission ) ;
1521
16- const handleUser = ( user : AppUser ) => {
1722 GlobalStore . set ( 'appUser' , user ) ;
1823
19- //#region ACL
20- acl . setFull ( user . permission . includes ( ROLE_ACL . super_admin ) ) ;
21- acl . set ( user . permission ) ;
22- //#endregion
23- } ;
24+ GlobalStore . set ( 'appMenu' , ( draft ) => {
25+ draft . expands = undefined ;
26+ } ) ;
2427
25- const getNotification = ( ) => {
2628 GlobalStore . set ( 'appNotifications' , undefined ) ;
27-
2829 http < AppNotification [ ] > (
2930 {
3031 url : '/notification' ,
@@ -36,18 +37,37 @@ export function useInit() {
3637 GlobalStore . set ( 'appNotifications' , res ) ;
3738 } ,
3839 } ) ;
39- } ;
4040
41- const resetMenu = ( ) => {
42- GlobalStore . set ( 'appMenu' , ( draft ) => {
43- draft . expands = undefined ;
44- } ) ;
45- } ;
41+ CLEAR_TOKEN_REFRESH ?.( ) ;
42+ if ( TOKEN_REFRESH ) {
43+ const refresh = ( ) => {
44+ const expiration = TOKEN . expiration ;
45+ if ( ! isNull ( expiration ) && ! TOKEN . expired ) {
46+ const tid = window . setTimeout ( ( ) => {
47+ const refreshTokenReq = http < string > (
48+ {
49+ url : '/auth/refresh' ,
50+ method : 'post' ,
51+ } ,
52+ { unmount : false }
53+ ) ;
54+ refreshTokenReq . subscribe ( {
55+ next : ( res ) => {
56+ TOKEN . set ( res ) ;
4657
47- return ( user : AppUser ) => {
48- refreshToken ( ) ;
49- handleUser ( user ) ;
50- getNotification ( ) ;
51- resetMenu ( ) ;
58+ refresh ( ) ;
59+ } ,
60+ } ) ;
61+ CLEAR_TOKEN_REFRESH = ( ) => {
62+ refreshTokenReq . abort ( ) ;
63+ } ;
64+ } , expiration - Date . now ( ) - TOKEN_REFRESH_OFFSET ) ;
65+ CLEAR_TOKEN_REFRESH = ( ) => {
66+ clearTimeout ( tid ) ;
67+ } ;
68+ }
69+ } ;
70+ refresh ( ) ;
71+ }
5272 } ;
5373}
0 commit comments