summaryrefslogtreecommitdiff
path: root/app/client/auth/auth.gate.js
blob: 574feb3a99936598867a53b59d4e2266740c75d8 (plain)
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
import { h, Component } from 'preact';
// import PropTypes from 'prop-types';
import { BrowserRouter, Route, Switch, Redirect, withRouter } from 'react-router-dom'
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import { history } from '../store'
import * as authActions from './auth.actions';

import Login from './login.component';
import Logout from './logout.component';
import Signup from './signup.component';

import { randint } from '../util/math'

class AuthRouter extends Component {
  render(){
    return (
      <BrowserRouter>
        <div>
          <div className="diamond"></div>
          <Switch>
            <Route exact path='/' component={Login} />
            <Route exact path='/login' component={Login} />
            <Route exact path='/logout' component={Logout} />
            <Route exact path='/signup' component={Signup} />
            <Route component={props => {
              this.props.actions.setReturnTo(props.location.pathname)
              return (
                <Redirect to="/login" />
              )
            }} />
          </Switch>
        </div>
      </BrowserRouter>
    )
  }
  componentDidMount(){
    document.querySelector('.diamond').style.backgroundImage = 'linear-gradient(' + (randint(40)-5) + 'deg, #fde, #ffe)'
  }
}

class AuthGate extends Component {
  render(){
    if (!this.props.auth.initialized) {
      return <div className='loading'>Loading</div>
    }
    if (this.props.auth.isAuthenticated) {
      if (this.props.auth.returnTo) {
        let { returnTo } = this.props.auth
        if (!returnTo || returnTo.match(/(login|logout|signup)/i)) {
          returnTo = '/'
        }
        this.props.actions.setReturnTo(null)
        history.push(returnTo)
        return <div>Launching app</div>
      }
      return <div>{this.props.children}</div>
    }
    return <AuthRouter {...this.props} />
  }
  componentDidMount(){
    this.props.actions.checkin()
  }
}

const mapStateToProps = (state) => ({
  auth: state.auth
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(authActions, dispatch)
});

export default connect(mapStateToProps, mapDispatchToProps)(AuthGate);