Przeglądaj źródła

Restore previous URL path after session expiration

If a user is logged out due to session expiration, if he logs right back
in, he will be redirected to the page he was on just before he was
logged out.

The information of the previous page / state he was on, is stored in the
URL itself.
Sergiu Miclea 6 lat temu
rodzic
commit
a16459710b
2 zmienionych plików z 27 dodań i 11 usunięć
  1. 12 6
      src/components/pages/LoginPage/LoginPage.jsx
  2. 15 5
      src/utils/ApiCaller.js

+ 12 - 6
src/components/pages/LoginPage/LoginPage.jsx

@@ -107,22 +107,28 @@ class LoginPage extends React.Component<Props, State> {
     document.title = 'Log In'
   }
 
-  handleFormSubmit(data: {
+  async handleFormSubmit(data: {
     username: string,
     password: string,
   }) {
-    userStore.login({
+    await userStore.login({
       name: data.username,
       password: data.password,
       domain: this.state.domain,
     })
-  }
-
-  render() {
-    if (userStore.loggedIn) {
+    if (!userStore.loggedIn) {
+      return
+    }
+    let prevExp = /\?prev=(.*)/
+    let prevMatch = prevExp.exec(window.location.hash) || prevExp.exec(window.location.search)
+    if (prevMatch) {
+      this.props.history.push(prevMatch[1])
+    } else {
       this.props.history.push('/')
     }
+  }
 
+  render() {
     return (
       <EmptyTemplate>
         <Wrapper>

+ 15 - 5
src/utils/ApiCaller.js

@@ -51,10 +51,20 @@ const addCancelable = (cancelable: Cancelable) => {
 }
 
 const isOnLoginPage = (): boolean => {
-  if (window.env.ENV === 'development') {
-    return window.location.hash === '#/login'
+  return window.location.hash.indexOf('login') > -1 || window.location.pathname.indexOf('login') > -1
+}
+
+const redirect = (statusCode: number) => {
+  if (statusCode !== 401 || isOnLoginPage()) {
+    return
+  }
+  let currentPath = '?prev=/'
+  if (window.location.pathname !== '/') {
+    currentPath = `?prev=${window.location.pathname}${window.location.search}`
+  } else if (window.location.hash) {
+    currentPath = `?prev=${window.location.hash.replace('#', '')}`
   }
-  return window.location.pathname === '/login'
+  window.location.href = `/login${currentPath}`
 }
 
 class ApiCaller {
@@ -138,8 +148,8 @@ class ApiCaller {
             }
           }
 
-          if (error.response.status === 401 && !isOnLoginPage() && error.request.responseURL.indexOf('/proxy/') === -1) {
-            window.location.href = '/login'
+          if (error.request.responseURL.indexOf('/proxy/') === -1) {
+            redirect(error.response.status)
           }
 
           logger.log({