Skip to content

Instantly share code, notes, and snippets.

@RaphaelBlehoue
Last active February 17, 2018 14:44
Show Gist options
  • Save RaphaelBlehoue/f090bb972a61cded13241d2ede2afcd0 to your computer and use it in GitHub Desktop.
Save RaphaelBlehoue/f090bb972a61cded13241d2ede2afcd0 to your computer and use it in GitHub Desktop.
HOC authorization Failed
import {
SIGN_IN_USER_REQUEST,
SIGN_IN_USER_FAILURE,
SIGN_IN_USER_SUCCESS,
GET_USER_LOGGED,
LOGOUT_USER
} from '../Constants/index';
import api from '../config';
export function SignInUserRequest(formValues) {
return {
type: SIGN_IN_USER_REQUEST,
formValues
}
}
export function SignInUserSuccess(data) {
return {
type: SIGN_IN_USER_SUCCESS,
data
}
}
export function SignInUserFailure(errors) {
return {
type: SIGN_IN_USER_FAILURE,
errors
}
}
export function getUserLogged() {
return {
type: GET_USER_LOGGED
}
}
export function logoutUser() {
return {
type: LOGOUT_USER
}
}
// User Sign In Action Event dispatch async Action
export function SignInUser(credentials) {
return async (dispatch) => {
dispatch(SignInUserRequest(credentials));
try {
const res = await api.auth.login(credentials);
dispatch(SignInUserSuccess(res.data));
localStorage.setItem('tdtk', res.data.token);
} catch(error) {
dispatch(SignInUserFailure(error.response.data));
}
};
}
// Verifie if Current User is logged Or is false Logout
export function VerifyUserLogged() {
return async (dispatch) => {
try {
const res = await api.logged.getLogged();
console.log(res);
dispatch(getUserLogged());
dispatch(SignInUserSuccess(res));
} catch( error ) {
dispatch(logoutUser());
localStorage.clear();
}
}
}
export function SignUpUser (data) {
console.log(data);
}
import axios from 'axios';
const API_URL = process.env.NODE_ENV === 'production' ? 'http://productUrl.com/api' : 'http://test-api.test/api';
const token = localStorage.tdtk;
const options = {
headers: {
Authorization: token ? `Bearer ${token}` : '',
'Content-Type': 'application/json',
},
};
export default {
auth: {
login: credentials => axios.post(`${API_URL}/login_check`, credentials),
},
logged: {
getLogged: () =>
axios.get(`${API_URL}/user/logged`, options),
},
};
import React from 'react';
import PropTypes from 'prop-types';
import { ConnectedRouter } from "react-router-redux";
import { Route, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { history } from "./Stores/ConfigureStore";
import userFeedContainer from './Containers/feed/userFeedContainer';
import ProfileContainer from './Containers/Security/ProfileContainer';
import SignInFormContainer from './Containers/Security/SignInFormContainer';
import SignUpFormContainer from './Containers/Security/SignUpFormContainer';
import Home from './Containers/Home';
const SecureRoute = ({ isAuthenticated, component: Component, ...rest }) => (
<Route
{...rest}
render={(props) => isAuthenticated === true
? <Component {...props} />
: <Redirect to={{ pathname: '/accounts/signIn', state: {from: props.location}}} />}
/>
);
const PublicRoute = ({ isAuthenticated, component: Component, ...rest }) => (
<Route
{...rest}
render={(props) => isAuthenticated === false
? <Component {...props} />
: <Redirect to='/feed' />}
/>
);
const App = ({isAuthenticated}) => (
<ConnectedRouter history={history}>
<div>
<Route exact path="/" component={ Home }/>
<SecureRoute isAuthenticated={ isAuthenticated } path="/feed" exact component={userFeedContainer} />
<SecureRoute isAuthenticated={ isAuthenticated } path="/profile" exact component={ProfileContainer} />
<PublicRoute isAuthenticated={ isAuthenticated } path="/accounts/signIn" exact component={SignInFormContainer} />
<PublicRoute isAuthenticated={ isAuthenticated } path="/accounts/signUp" exact component={SignUpFormContainer} />
</div>
</ConnectedRouter>
);
App.propTypes = {
isAuthenticated: PropTypes.bool.isRequired
};
PublicRoute.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
component: PropTypes.func.isRequired,
};
SecureRoute.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
component: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => {
return { isAuthenticated: state.auth.isAuthenticated };
};
export default connect(mapStateToProps)(App);
import React, { Component } from 'react';
import { connect } from "react-redux";
import $ from 'jquery/dist/jquery.min';
import FrontLayout from '../../Layouts/FrontLayout';
import FeedBodyComponent from '../../Components/feed/FeedBodyComponent';
import SideBarComponent from '../../Components/Sidebars/SideBarComponent';
import SecondSideBarComponent from '../../Components/Sidebars/SecondSideBarComponent';
class userFeedContainer extends Component {
componentWillMount() {
const body = $('body');
body.removeClass('navbar-bottom sidebar-xs');
}
componentDidMount() {
const body = $('body');
body.addClass('navbar-bottom sidebar-xs');
}
render() {
return (
<FrontLayout>
<SideBarComponent />
<SecondSideBarComponent />
<FeedBodyComponent />
</FrontLayout>
);
}
}
export default connect(null)(userFeedContainer);
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { configureStore } from './Stores/ConfigureStore';
import App from "./App";
import registerServiceWorker from './registerServiceWorker';
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
import { combineReducers } from 'redux';
import { reducer as form} from 'redux-form';
import { routerReducer as router } from 'react-router-redux';
import auth from './auth';
const rootReducer = combineReducers({
auth,
form,
router
});
export default rootReducer;
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import $ from 'jquery/dist/jquery.min';
import '../../Ui/styles/login.css';
import logo from '../../Ui/images/logo_origin.png';
import SecurityLayout from '../../Layouts/SecurityLayout';
import renderField from '../../Components/renderField';
import { SignInUser } from '../../Actions/authActions';
class SignInFormContainer extends Component {
constructor(props) {
super(props);
this.handleFormSignInAndValidate = this.handleFormSignInAndValidate.bind(this);
}
componentWillMount() {
const body = $('body');
body.removeClass('login-container login-cover');
}
componentDidMount() {
const body = $('body');
body.addClass('login-container login-cover');
}
handleFormSignInAndValidate = values => {
this.props.SignInUser(values);
};
render() {
const { handleSubmit, submitting, errorMessage } = this.props;
return (
<SecurityLayout>
<form onSubmit={handleSubmit(this.handleFormSignInAndValidate)}>
<div className="panel panel-body login-form">
<div className="text-center">
<div>
<img src={logo} alt="Toudeal Authentification" />
</div>
<h5 className="content-group-lg display-block pt-10">Connectez-vous à votre compte</h5>
</div>
{errorMessage &&
!errorMessage.authenticated && (
<div className="alert alert-danger no-border">{errorMessage}</div>
)}
<Field
name="username"
label="Entrez adresse Email (obligatoire)"
placeholder="Entrez votre email..."
type="text"
component={renderField}
/>
<Field
name="password"
label="Mot de passe (obligatoire)"
type="password"
component={renderField}
placeholder="Mot de passe"
/>
<div className="form-group">
<div className="row">
<div className="col-sm-8 text-right col-xs-offset-4">
<a>Mot de passe oublié ?</a>
</div>
</div>
</div>
<div className="form-group">
<button type="submit" className="btn bg-blue btn-block btn-xlg" disabled={submitting}>
Se Connecter
</button>
</div>
<div className="content-divider text-muted form-group">
<span className="no-margin text-semibold">{`Vous n'avez pas de compte?`}</span>
</div>
<Link
to="/accounts/signUp"
className="btn text-orange-800 border-orange btn-flat btn-xlg btn-block content-group"
>
Créer un nouveau compte
</Link>
<span className="help-block text-center no-margin">
{`By continuing, youre confirming that you've read our`} <a>{`Terms & Conditions`}</a> and{' '}
<a>Cookie Policy</a>
</span>
</div>
</form>
</SecurityLayout>
);
}
}
// Client-side validation informations
const validate = data => {
const errors = {};
if(!data.username) errors.username = "Entrez votre email pour vous connecter";
if(!data.password) errors.password = "Le Mot de passe ne doit pas etre vide";
// if (isValidPhoneNumber(!data.username)) errors.username = 'This field must be a valid phone number';
return errors;
};
function mapStateToProps (state) {
return {
errorMessage: state.auth.error,
auth: state.auth
}
}
SignInFormContainer.propTypes = {
handleSubmit: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired,
SignInUser: PropTypes.func.isRequired
};
SignInFormContainer.defaultProps = {
auth: PropTypes.shape({
status: PropTypes.string.isRequired,
authenticated: PropTypes.bool.isRequired,
}),
errorMessage: PropTypes.string,
};
const reduxFormSignin = reduxForm({
form: 'SignInValidation',
validate,
})(SignInFormContainer);
export default connect(mapStateToProps, { SignInUser })(reduxFormSignin);
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import promise from "redux-promise-middleware";
// import logger from 'redux-logger';
import createHistory from 'history/createBrowserHistory';
import { routerMiddleware } from 'react-router-redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from '../Reducers';
import { VerifyUserLogged } from "../Actions/authActions";
export const history = createHistory();
const middleware = composeWithDevTools(applyMiddleware(promise(), routerMiddleware(history), thunk));
export function configureStore (initialState) {
const store = createStore(rootReducer, initialState, middleware);
const token = localStorage.tdkd;
if (token){ store.dispatch(VerifyUserLogged()); }
return store;
}
@RaphaelBlehoue
Copy link
Author

RaphaelBlehoue commented Feb 17, 2018

--- English ---
***** By link: I create a link in my code, to access a page
By URL: I know the URL of the page so I do not go through the link, I type my URL page directly in the browser bar to access

--- French ---
*****Par lien : je creer un lien dans mon code , pour avoir accès a une page
Par URL: je connais l'url de la page donc je passe pas par le lien, je tape mon URL de page directement dans la barre du navigateur pour y avoir accès

--- English ---

  1. My secure pages are not accessible initially
  2. When I log in I am redirected to the feed page and the token is saved in localstorage
  3. When I want to have access to the login page while already logged in (By link) I am redirected to the feed page
    4 (* Problem): When I want to have access to the login page already connected (By Url) I am redirected to the login page and my state comes back with an isAuthenticated = false (While I had to be redirected to feed, because I dispatcher the VerifyUserLogged () function in the blinds which is supposed to reconnect automatically (if I'm doing it right)
  4. The same problem (4) redirection to login occurs when I want to have access to another secure page as a profile being already connected (By Url) I am redirected to the login page and my State returns to the initial one with an isAuthenticated = false

--- French ----

  1. Mes pages sécurisées ne sont pas accessible initialement
  2. Quand je me connecte je suis bien redirigé vers la page feed et le token est enregistré en localstorage
  3. Quand je veux avoir accès à la page login en étant déjà connecté (Par lien) je suis bien redirigé vers la page feed
    4 (*Problème): Quand je veux avoir accès à la page login étant déjà connecté (Par Url) je suis redirigé vers la page login et mon state revient à l'initial avec un isAuthenticated = false (Alors que je devais être redirigé vers feed, parce que je dispach la func VerifyUserLogged() dans le stores qui est sensé me reconnecté automatiquement (si je fais bien)
  4. Le même problème (4) de redirection vers login se produits quand je veux avoir accès à une autre page sécurisée comme profil en étant déjà connecté (Par Url) je suis redirigé vers la page login et mon State revient à l'initial avec un isAuthenticated = false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment