Add "ui login" support
This commit is contained in:
@@ -212,6 +212,10 @@ import {
|
||||
GetExtensionQuery,
|
||||
GetExtensionQueryVariables,
|
||||
DownloaderState,
|
||||
UserLoginMutation,
|
||||
UserLoginMutationVariables,
|
||||
UserRefreshMutation,
|
||||
UserRefreshMutationVariables,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GET_GLOBAL_METADATAS } from '@/lib/graphql/queries/GlobalMetadataQuery.ts';
|
||||
import { DELETE_GLOBAL_METADATA, SET_GLOBAL_METADATA } from '@/lib/graphql/mutations/GlobalMetadataMutation.ts';
|
||||
@@ -327,6 +331,8 @@ import { CHAPTER_META_FIELDS } from '@/lib/graphql/fragments/ChapterFragments.ts
|
||||
import { MetadataMigrationSettings } from '@/features/migration/Migration.types.ts';
|
||||
import { MangaIdInfo } from '@/features/manga/Manga.types.ts';
|
||||
import { updateMetadataList } from '@/features/metadata/services/MetadataApolloCacheHandler.ts';
|
||||
import { USER_LOGIN, USER_REFRESH } from '@/lib/graphql/mutations/UserMutation.ts';
|
||||
import { AuthManager } from '@/features/authentication/AuthManager.ts';
|
||||
|
||||
enum GQLMethod {
|
||||
QUERY = 'QUERY',
|
||||
@@ -434,9 +440,9 @@ export const SPECIAL_ED_SOURCES = {
|
||||
export class RequestManager {
|
||||
public static readonly API_VERSION = '/api/v1/';
|
||||
|
||||
public readonly graphQLClient = new GraphQLClient();
|
||||
public readonly graphQLClient = new GraphQLClient(this.refreshUser.bind(this));
|
||||
|
||||
private readonly restClient: RestClient = new RestClient();
|
||||
private readonly restClient: RestClient = new RestClient(this.refreshUser.bind(this));
|
||||
|
||||
private readonly cache = new CustomCache();
|
||||
|
||||
@@ -452,6 +458,8 @@ export class RequestManager {
|
||||
}
|
||||
|
||||
public reset(): void {
|
||||
AuthManager.setAuthRequired(null);
|
||||
AuthManager.removeTokens();
|
||||
this.graphQLClient.client.resetStore();
|
||||
this.graphQLClient.terminateSubscriptions();
|
||||
this.cache.clear();
|
||||
@@ -1020,7 +1028,7 @@ export class RequestManager {
|
||||
} = {},
|
||||
): ImageRequest {
|
||||
const finalOptions = {
|
||||
useFetchApi: false,
|
||||
useFetchApi: AuthManager.isAuthRequired(),
|
||||
shouldDecode: false,
|
||||
disableCors: false,
|
||||
...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined)),
|
||||
@@ -3231,6 +3239,24 @@ export class RequestManager {
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
public useLoginUser(
|
||||
options?: MutationHookOptions<UserLoginMutation, UserLoginMutationVariables>,
|
||||
): AbortableApolloUseMutationResponse<UserLoginMutation, UserLoginMutationVariables> {
|
||||
return this.doRequest(GQLMethod.USE_MUTATION, USER_LOGIN, undefined, options);
|
||||
}
|
||||
|
||||
public refreshUser(
|
||||
refreshToken: string,
|
||||
options?: MutationOptions<UserRefreshMutation, UserRefreshMutationVariables>,
|
||||
): AbortableApolloMutationResponse<UserRefreshMutation> {
|
||||
return this.doRequest<UserRefreshMutation, UserRefreshMutationVariables>(
|
||||
GQLMethod.MUTATION,
|
||||
USER_REFRESH,
|
||||
{ refreshToken: refreshToken ?? undefined },
|
||||
options,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const requestManager = new RequestManager();
|
||||
|
||||
@@ -7,12 +7,60 @@
|
||||
*/
|
||||
|
||||
import { AppStorage } from '@/lib/storage/AppStorage.ts';
|
||||
import { UserRefreshMutation } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { AuthManager } from '@/features/authentication/AuthManager.ts';
|
||||
import { AbortableApolloMutationResponse } from '@/lib/requests/RequestManager.ts';
|
||||
|
||||
export abstract class BaseClient<Client, ClientConfig, Fetcher> {
|
||||
protected abstract client: Client;
|
||||
|
||||
public abstract readonly fetcher: Fetcher;
|
||||
|
||||
private static activeTokenRefreshPromise: Promise<UserRefreshMutation | null | undefined> | null = null;
|
||||
|
||||
protected static async refreshAccessToken(
|
||||
refreshFn: (refreshToken: string) => AbortableApolloMutationResponse<UserRefreshMutation>,
|
||||
): Promise<UserRefreshMutation | null | undefined> {
|
||||
const refreshToken = AuthManager.getRefreshToken();
|
||||
|
||||
if (!AuthManager.isAuthRequired()) {
|
||||
AuthManager.setAuthRequired(true);
|
||||
}
|
||||
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token found');
|
||||
}
|
||||
|
||||
if (this.activeTokenRefreshPromise) {
|
||||
return this.activeTokenRefreshPromise;
|
||||
}
|
||||
|
||||
const refreshRequest = refreshFn(refreshToken).response;
|
||||
this.activeTokenRefreshPromise = refreshRequest.then((result) => result.data);
|
||||
|
||||
try {
|
||||
const result = await refreshRequest;
|
||||
const { data } = result;
|
||||
|
||||
if (!data) {
|
||||
throw new Error('No refreshed access token returned');
|
||||
}
|
||||
|
||||
AuthManager.setAccessToken(data.refreshToken.accessToken);
|
||||
|
||||
return data;
|
||||
} catch (e) {
|
||||
AuthManager.removeTokens();
|
||||
throw e;
|
||||
} finally {
|
||||
this.activeTokenRefreshPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
protected constructor(
|
||||
protected handleRefreshToken: (refreshToken: string) => AbortableApolloMutationResponse<UserRefreshMutation>,
|
||||
) {}
|
||||
|
||||
public getBaseUrl(): string {
|
||||
const { hostname, port, protocol } = window.location;
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { onError } from '@apollo/client/link/error';
|
||||
import { setContext } from '@apollo/client/link/context';
|
||||
import {
|
||||
ApolloClient,
|
||||
ApolloClientOptions,
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
NormalizedCacheObject,
|
||||
split,
|
||||
from,
|
||||
fromPromise,
|
||||
} from '@apollo/client';
|
||||
import createUploadLink from 'apollo-upload-client/createUploadLink.mjs';
|
||||
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
|
||||
@@ -23,6 +26,9 @@ import { TypePolicies } from '@apollo/client/cache';
|
||||
import { removeTypenameFromVariables } from '@apollo/client/link/remove-typename';
|
||||
import { BaseClient } from '@/lib/requests/client/BaseClient.ts';
|
||||
import { StrictTypedTypePolicies } from '@/lib/graphql/generated/apollo-helpers.ts';
|
||||
import { AuthManager } from '@/features/authentication/AuthManager.ts';
|
||||
import { UserRefreshMutation } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { AbortableApolloMutationResponse } from '@/lib/requests/RequestManager.ts';
|
||||
|
||||
/* eslint-disable no-underscore-dangle */
|
||||
const typePolicies: StrictTypedTypePolicies = {
|
||||
@@ -187,8 +193,8 @@ export class GraphQLClient extends BaseClient<
|
||||
|
||||
private wsClient!: Client;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
constructor(handleRefreshToken: (refreshToken: string) => AbortableApolloMutationResponse<UserRefreshMutation>) {
|
||||
super(handleRefreshToken);
|
||||
|
||||
this.createClient();
|
||||
}
|
||||
@@ -201,8 +207,44 @@ export class GraphQLClient extends BaseClient<
|
||||
this.wsClient.terminate();
|
||||
}
|
||||
|
||||
private createErrorLink() {
|
||||
return onError(({ graphQLErrors, operation, forward }) => {
|
||||
if (!graphQLErrors) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const isAuthError = graphQLErrors.some((graphQLError) =>
|
||||
graphQLError.message.includes('suwayomi.tachidesk.server.user.UnauthorizedException'),
|
||||
);
|
||||
if (!isAuthError) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return fromPromise(BaseClient.refreshAccessToken(this.handleRefreshToken))
|
||||
.filter(Boolean)
|
||||
.flatMap(() => forward(operation));
|
||||
});
|
||||
}
|
||||
|
||||
private createAuthLink() {
|
||||
return setContext((_, { headers }) => {
|
||||
const isAuthRequired = AuthManager.isAuthRequired();
|
||||
const accessToken = AuthManager.getAccessToken();
|
||||
|
||||
return {
|
||||
headers: {
|
||||
credentials: 'include',
|
||||
...headers,
|
||||
Authorization: isAuthRequired && accessToken ? `Bearer ${accessToken}` : '',
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private createUploadLink() {
|
||||
return createUploadLink({ uri: () => this.getBaseUrl(), credentials: 'include' });
|
||||
return createUploadLink({
|
||||
uri: () => this.getBaseUrl(),
|
||||
});
|
||||
}
|
||||
|
||||
private createWSLink() {
|
||||
@@ -218,8 +260,13 @@ export class GraphQLClient extends BaseClient<
|
||||
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
|
||||
},
|
||||
this.createWSLink(),
|
||||
// apollo-upload-client dependency is outdated (see 134e47763faae9e62db4d4e3a8387a74e32e5568) and thus types are not matching, but they are still correct
|
||||
from([removeTypenameLink, this.createUploadLink() as unknown as ApolloLink]),
|
||||
from([
|
||||
this.createErrorLink(),
|
||||
this.createAuthLink(),
|
||||
removeTypenameLink,
|
||||
// apollo-upload-client dependency is outdated (see 134e47763faae9e62db4d4e3a8387a74e32e5568) and thus types are not matching, but they are still correct
|
||||
this.createUploadLink() as unknown as ApolloLink,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -230,6 +277,14 @@ export class GraphQLClient extends BaseClient<
|
||||
url: () => this.getBaseUrl().replace(/http(|s)/g, 'ws'),
|
||||
keepAlive: heartbeatInterval,
|
||||
retryAttempts: 10,
|
||||
connectionParams: () => {
|
||||
const isAuthRequired = AuthManager.isAuthRequired();
|
||||
const accessToken = AuthManager.getAccessToken();
|
||||
|
||||
return {
|
||||
Authorization: isAuthRequired && accessToken ? accessToken : undefined,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
let lastHeartbeat: number = 0;
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
*/
|
||||
|
||||
import { BaseClient } from '@/lib/requests/client/BaseClient.ts';
|
||||
import { AuthManager } from '@/features/authentication/AuthManager.ts';
|
||||
import { UserRefreshMutation } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { AbortableApolloMutationResponse } from '@/lib/requests/RequestManager.ts';
|
||||
|
||||
export enum HttpMethod {
|
||||
GET = 'GET',
|
||||
@@ -48,17 +51,28 @@ export class RestClient
|
||||
} = {},
|
||||
): Promise<Response> => {
|
||||
const updatedUrl = url.startsWith('http') ? url : `${this.getBaseUrl()}${url}`;
|
||||
const accessToken = AuthManager.getAccessToken();
|
||||
|
||||
let result: Response;
|
||||
|
||||
switch (httpMethod) {
|
||||
case HttpMethod.GET:
|
||||
result = await this.client(updatedUrl, { ...this.config, ...config, method: httpMethod });
|
||||
result = await this.client(updatedUrl, {
|
||||
...this.config,
|
||||
...config,
|
||||
method: httpMethod,
|
||||
headers: {
|
||||
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
|
||||
...this.config.headers,
|
||||
...config?.headers,
|
||||
},
|
||||
});
|
||||
break;
|
||||
case HttpMethod.POST:
|
||||
case HttpMethod.PATCH:
|
||||
case HttpMethod.DELETE:
|
||||
result = await this.client(updatedUrl, {
|
||||
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
|
||||
...this.config,
|
||||
...config,
|
||||
method: httpMethod,
|
||||
@@ -69,6 +83,11 @@ export class RestClient
|
||||
throw new Error(`Unexpected HttpMethod "${httpMethod}"`);
|
||||
}
|
||||
|
||||
if (result.status === 401) {
|
||||
await BaseClient.refreshAccessToken(this.handleRefreshToken);
|
||||
return this.fetcher(url, { data, httpMethod, config, checkResponseIsJson });
|
||||
}
|
||||
|
||||
if (result.status !== 200) {
|
||||
throw new Error(`status ${result.status}: ${result.statusText}`);
|
||||
}
|
||||
@@ -80,8 +99,8 @@ export class RestClient
|
||||
return result;
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
constructor(handleRefreshToken: (refreshToken: string) => AbortableApolloMutationResponse<UserRefreshMutation>) {
|
||||
super(handleRefreshToken);
|
||||
|
||||
this.createClient();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user