feat(mobile): ios oauth & magic-link login (#8581)

Co-authored-by: EYHN <cneyhn@gmail.com>
This commit is contained in:
Cats Juice
2024-10-28 14:12:33 +08:00
committed by GitHub
parent d6ec4cc597
commit 06dda70319
59 changed files with 929 additions and 219 deletions

View File

@@ -6,6 +6,7 @@ export {
isNetworkError,
NetworkError,
} from './error';
export { WebSocketAuthProvider } from './provider/websocket-auth';
export { AccountChanged, AuthService } from './services/auth';
export { FetchService } from './services/fetch';
export { GraphQLService } from './services/graphql';
@@ -26,6 +27,7 @@ import {
WorkspaceScope,
} from '@toeverything/infra';
import { UrlService } from '../url';
import { CloudDocMeta } from './entities/cloud-doc-meta';
import { Invoices } from './entities/invoices';
import { ServerConfig } from './entities/server-config';
@@ -35,6 +37,8 @@ import { SubscriptionPrices } from './entities/subscription-prices';
import { UserCopilotQuota } from './entities/user-copilot-quota';
import { UserFeature } from './entities/user-feature';
import { UserQuota } from './entities/user-quota';
import { DefaultFetchProvider, FetchProvider } from './provider/fetch';
import { WebSocketAuthProvider } from './provider/websocket-auth';
import { AuthService } from './services/auth';
import { CloudDocMetaService } from './services/cloud-doc-meta';
import { FetchService } from './services/fetch';
@@ -57,17 +61,25 @@ import { UserQuotaStore } from './stores/user-quota';
export function configureCloudModule(framework: Framework) {
framework
.service(FetchService)
.service(FetchService, [FetchProvider])
.impl(FetchProvider, DefaultFetchProvider)
.service(GraphQLService, [FetchService])
.service(WebSocketService, [AuthService])
.service(
WebSocketService,
f =>
new WebSocketService(
f.get(AuthService),
f.getOptional(WebSocketAuthProvider)
)
)
.service(ServerConfigService)
.entity(ServerConfig, [ServerConfigStore])
.store(ServerConfigStore, [GraphQLService])
.service(AuthService, [FetchService, AuthStore])
.service(AuthService, [FetchService, AuthStore, UrlService])
.store(AuthStore, [FetchService, GraphQLService, GlobalState])
.entity(AuthSession, [AuthStore])
.service(SubscriptionService, [SubscriptionStore])
.store(SubscriptionStore, [GraphQLService, GlobalCache])
.store(SubscriptionStore, [GraphQLService, GlobalCache, UrlService])
.entity(Subscription, [AuthService, ServerConfigService, SubscriptionStore])
.entity(SubscriptionPrices, [ServerConfigService, SubscriptionStore])
.service(UserQuotaService)

View File

@@ -0,0 +1,16 @@
import { createIdentifier } from '@toeverything/infra';
import type { FetchInit } from '../services/fetch';
export interface FetchProvider {
/**
* standard fetch, in ios&android, we can use native fetch to implement this
*/
fetch: (input: string | URL, init?: FetchInit) => Promise<Response>;
}
export const FetchProvider = createIdentifier<FetchProvider>('FetchProvider');
export const DefaultFetchProvider = {
fetch: globalThis.fetch.bind(globalThis),
};

View File

@@ -0,0 +1,22 @@
import { createIdentifier } from '@toeverything/infra';
export interface WebSocketAuthProvider {
/**
* Returns the token and userId for WebSocket authentication
*
* Useful when cookies are not available for WebSocket connections
*
* @param url - The URL of the WebSocket endpoint
*/
getAuthToken: (url: string) => Promise<
| {
token?: string;
userId?: string;
}
| undefined
>;
}
export const WebSocketAuthProvider = createIdentifier<WebSocketAuthProvider>(
'WebSocketAuthProvider'
);

View File

@@ -1,6 +1,6 @@
import { notify } from '@affine/component';
import { AIProvider } from '@affine/core/blocksuite/presets/ai';
import { apis, appInfo, events } from '@affine/electron-api';
import { apis, events } from '@affine/electron-api';
import type { OAuthProviderType } from '@affine/graphql';
import { I18n } from '@affine/i18n';
import { track } from '@affine/track';
@@ -13,6 +13,7 @@ import {
} from '@toeverything/infra';
import { distinctUntilChanged, map, skip } from 'rxjs';
import type { UrlService } from '../../url';
import { type AuthAccountInfo, AuthSession } from '../entities/session';
import type { AuthStore } from '../stores/auth';
import type { FetchService } from './fetch';
@@ -44,7 +45,8 @@ export class AuthService extends Service {
constructor(
private readonly fetchService: FetchService,
private readonly store: AuthStore
private readonly store: AuthStore,
private readonly urlService: UrlService
) {
super();
@@ -117,14 +119,14 @@ export class AuthService extends Service {
) {
track.$.$.auth.signIn({ method: 'magic-link' });
try {
const scheme = this.urlService.getClientSchema();
const magicLinkUrlParams = new URLSearchParams();
if (redirectUrl) {
magicLinkUrlParams.set('redirect_uri', redirectUrl);
}
magicLinkUrlParams.set(
'client',
BUILD_CONFIG.isElectron && appInfo ? appInfo.schema : 'web'
);
if (scheme) {
magicLinkUrlParams.set('client', scheme);
}
await this.fetchService.fetch('/api/auth/sign-in', {
method: 'POST',
body: JSON.stringify({

View File

@@ -3,6 +3,7 @@ import { UserFriendlyError } from '@affine/graphql';
import { fromPromise, Service } from '@toeverything/infra';
import { BackendError, NetworkError } from '../error';
import type { FetchProvider } from '../provider/fetch';
export function getAffineCloudBaseUrl(): string {
if (BUILD_CONFIG.isElectron || BUILD_CONFIG.isIOS || BUILD_CONFIG.isAndroid) {
@@ -17,6 +18,9 @@ const logger = new DebugLogger('affine:fetch');
export type FetchInit = RequestInit & { timeout?: number };
export class FetchService extends Service {
constructor(private readonly fetchProvider: FetchProvider) {
super();
}
rxFetch = (
input: string,
init?: RequestInit & {
@@ -50,13 +54,15 @@ export class FetchService extends Service {
abortController.abort('timeout');
}, timeout);
const res = await fetch(new URL(input, getAffineCloudBaseUrl()), {
...init,
signal: abortController.signal,
}).catch(err => {
logger.debug('network error', err);
throw new NetworkError(err);
});
const res = await this.fetchProvider
.fetch(new URL(input, getAffineCloudBaseUrl()), {
...init,
signal: abortController.signal,
})
.catch(err => {
logger.debug('network error', err);
throw new NetworkError(err);
});
clearTimeout(timeoutId);
if (res.status === 504) {
const error = new Error('Gateway Timeout');

View File

@@ -1,6 +1,7 @@
import { ApplicationStarted, OnEvent, Service } from '@toeverything/infra';
import { Manager } from 'socket.io-client';
import type { WebSocketAuthProvider } from '../provider/websocket-auth';
import { getAffineCloudBaseUrl } from '../services/fetch';
import type { AuthService } from './auth';
import { AccountChanged } from './auth';
@@ -13,10 +14,26 @@ export class WebSocketService extends Service {
transports: ['websocket'],
secure: location.protocol === 'https:',
});
socket = this.ioManager.socket('/');
socket = this.ioManager.socket('/', {
auth: this.webSocketAuthProvider
? cb => {
this.webSocketAuthProvider
?.getAuthToken(`${getAffineCloudBaseUrl()}/`)
.then(v => {
cb(v ?? {});
})
.catch(e => {
console.error('Failed to get auth token for websocket', e);
});
}
: undefined,
});
refCount = 0;
constructor(private readonly authService: AuthService) {
constructor(
private readonly authService: AuthService,
private readonly webSocketAuthProvider?: WebSocketAuthProvider
) {
super();
}

View File

@@ -1,4 +1,3 @@
import { appInfo } from '@affine/electron-api';
import type {
CreateCheckoutSessionInput,
SubscriptionRecurring,
@@ -15,6 +14,7 @@ import {
import type { GlobalCache } from '@toeverything/infra';
import { Store } from '@toeverything/infra';
import type { UrlService } from '../../url';
import type { SubscriptionType } from '../entities/subscription';
import { getAffineCloudBaseUrl } from '../services/fetch';
import type { GraphQLService } from '../services/graphql';
@@ -22,14 +22,15 @@ import type { GraphQLService } from '../services/graphql';
const SUBSCRIPTION_CACHE_KEY = 'subscription:';
const getDefaultSubscriptionSuccessCallbackLink = (
plan: SubscriptionPlan | null
plan: SubscriptionPlan | null,
schema?: string
) => {
const path =
plan === SubscriptionPlan.AI ? '/ai-upgrade-success' : '/upgrade-success';
const urlString = getAffineCloudBaseUrl() + path;
const url = new URL(urlString);
if (BUILD_CONFIG.isElectron && appInfo) {
url.searchParams.set('schema', appInfo.schema);
if (schema) {
url.searchParams.set('schema', schema);
}
return url.toString();
};
@@ -37,7 +38,8 @@ const getDefaultSubscriptionSuccessCallbackLink = (
export class SubscriptionStore extends Store {
constructor(
private readonly gqlService: GraphQLService,
private readonly globalCache: GlobalCache
private readonly globalCache: GlobalCache,
private readonly urlService: UrlService
) {
super();
}
@@ -129,7 +131,10 @@ export class SubscriptionStore extends Store {
...input,
successCallbackLink:
input.successCallbackLink ||
getDefaultSubscriptionSuccessCallbackLink(input.plan),
getDefaultSubscriptionSuccessCallbackLink(
input.plan,
this.urlService.getClientSchema()
),
},
},
});