saleor-dashboard/src/utils/credentialsManagement.ts

56 lines
1.3 KiB
TypeScript
Raw Normal View History

import { UserFragment } from "@dashboard/graphql";
import { UserDetailsFragment } from "@saleor/sdk/dist/apollo/types";
2019-09-06 15:30:33 +00:00
export const isSupported = !!window.PasswordCredential;
2019-09-06 15:30:33 +00:00
export async function login<T>(
loginFn: (id: string, password: string) => Promise<T>,
): Promise<T | null> {
let result: T | null;
try {
const credential = await navigator.credentials.get({ password: true });
if (credential instanceof PasswordCredential) {
result = await loginFn(credential.id, credential.password ?? "");
}
} catch {
result = null;
2019-09-11 14:04:41 +00:00
}
2020-07-21 13:55:50 +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;
}
export function saveCredentials(
user: UserFragment | UserDetailsFragment,
password: string,
): Promise<CredentialType> | null {
let result: Promise<CredentialType> | null;
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,
password,
2019-09-11 14:04:41 +00:00
});
try {
result = navigator.credentials.store(cred);
} catch {
result = null;
}
} else {
result = null;
2019-09-11 14:04:41 +00:00
}
return result;
2019-09-06 15:30:33 +00:00
}