Permalink
Browse files

holy fakkk boys we got auth shit happening!

  • Loading branch information...
Elektro1776 committed Oct 12, 2017
1 parent 41ba3f7 commit 67dc54f5663a2e0b64bbdf3ce62203f378bfa15f
View
@@ -17,6 +17,7 @@ module.exports = {
},
plugins: ["react", "babel", "react", "jsx-a11y"],
rules: {
"no-underscore-dangle": ["off"],
"import/prefer-default-export": ["off"],
"import/first": ["off"],
"global-require": ["off"],
@@ -1,25 +1,29 @@
export const USER_TOKEN = 'USER_TOKEN';
export const USER_TOKEN_SUCCESS = 'USER_TOKEN_SUCCESS';
export const USER_TOKEN_FAILURE = 'USER_TOKEN_FAILURE';
export const USER_TOKEN_NOT_FOUND = 'USER_TOKEN_NOT_FOUND';
// const ROOT_URL = window.location.href.indexOf('localhost') > 0 ? 'http://localhost:3000/api' : '/api';
// const ROOT_URL = window.location.href.indexOf('localhost') > 0 ? 'http://localhost:3000/auth' : '/auth';
// console.log(' ROOT URL ????', ROOT_URL);
import axios from 'axios';
export const checkUserToken = (tokenFromStorage) => {
console.log('IS THIS FIRING ?', );
const request = axios({
method: 'get',
url: `${ROOT_URL}/me/from/token?token=${tokenFromStorage}`,
headers: {
Authorization: `Bearer ${tokenFromStorage}`,
},
});
return {
type: USER_TOKEN,
payload: request,
return (dispatch) => {
axios({
method: 'get',
url: `/auth/token`,
headers: {
Authorization: `Bearer ${tokenFromStorage}`,
},
})
.then((user) => {
console.info('IS THIS FIRING ?', user.data);
dispatch(tokenCheckSuccess(user.data))
})
.catch((err) => {
console.info(' WE HAVE AN ERROR HUSTON', err);
});
};
};
@@ -36,3 +40,9 @@ export const tokenCheckFailure = (error) => (
payload: error,
}
);
export const userTokenNotFound = () => {
return {
type: USER_TOKEN_NOT_FOUND,
}
};
@@ -8,14 +8,18 @@ export const signupUser = (userData) => (dispatch) => {
body: JSON.stringify(userData),
})
.then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response;
})
.then((result) => result.json())
.then((user) => {
console.info(' WHAT IS OUR USER ????', user.body);
console.info(' WHAT IS OUR USER ????', user);
if (user.token) {
localStorage.setItem('jwt_token', user.token);
}
dispatch(successUserSignIn(user));
})
.catch((err) => {
@@ -2,12 +2,19 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { checkUserToken } from '../actions/authenticateUserActions';
import { checkUserToken, userTokenNotFound } from '../actions/authenticateUserActions';
class AppContainer extends Component {
// constructor(props) {
// super(props);
// }
static propTypes = {
children: PropTypes.element.isRequired,
}
componentDidMount() {
this.props.loadUserFromToken();
console.log(' CAN I GET THE STORE HERE ?', this.props);
}
render() {
return (
<div>
@@ -20,10 +27,11 @@ class AppContainer extends Component {
export default connect(null, (dispatch) => (
{
loadUserFromToken: () => {
const token = localStorage.getItem('token');
console.log(' CHECKING FOR TOKEN!?');
const token = localStorage.getItem('jwt_token');
if (!token || token === '') {
console.info(' NO TOKEN FOUND!');
return null;
return dispatch(userTokenNotFound());
}
console.info('FOUND A TOKEN!', token);
dispatch(checkUserToken(token));
@@ -7,7 +7,7 @@ import Routes from '../routes/Routes';
const ConnectedContainer = ({ history }) => (
<ConnectedRouter history={history} >
<Route render={({ location }) => (<Routes location={location} />)} />
<Route render={({ location }) => (<Routes location={location} meowmix={'fuckthisshit'}/>)} />
</ConnectedRouter>
);
ConnectedContainer.propTypes = {
View
@@ -5,7 +5,7 @@ import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import reducer from './reducers';
export default function configureStore(history) {
export default function configureStore(history, initalState) {
const routeMiddleware = routerMiddleware(history);
const middleware = [thunk, routeMiddleware];
const enhancer = compose(
@@ -16,7 +16,7 @@ export default function configureStore(history) {
// maxAge: 30
// })
);
const initalState = window.__INITALSTATE__;
// const initalState = window.__INITALSTATE__;
console.log(' WHAT IS THE INITAL STATE?', initalState);
const store = createStore(reducer, initalState, enhancer);
console.log(' WHAT I SOUR STORE STATE?', store.getState());
@@ -1,13 +1,22 @@
import { USER_TOKEN, USER_TOKEN_SUCCESS, USER_TOKEN_FAILURE } from '../actions/authenticateUserActions';
import { USER_TOKEN, USER_TOKEN_SUCCESS, USER_TOKEN_FAILURE, USER_TOKEN_NOT_FOUND } from '../actions/authenticateUserActions';
const initalState = {
isAuthenticated: false,
username: '',
loadingUser: false,
};
export default function (state = initalState, action) {
switch (action.type) {
case USER_TOKEN:
return Object.assign({}, state, {})
return Object.assign({}, state, { loadingUser: true });
case USER_TOKEN_SUCCESS: {
// console.log(' WE HAVE A USER TOKEN!!!!', action.payload.username);
return Object.assign({}, state, { isAuthenticated: true, username: action.payload.username, loadingUser: false });
}
case USER_TOKEN_NOT_FOUND: {
console.log(' USER TOKEN NOT FOUND');
return Object.assign({}, state, { isAuthenticated: false, loadingUser: false });
}
default:
return state;
}
View
@@ -11,11 +11,14 @@ import configureStore from '../createstore';
const history = createHistory();
const initalState = window.__INITALSTATE__;
// console.log(' THIS IS OUR CLIENT SIDE REHYDRATE STATE?', window.__INITALSTATE__);
// garbage collect the initalState
// then just go ahead and remove the script tag for shigrins.... :)
delete window.__INITALSTATE__;
document.getElementById('initalState').remove();
// delete window.__INITALSTATE__;
// document.getElementById('initalState').remove();
const store = configureStore(history, initalState);
const meow = store.getState();
// console.log(' WHAT IS THIS STORE STATE???? MEOWWWWWW', meow)
const root = document.getElementById('root');
const renderApp = (Component) =>
render(
@@ -27,6 +30,7 @@ const renderApp = (Component) =>
root,
);
renderApp(App);
if (module.hot) {
module.hot.accept('../containers/ConnectedContainer', () => {
const NextApp = require('../containers/ConnectedContainer').default;
View
@@ -9,22 +9,61 @@ import Routes from '../routes/Routes';
import configureServerStore from '../createServerstore';
const routes = [
'/',
'/login',
'/signup',
'/dashboard',
'/projects',
'/settings',
'profile',
'/about',
{
path: '/',
exact: true,
strict: false,
},
{
path: '/login',
exact: true,
strict: false,
},
{
path: '/signup',
exact: true,
strict: false,
},
{
path: '/dashboard',
exact: true,
strict: false,
},
{
path: '/projects',
exact: true,
strict: false,
},
{
path: '/settings',
exact: true,
strict: false,
},
{
path: '/profile',
exact: true,
strict: false,
},
{
path: '/about',
exact: true,
strict: false,
},
];
function renderApp(url, store) {
let counter = 0;
function renderApp(url, req) {
// console.info("We should be rendering the app???", url, window.location)
const context = {};
const history = createHistory();
const initalServerState = {};
const ssr = () => {
const match = routes.reduce((acc, route) => matchPath(url, route, { exact: true }) || acc, null);
if (!match) {
return;
const store = configureServerStore(history, initalServerState);
if (req.user) {
store.dispatch({
type: 'USER_TOKEN_SUCCESS',
payload: req.user,
});
}
const initalContent = renderToString(
<Provider store={store}>
@@ -42,20 +81,19 @@ function renderApp(url, store) {
return ssr();
}
export const renderPage = function serveIt(req, res) {
const history = createHistory();
const initalServerState = {};
if (!req.user) {
initalServerState.auth = { isAuthenticated: false, username: '' };
} else {
initalServerState.auth = { isAuthenticated: true, username: req.user };
}
const store = configureServerStore(history, initalServerState);
const match = routes.reduce((acc, route) => {
const realMatch = matchPath(req.url, route);
return realMatch || acc;
}, { path: '/', exact: true });
// console.log(' DO WE MAKE IT PAST OUR MATCH CHECK', match);
// console.log(' WHAT IS OUR REQ URL??', req.url);
// const assets = require('../../build/assets.json');
// assets.manifest.text = fs.readFileSync(
// join(__dirname, '..', '..', 'build', basename(assets.manifest.js)),
// 'utf-8'
// );
return renderApp(req.url, store);
if (match !== null) {
return renderApp(match, req);
}
};
export default renderPage;
View
@@ -1,39 +1,67 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router-dom';
import { Route, Redirect } from 'react-router-dom';
import * as RouteMap from './static';
import AppContainer from '../containers/AppContainer';
import { connect } from 'react-redux';
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) => (
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location },
}}
/>
)
)}
/>
);
const PrivateRoute = ({ component: Component, ...rest }) => {
console.log(' WHAT IS THE RESTTTTT', rest);
return(
<Route
{...rest}
render={(props) => (
rest.authorized ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/',
state: { from: props.location },
}}
/>
)
)}
/>
);
};
class Routes extends Component {
constructor(props) {
super(props);
this.state = {
userIsAuthorized: false,
userNotFound: true,
loadingUser: true,
};
}
componentWillReceiveProps(nextProps) {
const { isAuthenticated, loadingUser } = nextProps.auth;
if (isAuthenticated !== this.props.auth.isAuthenticated) {
this.setState({ userIsAuthorized: nextProps.auth.isAuthenticated, userNotFound: false });
} else if (!nextProps.auth.isAuthenticated && !loadingUser) {
this.setState({ userNotFound: true, loadingUser: false })
}
}
render() {
const { location } = this.props;
const { userIsAuthorized, userNotFound, loadingUser } = this.state;
if (userNotFound && loadingUser) {
return (
<AppContainer>
<div>Loading Blast Canon.....</div>
</AppContainer>
);
}
return (
<AppContainer>
<div>
<Route exact location={location} path="/" component={RouteMap.Dashboard} />
<Route exact location={location} path="/about" component={RouteMap.About} />
<Route exact location={location} path="/signup" component={RouteMap.Signup} />
<Route exact location={location} path="/" component={RouteMap.Signup} />
{/* <Route exact location={location} path="/login" component={RouteMap.Login} /> */}
<PrivateRoute exact path="/dashboard" component={RouteMap.Dashboard} authorized={userIsAuthorized} />
{/* <PrivateRoute path="/projects" component={RouteMap.Projects} authorized={userIsAuthorized} /> */}
{/* <PrivateRoute path="/settings" component={RouteMap.Settings} authorized={userIsAuthorized} /> */}
<PrivateRoute exact path="/about" component={RouteMap.About} authorized={userIsAuthorized} />
{/* <Route exact location={location} path="/about" component={RouteMap.About} /> */}
</div>
</AppContainer>
@@ -45,4 +73,7 @@ class Routes extends Component {
Routes.propTypes = {
location: PropTypes.object.isRequired,
};
export default Routes;
export default connect(
(state) => ({
auth: state.auth,
}), null)(Routes);
Oops, something went wrong.

0 comments on commit 67dc54f

Please sign in to comment.