2020-07-07 10:14:12 +00:00
|
|
|
import { User } from "@saleor/fragments/types/User";
|
2019-09-06 15:30:33 +00:00
|
|
|
|
2020-11-23 09:39:24 +00:00
|
|
|
export const isSupported = !!(
|
2020-11-30 10:26:51 +00:00
|
|
|
navigator?.credentials?.preventSilentAccess && window.PasswordCredential
|
2020-11-23 09:39:24 +00:00
|
|
|
);
|
2019-09-06 15:30:33 +00:00
|
|
|
|
2020-11-23 09:39:24 +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
|
|
|
|
2020-11-23 09:39:24 +00:00
|
|
|
return result;
|
2019-09-06 15:30:33 +00:00
|
|
|
}
|
|
|
|
|
2020-11-23 09:39:24 +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
|
|
|
|
});
|
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
|
|
|
}
|