1
- import { Component } from "react" ;
1
+ import React from "react" ;
2
2
import { connect } from "react-redux" ;
3
+ import { withRouter } from "react-router-dom" ;
3
4
4
5
import { fetchPermissions , loginSuccess } from "../actions/meta" ;
5
6
import { selectIsLoggedIn , selectLocationHash } from "../selectors" ;
6
- import { history } from "../config/store" ;
7
7
8
- class Auth extends Component {
8
+ class Auth extends React . Component {
9
9
componentDidMount ( ) {
10
10
const {
11
- fetchPermissions,
12
11
hash : { access_token, expires_in } ,
13
12
isLoggedIn,
14
- loginSuccess
13
+ loginSuccess,
14
+ fetchPermissions,
15
+ history,
16
+ location
15
17
} = this . props ;
16
18
19
+ if ( access_token ) {
20
+ const expiresAt = expires_in
21
+ ? Date . now ( ) + parseInt ( expires_in , 10 ) * 1000
22
+ : null ;
23
+
24
+
25
+ loginSuccess ( access_token , expiresAt ) ;
26
+ localStorage . setItem ( "access_token" , access_token ) ;
27
+ if ( expiresAt ) localStorage . setItem ( "expires_at" , expiresAt ) ;
28
+
29
+
30
+ fetchPermissions ( ) ;
31
+
32
+ window . location . hash = "" ;
33
+ history . replace ( location . pathname ) ;
34
+ return ;
35
+ }
36
+
37
+
38
+ if ( ! isLoggedIn ) {
39
+ const storedToken = localStorage . getItem ( "access_token" ) ;
40
+ const storedExpiry = localStorage . getItem ( "expires_at" ) ;
41
+ if ( storedToken ) {
42
+ const storedExpiresAt = storedExpiry
43
+ ? parseInt ( storedExpiry , 10 )
44
+ : null ;
45
+ if ( ! storedExpiresAt || storedExpiresAt > Date . now ( ) ) {
46
+ loginSuccess ( storedToken , storedExpiresAt ) ;
47
+ } else {
48
+ // expired → clear out
49
+ localStorage . removeItem ( "access_token" ) ;
50
+ localStorage . removeItem ( "expires_at" ) ;
51
+ }
52
+ }
53
+ }
54
+
55
+
17
56
if ( isLoggedIn ) {
18
57
fetchPermissions ( ) ;
19
- } else if ( access_token != null ) {
20
- loginSuccess ( access_token , expires_in ) ;
21
- history . replace ( "/" ) ;
22
58
}
23
59
}
24
60
25
- componentWillUpdate ( nextProps , nextState ) {
26
- const { fetchPermissions, isLoggedIn : wasLoggedIn } = this . props ;
27
- const { isLoggedIn } = nextProps ;
61
+ componentDidUpdate ( prevProps ) {
28
62
29
- if ( ! wasLoggedIn && isLoggedIn ) {
30
- fetchPermissions ( ) ;
63
+ if ( ! prevProps . isLoggedIn && this . props . isLoggedIn ) {
64
+ this . props . fetchPermissions ( ) ;
31
65
}
32
66
}
33
67
@@ -37,10 +71,13 @@ class Auth extends Component {
37
71
}
38
72
39
73
const mapStateToProps = state => ( {
40
- hash : selectLocationHash ( state ) ,
41
- isLoggedIn : selectIsLoggedIn ( state )
74
+ hash : selectLocationHash ( state ) ,
75
+ isLoggedIn : selectIsLoggedIn ( state )
42
76
} ) ;
43
77
44
- export default connect ( mapStateToProps , { fetchPermissions, loginSuccess } ) (
45
- Auth
46
- ) ;
78
+ export default withRouter (
79
+ connect (
80
+ mapStateToProps ,
81
+ { fetchPermissions, loginSuccess }
82
+ ) ( Auth )
83
+ ) ;
0 commit comments