Skip to content

Instantly share code, notes, and snippets.

@kriswallsmith
Last active August 29, 2015 14:16
Show Gist options
  • Save kriswallsmith/302fedad59ad0845ed79 to your computer and use it in GitHub Desktop.
Save kriswallsmith/302fedad59ad0845ed79 to your computer and use it in GitHub Desktop.
My first bit of React code worth sharing.
var React = require('react');
var Router = require('react-router');
var SessionStore = require('../stores/SessionStore');
var Stash = require('../utils/Stash');
function authentication(transition) {
if (!SessionStore.isLoggedIn()) {
Stash.set('onLogin', transition.retry);
transition.redirect('login');
return false;
}
return true;
}
function Secure(authorization) {
return {
mixins: [Router.Navigation],
propTypes: {
isLoggedIn: React.PropTypes.bool.isRequired
},
statics: {
willTransitionTo: function(transition, params, query, callback) {
if (!authentication(transition)) {
callback();
} else if (authorization) {
authorization(transition, params, query, callback);
if (authorization.length < 4) callback();
} else {
callback();
}
}
},
componentDidUpdate: function(prevProps, prevState) {
this.props.isLoggedIn || this.transitionTo('login');
}
};
}
module.exports = Secure;
var React = require('react');
var Router = require('react-router');
var Stash = require('../utils/Stash');
var LoginPage = React.createClass({
mixins: [Router.Navigation],
// ...
componentDidUpdate: function(prevProps, prevState) {
if (this.props.isLoggedIn && !prevProps.isLoggedIn) {
var onLogin = Stash.get('onLogin');
onLogin ? onLogin : this.transitionTo('home');
}
}
// ...
});
module.exports = LoginPage;
var React = require('react');
var Secure = require('../mixins/Secure');
var SecurePage = React.createClass({
mixins: [Secure()]
// ...
});
module.exports = SecurePage;
var React = require('react');
var Secure = require('../mixins/Secure');
function authorization(transition) {
// authorization logic...
}
var AuthorizationPage = React.createClass({
mixins: [Secure(authorization)]
// ...
});
module.exports = AuthorizationPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment