showing results for - "react native cognito passwordless"
Lucia
02 Oct 2020
1export function sendAuthCode(email) {
2  const loginDetails = new AuthenticationDetails({ Username: email });
3  const preAuthCognitoUser = createCognitoUser(email);
4  preAuthCognitoUser.setAuthenticationFlowType("CUSTOM_AUTH");
5
6  return new Promise((resolve, reject) =>
7    preAuthCognitoUser.initiateAuth(loginDetails, {
8      onSuccess: resolve,
9      onFailure: reject,
10      customChallenge: async function() {
11        await savePreAuthSession({
12          email: preAuthCognitoUser.username,
13          session: preAuthCognitoUser.Session
14        }).catch(e =>
15          console.warn(
16            "Could not store session remotely. Access from an other browser tab won't be allowed",
17            e
18          )
19        );
20        resolve();
21      }
22    })
23  );
24}
25
26export async function checkAuthCode(code, email) {
27  const sessionData = await getPreAuthSession(email);
28  const preAuthCognitoUser = createCognitoUser(email, sessionData.session);
29  return new Promise((resolve, reject) =>
30    preAuthCognitoUser.sendCustomChallengeAnswer(code, {
31      onSuccess: resolve,
32      onFailure: reject,
33      customChallenge: async () => {
34        await savePreAuthSession({
35          email: preAuthCognitoUser.username,
36          session: preAuthCognitoUser.session
37        });
38        const error = new Error("Code not valid, try again");
39        error.code = "CodeValidationFail";
40        reject(error);
41      }
42    })
43  );
44}
45
46function createCognitoUser(email, session) {
47  const cognitoUser = new CognitoUser({ Username: email, Pool: userPool });
48  if (session) {
49    cognitoUser.Session = session;
50  }
51  return cognitoUser;
52}