Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@uppy/companion-client,@uppy/provider-views: make authentication optional #4556

Merged
merged 6 commits into from
Aug 6, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/@uppy/box/src/Box.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default class Box extends UIPlugin {
pluginId: this.id,
})

this.defaultLocale = locale
this.defaultLocale = [this.provider.defaultLocale, locale]

this.i18nInit()
this.title = this.i18n('pluginNameBox')
Expand Down
68 changes: 67 additions & 1 deletion packages/@uppy/companion-client/src/Provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,32 @@

import RequestClient from './RequestClient.js'
import * as tokenStorage from './tokenStorage.js'
import locale from './locale.js'

const getName = (id) => {
return id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
}

function getOrigin () {
// eslint-disable-next-line no-restricted-globals
return location.origin
}

function getRegex (value) {
if (typeof value === 'string') {
return new RegExp(`^${value}$`)
} if (value instanceof RegExp) {
return value
}
return undefined
}

function isOriginAllowed (origin, allowedOrigin) {
const patterns = Array.isArray(allowedOrigin) ? allowedOrigin.map(getRegex) : [getRegex(allowedOrigin)]
return patterns
.some((pattern) => pattern?.test(origin) || pattern?.test(`${origin}/`)) // allowing for trailing '/'
}

export default class Provider extends RequestClient {
#refreshingTokenPromise

Expand All @@ -19,6 +40,8 @@ export default class Provider extends RequestClient {
this.tokenKey = `companion-${this.pluginId}-auth-token`
this.companionKeysParams = this.opts.companionKeysParams
this.preAuthToken = null

this.defaultLocale = locale
}

async headers () {
Expand Down Expand Up @@ -72,14 +95,57 @@ export default class Provider extends RequestClient {
}

authUrl (queries = {}) {
const params = new URLSearchParams(queries)
const params = new URLSearchParams({
state: btoa(JSON.stringify({ origin: getOrigin() })),
...queries,
})
if (this.preAuthToken) {
params.set('uppyPreAuthToken', this.preAuthToken)
}

return `${this.hostname}/${this.id}/connect?${params}`
}

async login (queries) {
await this.ensurePreAuth()

return new Promise((resolve, reject) => {
const link = this.authUrl(queries)
const authWindow = window.open(link, '_blank')
const handleToken = (e) => {
if (e.source !== authWindow) {
reject(new Error('rejecting event from unknown source'))
}

const { companionAllowedHosts } = this.uppy.getPlugin(this.pluginId).opts
if (!isOriginAllowed(e.origin, companionAllowedHosts) || e.source !== authWindow) {
reject(new Error(`rejecting event from ${e.origin} vs allowed pattern ${companionAllowedHosts}`))
}

// Check if it's a string before doing the JSON.parse to maintain support
// for older Companion versions that used object references
const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data

if (data.error) {
const { i18n } = this.uppy.getPlugin(this.pluginId)
const message = i18n('authAborted')
this.uppy.info({ message }, 'warning', 5000)
reject(new Error('auth aborted'))
}

if (!data.token) {
reject(new Error('did not receive token from auth window'))
}

authWindow.close()
window.removeEventListener('message', handleToken)
this.setAuthToken(data.token)
resolve()
}
window.addEventListener('message', handleToken)
})
}

refreshTokenUrl () {
return `${this.hostname}/${this.id}/refresh-token`
}
Expand Down
5 changes: 5 additions & 0 deletions packages/@uppy/companion-client/src/locale.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
strings: {
authAborted: 'Authentication aborted',
},
}
6 changes: 5 additions & 1 deletion packages/@uppy/core/src/BasePlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ export default class BasePlugin {
}

i18nInit () {
const translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale])
const translator = new Translator([
...(Array.isArray(this.defaultLocale) ? this.defaultLocale : [this.defaultLocale]),
this.uppy.locale,
this.opts.locale,
])
this.i18n = translator.translate.bind(translator)
this.i18nArray = translator.translateArray.bind(translator)
this.setPluginState() // so that UI re-renders and we see the updated locale
Expand Down
5 changes: 4 additions & 1 deletion packages/@uppy/core/src/Uppy.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,10 @@ class Uppy {
}

i18nInit () {
const translator = new Translator([this.defaultLocale, this.opts.locale])
const translator = new Translator([
...(Array.isArray(this.defaultLocale) ? this.defaultLocale : [this.defaultLocale]),
this.opts.locale,
])
this.i18n = translator.translate.bind(translator)
this.i18nArray = translator.translateArray.bind(translator)
this.locale = translator.locale
Expand Down
1 change: 0 additions & 1 deletion packages/@uppy/core/src/locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export default {
noDuplicates:
"Cannot add the duplicate file '%{fileName}', it already exists",
companionError: 'Connection with Companion failed',
authAborted: 'Authentication aborted',
companionUnauthorizeHint:
'To unauthorize to your %{provider} account, please go to %{url}',
failedToUpload: 'Failed to upload %{file}',
Expand Down
2 changes: 1 addition & 1 deletion packages/@uppy/dropbox/src/Dropbox.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default class Dropbox extends UIPlugin {
pluginId: this.id,
})

this.defaultLocale = locale
this.defaultLocale = [this.provider.defaultLocale, locale]

this.i18nInit()
this.title = this.i18n('pluginNameDropbox')
Expand Down
2 changes: 1 addition & 1 deletion packages/@uppy/facebook/src/Facebook.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default class Facebook extends UIPlugin {
pluginId: this.id,
})

this.defaultLocale = locale
this.defaultLocale = [this.provider.defaultLocale, locale]

this.i18nInit()
this.title = this.i18n('pluginNameFacebook')
Expand Down
2 changes: 1 addition & 1 deletion packages/@uppy/google-drive/src/GoogleDrive.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default class GoogleDrive extends UIPlugin {
pluginId: this.id,
})

this.defaultLocale = locale
this.defaultLocale = [this.provider.defaultLocale, locale]

this.i18nInit()
this.title = this.i18n('pluginNameGoogleDrive')
Expand Down
10 changes: 5 additions & 5 deletions packages/@uppy/instagram/src/Instagram.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,6 @@ export default class Instagram extends UIPlugin {
</svg>
)

this.defaultLocale = locale

this.i18nInit()
this.title = this.i18n('pluginNameInstagram')

this.provider = new Provider(uppy, {
companionUrl: this.opts.companionUrl,
companionHeaders: this.opts.companionHeaders,
Expand All @@ -42,6 +37,11 @@ export default class Instagram extends UIPlugin {
pluginId: this.id,
})

this.defaultLocale = [this.provider.defaultLocale, locale]

this.i18nInit()
this.title = this.i18n('pluginNameInstagram')

this.onFirstRender = this.onFirstRender.bind(this)
this.render = this.render.bind(this)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@uppy/onedrive/src/OneDrive.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default class OneDrive extends UIPlugin {
pluginId: this.id,
})

this.defaultLocale = locale
this.defaultLocale = [this.provider.defaultLocale, locale]

this.i18nInit()
this.title = this.i18n('pluginNameOneDrive')
Expand Down
60 changes: 5 additions & 55 deletions packages/@uppy/provider-views/src/ProviderView/ProviderView.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,6 @@ import View from '../View.js'

import packageJson from '../../package.json'

function getOrigin () {
// eslint-disable-next-line no-restricted-globals
return location.origin
}

function getRegex (value) {
if (typeof value === 'string') {
return new RegExp(`^${value}$`)
} if (value instanceof RegExp) {
return value
}
return undefined
}
function isOriginAllowed (origin, allowedOrigin) {
const patterns = Array.isArray(allowedOrigin) ? allowedOrigin.map(getRegex) : [getRegex(allowedOrigin)]
return patterns
.some((pattern) => pattern?.test(origin) || pattern?.test(`${origin}/`)) // allowing for trailing '/'
}

function formatBreadcrumbs (breadcrumbs) {
return breadcrumbs.slice(1).map((directory) => directory.name).join('/')
}
Expand Down Expand Up @@ -254,45 +235,14 @@ export default class ProviderView extends View {
}

async handleAuth () {
await this.provider.ensurePreAuth()

const authState = btoa(JSON.stringify({ origin: getOrigin() }))
const clientVersion = `@uppy/provider-views=${ProviderView.VERSION}`
const link = this.provider.authUrl({ state: authState, uppyVersions: clientVersion })

const authWindow = window.open(link, '_blank')
const handleToken = (e) => {
if (e.source !== authWindow) {
this.plugin.uppy.log('rejecting event from unknown source')
return
}
if (!isOriginAllowed(e.origin, this.plugin.opts.companionAllowedHosts) || e.source !== authWindow) {
this.plugin.uppy.log(`rejecting event from ${e.origin} vs allowed pattern ${this.plugin.opts.companionAllowedHosts}`)
}
Murderlon marked this conversation as resolved.
Show resolved Hide resolved

// Check if it's a string before doing the JSON.parse to maintain support
// for older Companion versions that used object references
const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data

if (data.error) {
this.plugin.uppy.log('auth aborted', 'warning')
const { uppy } = this.plugin
const message = uppy.i18n('authAborted')
uppy.info({ message }, 'warning', 5000)
return
}

if (!data.token) {
this.plugin.uppy.log('did not receive token from auth window', 'error')
return
}

authWindow.close()
window.removeEventListener('message', handleToken)
this.provider.setAuthToken(data.token)
try {
await this.provider.login({ uppyVersions: clientVersion })
this.plugin.setPluginState({ authenticated: true })
this.preFirstRender()
} catch (e) {
this.plugin.uppy.log(`login failed: ${e.message}`)
}
window.addEventListener('message', handleToken)
}

async handleScroll (event) {
Expand Down
2 changes: 1 addition & 1 deletion packages/@uppy/zoom/src/Zoom.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default class Zoom extends UIPlugin {
pluginId: this.id,
})

this.defaultLocale = locale
this.defaultLocale = [this.provider.defaultLocale, locale]

this.i18nInit()
this.title = this.i18n('pluginNameZoom')
Expand Down