53 lines
1.6 KiB
JavaScript
53 lines
1.6 KiB
JavaScript
import Service, { service } from '@ember/service';
|
|
import { providerFor } from '../auth/providers';
|
|
import { selectTransport } from '../auth/transport';
|
|
import { getIdentityApi } from '../utils/extension';
|
|
|
|
// Orchestrates an integration authorization, delegating to a provider for the
|
|
// protocol specifics and to a transport for how the user's browser gets there.
|
|
export default class AuthorizationService extends Service {
|
|
@service storage;
|
|
|
|
async start(type, inputUrl, identity = getIdentityApi()) {
|
|
const provider = providerFor(type);
|
|
if (!provider) {
|
|
throw new Error(`Unsupported integration type: ${type}`);
|
|
}
|
|
|
|
const transport = selectTransport(identity);
|
|
const redirectUri =
|
|
transport.kind === 'extension'
|
|
? transport.redirectUri(provider.id)
|
|
: `${window.location.origin}${provider.webCallbackPath}`;
|
|
|
|
const requestUrl = await provider.prepare({
|
|
inputUrl,
|
|
redirectUri,
|
|
storage: this.storage,
|
|
});
|
|
|
|
if (transport.kind === 'extension') {
|
|
const resultUrl = await transport.launch(requestUrl);
|
|
if (!resultUrl) {
|
|
throw new Error('Authorization was cancelled');
|
|
}
|
|
const integration = await provider.complete({
|
|
resultUrl,
|
|
storage: this.storage,
|
|
});
|
|
return { transport: transport.kind, integration };
|
|
}
|
|
|
|
transport.redirect(requestUrl);
|
|
return { transport: transport.kind };
|
|
}
|
|
|
|
async completeWebCallback(type, resultUrl) {
|
|
const provider = providerFor(type);
|
|
if (!provider) {
|
|
throw new Error(`Unsupported integration type: ${type}`);
|
|
}
|
|
return provider.complete({ resultUrl, storage: this.storage });
|
|
}
|
|
}
|