UNPKG

@jbrowse/plugin-authentication

Version:

JBrowse 2 Authentication

67 lines (66 loc) 2.7 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { ConfigurationReference } from '@jbrowse/core/configuration'; import { types } from 'mobx-state-tree'; import { configSchema as OAuthConfigSchema } from '../OAuthModel'; import { GoogleDriveFile } from './GoogleDriveFilehandle'; import GoogleDriveIcon from './GoogleDriveIcon'; import { getDescriptiveErrorMessage } from './util'; import baseModel from '../OAuthModel/model'; function getUri(str) { const urlId = /[-\w]{25,}/.exec(str); return `https://www.googleapis.com/drive/v3/files/${urlId}`; } export default function stateModelFactory(configSchema) { return baseModel(OAuthConfigSchema) .named('GoogleDriveOAuthInternetAccount') .props({ type: types.literal('GoogleDriveOAuthInternetAccount'), configuration: ConfigurationReference(configSchema), }) .views(() => ({ get toggleContents() { return _jsx(GoogleDriveIcon, {}); }, get selectorLabel() { return 'Enter Google Drive share link'; }, })) .actions(self => ({ getFetcher(location) { return async (input, init) => { const driveUrl = new URL(getUri(String(input))); const searchParams = new URLSearchParams(); if (init === null || init === void 0 ? void 0 : init.metadataOnly) { searchParams.append('fields', 'size'); } else { searchParams.append('alt', 'media'); } driveUrl.search = searchParams.toString(); const authToken = await self.getToken(location); const response = await fetch(driveUrl, self.addAuthHeaderToInit({ ...init, method: 'GET', credentials: 'same-origin' }, authToken)); if (!response.ok) { throw new Error(await getDescriptiveErrorMessage(response)); } return response; }; }, openLocation(location) { return new GoogleDriveFile(location.uri, { fetch: this.getFetcher(location), }); }, async validateToken(token, location) { const response = await fetch(getUri(location.uri), { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/x-www-form-urlencoded', }, }); if (!response.ok) { throw new Error(await getDescriptiveErrorMessage(response, 'Token could not be validated')); } return token; }, })); }