|
| 1 | +import React, { createClass, PropTypes } from 'react' |
| 2 | +import { render } from 'react-dom' |
| 3 | +import { Router, Route, IndexRoute, browserHistory, Link } from 'react-router' |
| 4 | + |
| 5 | +function App(props) { |
| 6 | + return ( |
| 7 | + <div> |
| 8 | + {props.children} |
| 9 | + </div> |
| 10 | + ) |
| 11 | +} |
| 12 | + |
| 13 | +const Form = createClass({ |
| 14 | + contextTypes: { |
| 15 | + router: PropTypes.object.isRequired |
| 16 | + }, |
| 17 | + |
| 18 | + getInitialState() { |
| 19 | + return { |
| 20 | + value: '' |
| 21 | + } |
| 22 | + }, |
| 23 | + |
| 24 | + submitAction(event) { |
| 25 | + event.preventDefault() |
| 26 | + this.context.router.push({ |
| 27 | + pathname: '/page', |
| 28 | + query: { |
| 29 | + qsparam: this.state.value |
| 30 | + } |
| 31 | + }) |
| 32 | + }, |
| 33 | + |
| 34 | + handleChange(event) { |
| 35 | + this.setState({ value: event.target.value }) |
| 36 | + }, |
| 37 | + |
| 38 | + render() { |
| 39 | + return ( |
| 40 | + <form onSubmit={this.submitAction}> |
| 41 | + <p>Token is <em>pancakes</em></p> |
| 42 | + <input type="text" value={this.state.value} onChange={this.handleChange} /> |
| 43 | + <button type="submit">Submit the thing</button> |
| 44 | + <p><Link to="/page?qsparam=pancakes">Or authenticate via URL</Link></p> |
| 45 | + <p><Link to="/page?qsparam=bacon">Or try failing to authenticate via URL</Link></p> |
| 46 | + </form> |
| 47 | + ) |
| 48 | + } |
| 49 | +}) |
| 50 | + |
| 51 | +function Page() { |
| 52 | + return <h1>Hey I see you are authenticated.</h1> |
| 53 | +} |
| 54 | + |
| 55 | +function ErrorPage() { |
| 56 | + return <h1>Oh no! your auth failed!</h1> |
| 57 | +} |
| 58 | + |
| 59 | +function requireCredentials(nextState, replace, next) { |
| 60 | + const query = nextState.location.query |
| 61 | + if (query.qsparam) { |
| 62 | + serverAuth(query.qsparam) |
| 63 | + .then( |
| 64 | + () => next(), |
| 65 | + () => { |
| 66 | + replace('/error') |
| 67 | + next() |
| 68 | + } |
| 69 | + ) |
| 70 | + } else { |
| 71 | + replace('/error') |
| 72 | + next() |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +function serverAuth(authToken) { |
| 77 | + return new Promise((resolve, reject) => { |
| 78 | + // That server is gonna take a while |
| 79 | + setTimeout(() => { |
| 80 | + if(authToken === 'pancakes') { |
| 81 | + resolve('authenticated') |
| 82 | + } else { |
| 83 | + reject('nope') |
| 84 | + } |
| 85 | + }, 200) |
| 86 | + }) |
| 87 | +} |
| 88 | + |
| 89 | +render(( |
| 90 | + <Router history={browserHistory}> |
| 91 | + <Route path="/" component={App}> |
| 92 | + <IndexRoute component={Form} /> |
| 93 | + <Route path="page" component={Page} onEnter={requireCredentials}/> |
| 94 | + <Route path="error" component={ErrorPage}/> |
| 95 | + </Route> |
| 96 | + </Router> |
| 97 | +), document.getElementById('example')) |
0 commit comments