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
+ loginSuccess ( access_token , expiresAt ) ;
25
+ localStorage . setItem ( "access_token" , access_token ) ;
26
+ if ( expiresAt ) localStorage . setItem ( "expires_at" , expiresAt ) ;
27
+
28
+ fetchPermissions ( ) ;
29
+
30
+ window . location . hash = "" ;
31
+ history . replace ( location . pathname ) ;
32
+ return ;
33
+ }
34
+
35
+
36
+ if ( ! isLoggedIn ) {
37
+ const storedToken = localStorage . getItem ( "access_token" ) ;
38
+ const storedExpiry = localStorage . getItem ( "expires_at" ) ;
39
+ if ( storedToken ) {
40
+ const storedExpiresAt = storedExpiry
41
+ ? parseInt ( storedExpiry , 10 )
42
+ : null ;
43
+ if ( ! storedExpiresAt || storedExpiresAt > Date . now ( ) ) {
44
+ loginSuccess ( storedToken , storedExpiresAt ) ;
45
+ } else {
46
+ // expired
47
+ localStorage . removeItem ( "access_token" ) ;
48
+ localStorage . removeItem ( "expires_at" ) ;
49
+ }
50
+ }
51
+ }
17
52
if ( isLoggedIn ) {
18
53
fetchPermissions ( ) ;
19
- } else if ( access_token != null ) {
20
- loginSuccess ( access_token , expires_in ) ;
21
- history . replace ( "/" ) ;
22
54
}
23
55
}
24
56
25
- componentWillUpdate ( nextProps , nextState ) {
26
- const { fetchPermissions, isLoggedIn : wasLoggedIn } = this . props ;
27
- const { isLoggedIn } = nextProps ;
57
+ componentDidUpdate ( prevProps ) {
28
58
29
- if ( ! wasLoggedIn && isLoggedIn ) {
30
- fetchPermissions ( ) ;
59
+ if ( ! prevProps . isLoggedIn && this . props . isLoggedIn ) {
60
+ this . props . fetchPermissions ( ) ;
31
61
}
32
62
}
33
63
@@ -41,6 +71,9 @@ const mapStateToProps = state => ({
41
71
isLoggedIn : selectIsLoggedIn ( state )
42
72
} ) ;
43
73
44
- export default connect ( mapStateToProps , { fetchPermissions, loginSuccess } ) (
45
- Auth
46
- ) ;
74
+ export default withRouter (
75
+ connect (
76
+ mapStateToProps ,
77
+ { fetchPermissions, loginSuccess }
78
+ ) ( Auth )
79
+ ) ;
0 commit comments