saleor-dashboard/src/utils/credentialsManagement.ts

48 lines
1.1 KiB
TypeScript
Raw Normal View History

import { User } from "@saleor/fragments/types/User";
2019-09-06 15:30:33 +00:00
export const isSupported = !!(
navigator?.credentials?.preventSilentAccess && PasswordCredential
);
2019-09-06 15:30:33 +00:00
export async function login<T>(
loginFn: (id: string, password: string) => T
): Promise<T | null> {
let result: T;
try {
const credential = await navigator.credentials.get({ password: true });
if (credential instanceof PasswordCredential) {
result = 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
}
export function saveCredentials(
user: User,
password: string
): Promise<CredentialType | null> {
let result: Promise<CredentialType | null>;
2019-09-11 14:04:41 +00:00
if (isSupported) {
const cred = new PasswordCredential({
iconURL: user.avatar ? user.avatar.url : undefined,
id: user.email,
name: user.firstName ? `${user.firstName} ${user.lastName}` : undefined,
password
});
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
}