2022-11-23 11:09:48 +00:00
|
|
|
import { ApolloError } from "@apollo/client";
|
2020-05-07 11:04:15 +00:00
|
|
|
import { findValueInEnum } from "@saleor/misc";
|
2020-05-14 09:30:32 +00:00
|
|
|
import { GraphQLError } from "graphql";
|
2020-05-07 11:04:15 +00:00
|
|
|
|
2022-11-23 11:09:48 +00:00
|
|
|
import { UserContextError } from "./types";
|
|
|
|
|
2020-05-07 11:04:15 +00:00
|
|
|
export enum JWTError {
|
2020-07-21 16:51:36 +00:00
|
|
|
invalid = "InvalidTokenError",
|
|
|
|
invalidSignature = "InvalidSignatureError",
|
2022-06-21 09:36:55 +00:00
|
|
|
expired = "ExpiredSignatureError",
|
2020-05-07 11:04:15 +00:00
|
|
|
}
|
|
|
|
|
2022-11-23 11:09:48 +00:00
|
|
|
export const AuthError = {
|
|
|
|
PermissionDenied: "PermissionDenied",
|
|
|
|
OAuthError: "OAuthError",
|
|
|
|
} as const;
|
|
|
|
|
|
|
|
export type AuthError = typeof AuthError[keyof typeof AuthError];
|
|
|
|
|
2020-05-07 11:04:15 +00:00
|
|
|
export function isJwtError(error: GraphQLError): boolean {
|
2020-08-18 15:20:06 +00:00
|
|
|
let jwtError: boolean;
|
|
|
|
try {
|
|
|
|
jwtError = !!findValueInEnum(error.extensions.exception.code, JWTError);
|
|
|
|
} catch (e) {
|
|
|
|
jwtError = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return jwtError;
|
2020-05-07 11:04:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function isTokenExpired(error: GraphQLError): boolean {
|
|
|
|
return error.extensions.exception.code === JWTError.expired;
|
|
|
|
}
|
2022-11-23 11:09:48 +00:00
|
|
|
|
|
|
|
export function getAuthErrorType(graphQLError: GraphQLError): UserContextError {
|
|
|
|
switch (graphQLError.extensions?.exception?.code as AuthError) {
|
|
|
|
case AuthError.PermissionDenied:
|
|
|
|
return UserContextError.noPermissionsError;
|
|
|
|
case AuthError.OAuthError:
|
|
|
|
return UserContextError.externalLoginError;
|
|
|
|
default:
|
|
|
|
return UserContextError.unknownLoginError;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function parseAuthError(authError: ApolloError): UserContextError[] {
|
|
|
|
return (
|
|
|
|
authError?.graphQLErrors?.map(graphQLError =>
|
|
|
|
getAuthErrorType(graphQLError),
|
|
|
|
) || []
|
|
|
|
);
|
|
|
|
}
|