From 638fc971b20624310114553a0876989c5556d06f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Delattre?= Date: Sun, 21 May 2017 16:12:50 +0200 Subject: [PATCH] Better redirections while logged in * If the user is already logged in and tries to go to /users/login, redirect him to the default page * Add check on the /users/edit page, it was not secure --- src/public/js/app.js | 50 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/src/public/js/app.js b/src/public/js/app.js index 3f441aa..366c3b8 100644 --- a/src/public/js/app.js +++ b/src/public/js/app.js @@ -81,8 +81,8 @@ export function startPollingTorrents() { ) } -var pollingTorrentsId; -const loginCheck = function(nextState, replace, next, f) { +// This function returns true if the user is logged in, false otherwise +function isLoggedIn() { const state = store.getState(); const isLogged = state.userStore.isLogged; let token = localStorage.getItem('token'); @@ -98,10 +98,23 @@ const loginCheck = function(nextState, replace, next, f) { }); } - if (!isLogged && (!token || token === "")) { + if (isLogged || (token && token !== "")) { + return true + } + + return false +} + +var pollingTorrentsId; +const loginCheck = function(nextState, replace, next, f = null) { + const loggedIn = isLoggedIn(); + if (!loggedIn) { replace('/users/login'); } else { - f(); + if (f) { + f(); + } + // Poll torrents once logged if (!pollingTorrentsId) { // Fetch the torrents every 10s @@ -114,15 +127,34 @@ const loginCheck = function(nextState, replace, next, f) { next(); } +const defaultRoute = '/movies/explore/yts/seeds'; const routes = { path: '/', component: App, - indexRoute: {onEnter: ({params}, replace) => replace('/movies/explore/yts/seeds')}, + indexRoute: {onEnter: ({params}, replace) => replace(defaultRoute)}, childRoutes: [ - { path: '/users/login' , component: UserLoginForm }, - { path: '/users/signup' , component: UserSignUp }, - { path: '/users/edit' , component: UserEdit }, - { path: '/users/signup' , component: UserSignUp }, + { + path: '/users/signup', + component: UserSignUp + }, + { + path: '/users/login', + component: UserLoginForm, + onEnter: function(nextState, replace, next) { + if (isLoggedIn()) { + // User is already logged in, redirect him to the default route + replace(defaultRoute); + } + next(); + }, + }, + { + path: '/users/edit', + component: UserEdit, + onEnter: function(nextState, replace, next) { + loginCheck(nextState, replace, next); + }, + }, { path: '/users/logout', onEnter: function(nextState, replace, next) {