Преглед изворни кода

provier-views,companion-client: handle 401 response for companion

Ifedapo Olarewaju пре 6 година
родитељ
комит
700b557c3b

+ 8 - 7
packages/@uppy/companion-client/src/Provider.js

@@ -28,6 +28,14 @@ module.exports = class Provider extends RequestClient {
     })
   }
 
+  onReceiveResponse (response) {
+    response = super.onReceiveResponse(response)
+    const authenticated = response.status !== 401
+    this.uppy.getPlugin(this.pluginId).setPluginState({ authenticated })
+    return response
+  }
+
+  // @todo(i.olarewaju) consider whether or not this method should be exposed
   setAuthToken (token) {
     return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token)
   }
@@ -36,13 +44,6 @@ module.exports = class Provider extends RequestClient {
     return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey)
   }
 
-  checkAuth () {
-    return this.get(`${this.id}/authorized`)
-      .then((payload) => {
-        return payload.authenticated
-      })
-  }
-
   authUrl () {
     return `${this.hostname}/${this.id}/connect`
   }

+ 30 - 17
packages/@uppy/companion-client/src/RequestClient.js

@@ -29,6 +29,16 @@ module.exports = class RequestClient {
     return Promise.resolve(Object.assign({}, this.defaultHeaders, this.opts.serverHeaders || {}))
   }
 
+  _getPostResponseFunc (skip) {
+    return (response) => {
+      if (!skip) {
+        return this.onReceiveResponse(response)
+      }
+
+      return response
+    }
+  }
+
   onReceiveResponse (response) {
     const state = this.uppy.getState()
     const companion = state.companion || {}
@@ -52,7 +62,18 @@ module.exports = class RequestClient {
     return `${this.hostname}/${url}`
   }
 
-  get (path) {
+  _json(res) {
+    if (res.status === 401) {
+      throw new Error('Auth required')
+    }
+
+    if (res.status < 200 || res.status > 300) {
+      throw new Error(`Failed request to ${res.url}. ${res.statusText}`)
+    }
+    return res.json()
+  }
+
+  get (path, skipPostResponse) {
     return new Promise((resolve, reject) => {
       this.headers().then((headers) => {
         fetch(this._getUrl(path), {
@@ -60,9 +81,8 @@ module.exports = class RequestClient {
           headers: headers,
           credentials: 'same-origin'
         })
-          // @todo validate response status before calling json
-          .then(this.onReceiveResponse)
-          .then((res) => res.json().then(resolve))
+          .then(this._getPostResponseFunc(skipPostResponse))
+          .then((res) => this._json(res).then(resolve))
           .catch((err) => {
             reject(new Error(`Could not get ${this._getUrl(path)}. ${err}`))
           })
@@ -70,7 +90,7 @@ module.exports = class RequestClient {
     })
   }
 
-  post (path, data) {
+  post (path, data, skipPostResponse) {
     return new Promise((resolve, reject) => {
       this.headers().then((headers) => {
         fetch(this._getUrl(path), {
@@ -79,14 +99,8 @@ module.exports = class RequestClient {
           credentials: 'same-origin',
           body: JSON.stringify(data)
         })
-          .then(this.onReceiveResponse)
-          .then((res) => {
-            if (res.status < 200 || res.status > 300) {
-              reject(new Error(`Could not post ${this._getUrl(path)}. ${res.statusText}`))
-              return
-            }
-            res.json().then(resolve)
-          })
+          .then(this._getPostResponseFunc(skipPostResponse))
+          .then((res) => this._json(res).then(resolve))
           .catch((err) => {
             reject(new Error(`Could not post ${this._getUrl(path)}. ${err}`))
           })
@@ -94,7 +108,7 @@ module.exports = class RequestClient {
     })
   }
 
-  delete (path, data) {
+  delete (path, data, skipPostResponse) {
     return new Promise((resolve, reject) => {
       this.headers().then((headers) => {
         fetch(`${this.hostname}/${path}`, {
@@ -103,9 +117,8 @@ module.exports = class RequestClient {
           credentials: 'same-origin',
           body: data ? JSON.stringify(data) : null
         })
-          .then(this.onReceiveResponse)
-          // @todo validate response status before calling json
-          .then((res) => res.json().then(resolve))
+          .then(this._getPostResponseFunc(skipPostResponse))
+          .then((res) => this._json(res).then(resolve))
           .catch((err) => {
             reject(new Error(`Could not delete ${this._getUrl(path)}. ${err}`))
           })

+ 3 - 6
packages/@uppy/dropbox/src/index.js

@@ -25,7 +25,7 @@ module.exports = class Dropbox extends Plugin {
       pluginId: this.id
     })
 
-    this.onAuth = this.onAuth.bind(this)
+    this.onFirstRender = this.onFirstRender.bind(this)
     this.render = this.render.bind(this)
   }
 
@@ -55,11 +55,8 @@ module.exports = class Dropbox extends Plugin {
     this.unmount()
   }
 
-  onAuth (authenticated) {
-    this.setPluginState({ authenticated })
-    if (authenticated) {
-      this.view.getFolder()
-    }
+  onFirstRender () {
+    return this.view.getFolder()
   }
 
   render (state) {

+ 3 - 6
packages/@uppy/google-drive/src/index.js

@@ -29,7 +29,7 @@ module.exports = class GoogleDrive extends Plugin {
       pluginId: this.id
     })
 
-    this.onAuth = this.onAuth.bind(this)
+    this.onFirstRender = this.onFirstRender.bind(this)
     this.render = this.render.bind(this)
   }
 
@@ -62,11 +62,8 @@ module.exports = class GoogleDrive extends Plugin {
     this.unmount()
   }
 
-  onAuth (authenticated) {
-    this.setPluginState({ authenticated })
-    if (authenticated) {
-      this.view.getFolder('root', '/')
-    }
+  onFirstRender () {
+    return this.view.getFolder('root', '/')
   }
 
   render (state) {

+ 3 - 6
packages/@uppy/instagram/src/index.js

@@ -26,7 +26,7 @@ module.exports = class Instagram extends Plugin {
       pluginId: this.id
     })
 
-    this.onAuth = this.onAuth.bind(this)
+    this.onFirstRender = this.onFirstRender.bind(this)
     this.render = this.render.bind(this)
   }
 
@@ -60,11 +60,8 @@ module.exports = class Instagram extends Plugin {
     this.unmount()
   }
 
-  onAuth (authenticated) {
-    this.setPluginState({ authenticated })
-    if (authenticated) {
-      this.view.getFolder('recent')
-    }
+  onFirstRender () {
+    this.view.getFolder('recent')
   }
 
   render (state) {

+ 0 - 8
packages/@uppy/provider-views/src/AuthView.js

@@ -1,4 +1,3 @@
-const LoaderView = require('./Loader')
 const { h, Component } = require('preact')
 
 class AuthBlock extends Component {
@@ -29,14 +28,7 @@ class AuthBlock extends Component {
 }
 
 class AuthView extends Component {
-  componentDidMount () {
-    this.props.checkAuth()
-  }
-
   render () {
-    if (this.props.checkAuthInProgress) {
-      return <LoaderView />
-    }
     return <AuthBlock {...this.props} />
   }
 }

+ 17 - 18
packages/@uppy/provider-views/src/index.js

@@ -56,7 +56,7 @@ module.exports = class ProviderView {
     this.getFolder = this.getFolder.bind(this)
     this.getNextFolder = this.getNextFolder.bind(this)
     this.logout = this.logout.bind(this)
-    this.checkAuth = this.checkAuth.bind(this)
+    this.preFirstRender = this.preFirstRender.bind(this)
     this.handleAuth = this.handleAuth.bind(this)
     this.handleDemoAuth = this.handleDemoAuth.bind(this)
     this.sortByTitle = this.sortByTitle.bind(this)
@@ -93,17 +93,13 @@ module.exports = class ProviderView {
     this.plugin.setPluginState({ folders, files })
   }
 
-  checkAuth () {
-    this.plugin.setPluginState({ checkAuthInProgress: true })
-    this.provider.checkAuth()
-      .then((authenticated) => {
-        this.plugin.setPluginState({ checkAuthInProgress: false })
-        this.plugin.onAuth(authenticated)
-      })
-      .catch((err) => {
-        this.plugin.setPluginState({ checkAuthInProgress: false })
-        this.handleError(err)
-      })
+  /**
+   * Called only the first time the provider view is rendered.
+   * Kind of like an init function.
+   */
+  preFirstRender () {
+    this.plugin.setPluginState({ didFirstRender: true })
+    this.plugin.onFirstRender()
   }
 
   /**
@@ -434,7 +430,7 @@ module.exports = class ProviderView {
       authWindow.close()
       window.removeEventListener('message', handleToken)
       this.provider.setAuthToken(e.data.token)
-      this._loaderWrapper(this.provider.checkAuth(), this.plugin.onAuth, this.handleError)
+      this.preFirstRender()
     }
     window.addEventListener('message', handleToken)
   }
@@ -517,9 +513,14 @@ module.exports = class ProviderView {
   }
 
   render (state) {
-    const { authenticated, checkAuthInProgress, loading } = this.plugin.getPluginState()
+    const { authenticated, didFirstRender } = this.plugin.getPluginState()
+    if (!didFirstRender) {
+      this.preFirstRender()
+    }
 
-    if (loading) {
+    // reload pluginState for "loading" attribute because it might
+    // have changed above.
+    if (this.plugin.getPluginState().loading) {
       return (
         <CloseWrapper onUnmount={this.clearSelection}>
           <LoaderView />
@@ -534,10 +535,8 @@ module.exports = class ProviderView {
             pluginName={this.plugin.title}
             pluginIcon={this.plugin.icon}
             demo={this.plugin.opts.demo}
-            checkAuth={this.checkAuth}
             handleAuth={this.handleAuth}
-            handleDemoAuth={this.handleDemoAuth}
-            checkAuthInProgress={checkAuthInProgress} />
+            handleDemoAuth={this.handleDemoAuth} />
         </CloseWrapper>
       )
     }