1- import { Component } from "react" ;
1+ import React from "react" ;
22import { connect } from "react-redux" ;
3+ import { withRouter } from "react-router-dom" ;
34
45import { fetchPermissions , loginSuccess } from "../actions/meta" ;
56import { selectIsLoggedIn , selectLocationHash } from "../selectors" ;
6- import { history } from "../config/store" ;
77
8- class Auth extends Component {
8+ class Auth extends React . Component {
99 componentDidMount ( ) {
1010 const {
11- fetchPermissions,
1211 hash : { access_token, expires_in } ,
1312 isLoggedIn,
14- loginSuccess
13+ loginSuccess,
14+ fetchPermissions,
15+ history,
16+ location
1517 } = this . props ;
1618
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+ }
1752 if ( isLoggedIn ) {
1853 fetchPermissions ( ) ;
19- } else if ( access_token != null ) {
20- loginSuccess ( access_token , expires_in ) ;
21- history . replace ( "/" ) ;
2254 }
2355 }
2456
25- componentWillUpdate ( nextProps , nextState ) {
26- const { fetchPermissions, isLoggedIn : wasLoggedIn } = this . props ;
27- const { isLoggedIn } = nextProps ;
57+ componentDidUpdate ( prevProps ) {
2858
29- if ( ! wasLoggedIn && isLoggedIn ) {
30- fetchPermissions ( ) ;
59+ if ( ! prevProps . isLoggedIn && this . props . isLoggedIn ) {
60+ this . props . fetchPermissions ( ) ;
3161 }
3262 }
3363
@@ -41,6 +71,9 @@ const mapStateToProps = state => ({
4171 isLoggedIn : selectIsLoggedIn ( state )
4272} ) ;
4373
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