2023-01-23 08:30:04 +00:00
|
|
|
import { UserFragment } from "@dashboard/graphql";
|
|
|
|
import { UserDetailsFragment } from "@saleor/sdk/dist/apollo/types";
|
2019-09-06 15:30:33 +00:00
|
|
|
|
2023-01-23 08:30:04 +00:00
|
|
|
export const isSupported = !!window.PasswordCredential;
|
2019-09-06 15:30:33 +00:00
|
|
|
|
2020-11-23 09:39:24 +00:00
|
|
|
export async function login<T>(
|
2022-06-21 09:36:55 +00:00
|
|
|
loginFn: (id: string, password: string) => Promise<T>,
|
2020-11-23 09:39:24 +00:00
|
|
|
): Promise<T | null> {
|
2023-01-23 08:30:04 +00:00
|
|
|
let result: T | null;
|
2020-11-23 09:39:24 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
const credential = await navigator.credentials.get({ password: true });
|
|
|
|
if (credential instanceof PasswordCredential) {
|
2023-01-23 08:30:04 +00:00
|
|
|
result = await loginFn(credential.id, credential.password ?? "");
|
2020-11-23 09:39:24 +00:00
|
|
|
}
|
|
|
|
} catch {
|
|
|
|
result = null;
|
2019-09-11 14:04:41 +00:00
|
|
|
}
|
2020-07-21 13:55:50 +00:00
|
|
|
|
2023-01-23 08:30:04 +00:00
|
|
|
return result!;
|
2019-09-06 15:30:33 +00:00
|
|
|
}
|
|
|
|
|
2023-07-28 07:33:22 +00:00
|
|
|
export async function checkIfCredentialsExist() {
|
|
|
|
const credential = await navigator.credentials.get({ password: true });
|
|
|
|
|
|
|
|
if (credential === null) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2020-11-23 09:39:24 +00:00
|
|
|
export function saveCredentials(
|
2023-01-23 08:30:04 +00:00
|
|
|
user: UserFragment | UserDetailsFragment,
|
2022-06-21 09:36:55 +00:00
|
|
|
password: string,
|
2023-01-23 08:30:04 +00:00
|
|
|
): Promise<CredentialType> | null {
|
|
|
|
let result: Promise<CredentialType> | null;
|
2020-11-23 09:39:24 +00:00
|
|
|
|
2019-09-11 14:04:41 +00:00
|
|
|
if (isSupported) {
|
|
|
|
const cred = new PasswordCredential({
|
|
|
|
id: user.email,
|
|
|
|
name: user.firstName ? `${user.firstName} ${user.lastName}` : undefined,
|
2022-06-21 09:36:55 +00:00
|
|
|
password,
|
2019-09-11 14:04:41 +00:00
|
|
|
});
|
2020-11-23 09:39:24 +00:00
|
|
|
try {
|
|
|
|
result = navigator.credentials.store(cred);
|
|
|
|
} catch {
|
|
|
|
result = null;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
result = null;
|
2019-09-11 14:04:41 +00:00
|
|
|
}
|
2020-11-23 09:39:24 +00:00
|
|
|
|
|
|
|
return result;
|
2019-09-06 15:30:33 +00:00
|
|
|
}
|