src/actions/member.js
/**
 * Login to Firebase with Email/Password
 */
Login to Firebase with Email/Password
Login to Firebase with Email / Password
function login(formData) {
  const { email, password, cellphone, userWithEmail, checked } = formData;
  return dispatch =>
    new Promise(async (resolve, reject) => {
      await statusMessage(dispatch, "loading", true);
      if (!email) return reject({ message: ErrorMessages.missingEmail });
      if (!password) return reject({ message: ErrorMessages.missingPassword });
      if (!cellphone)
        return reject({ message: ErrorMessages.missingCellphone });
      if (!userWithEmail) {
        if (!checked) return reject({ message: ErrorMessages.missingTandC });
        publicAPI.defaults.headers.common = {};
        return publicAPI
          .post("https://seller-server-dev.herokuapp.com/api/login", {
            username: cellphone,
            password: password
          })
          .then(response => {
            let user_data = response.data.user;
            console.log("el user_id");
            console.log(user_data.id);
            publicAPI.defaults.headers.common["Authorization"] = `Bearer ${
              response.data.access_token
            }`;
            return publicAPI
              .put(
                `https://seller-server-dev.herokuapp.com/api/users/${
                  user_data.id
                }`,
                { user: { email: email } }
              )
              .then(async uppdatedUserRes => {
                console.log("entra al update del email");
                console.log(uppdatedUserRes.data);
                publicAPI.defaults.headers.common = {};
                return Firebase.auth()
                  .createUserWithEmailAndPassword(email, password)
                  .then(res => {
                    console.log(res);
                    if (res && res.user.uid) {
                      FirebaseRef.child(`users/${res.user.uid}`)
                        .set({
                          firstName: user_data.first_name,
                          lastName: user_data.last_name,
                          phoneNumber: cellphone,
                          signedUp: Firebase.database.ServerValue.TIMESTAMP,
                          lastLoggedIn: Firebase.database.ServerValue.TIMESTAMP
                        })
                        .then(async () => {
                          return await Firebase.auth()
                            .setPersistence(
                              Firebase.auth.Auth.Persistence.LOCAL
                            )
                            .then(() =>
                              Firebase.auth()
                                .signInWithEmailAndPassword(email, password)
                                .then(async res => {
                                  const userDetails =
                                    res && res.user ? res.user : null;
                                  if (userDetails.uid) {
                                    FirebaseRef.child(
                                      `users/${userDetails.uid}`
                                    ).update({
                                      lastLoggedIn:
                                        Firebase.database.ServerValue.TIMESTAMP
                                    });
                                    if (userDetails.emailVerified === false) {
                                      Firebase.auth()
                                        .currentUser.sendEmailVerification()
                                        .catch(() =>
                                          console.log(
                                            "Verification email failed to send"
                                          )
                                        );
                                    }
                                    await setupAxios(
                                      dispatch,
                                      cellphone,
                                      password
                                    );
                                    AsyncStorage.getItem("token").then(res => {
                                      console.log("here's the token");
                                      console.log(res);
                                    });
                                  }
                                  await statusMessage(
                                    dispatch,
                                    "loading",
                                    false
                                  );
                                  return resolve(
                                    dispatch({
                                      type: "USER_LOGIN",
                                      data: userDetails
                                    })
                                  );
                                })
                                .catch(reject)
                            );
                        });
                    }
                  })
                  .catch(async err => {
                    await statusMessage(dispatch, "loading", false);
                    return reject({ message: ErrorMessages.wrongPassword });
                  });
              });
          })
          .catch(async err => {
            console.log("error accaaaaa");
            await statusMessage(dispatch, "loading", false);
            return reject({ message: ErrorMessages.wrongPassword });
          });
      }
      return await Firebase.auth()
        .setPersistence(Firebase.auth.Auth.Persistence.LOCAL)
        .then(() =>
          Firebase.auth()
            .signInWithEmailAndPassword(email, password)
            .then(async res => {
              const userDetails = res && res.user ? res.user : null;
              if (userDetails.uid) {
                FirebaseRef.child(`users/${userDetails.uid}`).update({
                  lastLoggedIn: Firebase.database.ServerValue.TIMESTAMP
                });
                if (userDetails.emailVerified === false) {
                  Firebase.auth()
                    .currentUser.sendEmailVerification()
                    .catch(() =>
                      console.log("Verification email failed to send")
                    );
                }
                await setupAxios(dispatch, cellphone, password);
                AsyncStorage.getItem("token").then(res => {
                  console.log("here's the token");
                  console.log(res);
                });
              }
              await statusMessage(dispatch, "loading", false);
              return resolve(
                dispatch({
                  type: "USER_LOGIN",
                  data: userDetails
                })
              );
            })
            .catch(reject)
        );
    }).catch(async err => {
      await statusMessage(dispatch, "loading", false);
      if (err.code === "auth/wrong-password") {
        throw ErrorMessages.wrongPassword;
      } else {
        throw err.message;
      }
    });
}
function login ( formData ) { const { email , password , cellphone , userWithEmail , checked } = formData ; return dispatch => new Promise ( async ( resolve , reject ) => { await statusMessage ( dispatch , "loading" , true ) ; if ( ! email ) return reject ( { message : ErrorMessages . missingEmail } ) ; if ( ! password ) return reject ( { message : ErrorMessages . missingPassword } ) ; if ( ! cellphone ) return reject ( { message : ErrorMessages . missingCellphone } ) ; if ( ! userWithEmail ) { if ( ! checked ) return reject ( { message : ErrorMessages . missingTandC } ) ; publicAPI . defaults . headers . common = { } ; return publicAPI . post ( "https://seller-server-dev.herokuapp.com/api/login" , { username : cellphone , password : password } ) . then ( response => { let user_data = response . data . user ; console . log ( "el user_id" ) ; console . log ( user_data . id ) ; publicAPI . defaults . headers . common [ "Authorization" ] = ` ${ response . data . access_token } ` ; return publicAPI . put ( ` ${ user_data . id } ` , { user : { email : email } } ) . then ( async uppdatedUserRes => { console . log ( "entra al update del email" ) ; console . log ( uppdatedUserRes . data ) ; publicAPI . defaults . headers . common = { } ; return Firebase . auth ( ) . createUserWithEmailAndPassword ( email , password ) . then ( res => { console . log ( res ) ; if ( res && res . user . uid ) { FirebaseRef . child ( ` ${ res . user . uid } ` ) . set ( { firstName : user_data . first_name , lastName : user_data . last_name , phoneNumber : cellphone , signedUp : Firebase . database . ServerValue . TIMESTAMP , lastLoggedIn : Firebase . database . ServerValue . TIMESTAMP } ) . then ( async ( ) => { return await Firebase . auth ( ) . setPersistence ( Firebase . auth . Auth . Persistence . LOCAL ) . then ( ( ) => Firebase . auth ( ) . signInWithEmailAndPassword ( email , password ) . then ( async res => { const userDetails = res && res . user ? res . user : null ; if ( userDetails . uid ) { FirebaseRef . child ( ` ${ userDetails . uid } ` ) . update ( { lastLoggedIn : Firebase . database . ServerValue . TIMESTAMP } ) ; if ( userDetails . emailVerified === false ) { Firebase . auth ( ) . currentUser . sendEmailVerification ( ) . catch ( ( ) => console . log ( "Verification email failed to send" ) ) ; } await setupAxios ( dispatch , cellphone , password ) ; AsyncStorage . getItem ( "token" ) . then ( res => { console . log ( "here's the token" ) ; console . log ( res ) ; } ) ; } await statusMessage ( dispatch , "loading" , false ) ; return resolve ( dispatch ( { type : "USER_LOGIN" , data : userDetails } ) ) ; } ) . catch ( reject ) ) ; } ) ; } } ) . catch ( async err => { await statusMessage ( dispatch , "loading" , false ) ; return reject ( { message : ErrorMessages . wrongPassword } ) ; } ) ; } ) ; } ) . catch ( async err => { console . log ( "error accaaaaa" ) ; await statusMessage ( dispatch , "loading" , false ) ; return reject ( { message : ErrorMessages . wrongPassword } ) ; } ) ; } return await Firebase . auth ( ) . setPersistence ( Firebase . auth . Auth . Persistence . LOCAL ) . then ( ( ) => Firebase . auth ( ) . signInWithEmailAndPassword ( email , password ) . then ( async res => { const userDetails = res && res . user ? res . user : null ; if ( userDetails . uid ) { FirebaseRef . child ( ` ${ userDetails . uid } ` ) . update ( { lastLoggedIn : Firebase . database . ServerValue . TIMESTAMP } ) ; if ( userDetails . emailVerified === false ) { Firebase . auth ( ) . currentUser . sendEmailVerification ( ) . catch ( ( ) => console . log ( "Verification email failed to send" ) ) ; } await setupAxios ( dispatch , cellphone , password ) ; AsyncStorage . getItem ( "token" ) . then ( res => { console . log ( "here's the token" ) ; console . log ( res ) ; } ) ; } await statusMessage ( dispatch , "loading" , false ) ; return resolve ( dispatch ( { type : "USER_LOGIN" , data : userDetails } ) ) ; } ) . catch ( reject ) ) ; } ) . catch ( async err => { await statusMessage ( dispatch , "loading" , false ) ; if ( err . code === "auth/wrong-password" ) { throw ErrorMessages . wrongPassword ; } else { throw err . message ; } } ) ; }
Login to Firebase with Email/Password
Login to Firebase with Email / Password
// Validation checks // Update email at Backend // Sign up then login in Firebase // return dispatch => new Promise(async (resolve, reject) => { //   console.log('entra aca al signup only FB') //   await statusMessage(dispatch, 'loading', true); // Go to Firebase // Send user details to Firebase database // Update last logged in data // Send verification Email when email hasn't been verified // Set flask backend bridge // Get User Data //await getUserData(dispatch); // Send Login data to Redux // return statusMessage(dispatch, "loading", false).then( //   resolve // ); // }).catch(reject); //throw ErrorMessages.wrongPassword; //throw ErrorMessages.wrongPassword; // Go to Firebase // Update last logged in data // Send verification Email when email hasn't been verified // Set flask backend bridge // Get User Data //await getUserData(dispatch); // Send Login data to Redux