Allow login by email, CPF or CNPJ Woocommerce

Asked

Viewed 2,413 times

1

I need to make a filter where it is allowed to login with the CPF or CNPJ in addition to those already allowed by Woocommerce, which is the email or user, on the My Account page. In short, I need to be able to log in with email, user, Cpf or cnpj

I read that the filter that can do this is the add_filter( 'authenticate', 'my_custom_authenticate', 10, 3 ); but I don’t know how to.

I’m using the plugin Woocommerce Extra Checkout Fields for Brazil to add the fields.

3 answers

3


I don’t know exactly how this plugin stores the data, but the code to make the login work with them will be something like this.

add_filter( 'authenticate', 'ptstackoverflow_auth_com_cpf_ou_cpnj', 99, 3 );

function ptstackoverflow_auth_com_cpf_ou_cpnj( $user, $username, $password ) {
    global $wpdb;

    // Se o primeiro parametro não é null, o usuário já está autenticado
    if ( $user ) {
        return $user;
    }

     // Passo 1: procurar no banco um usuário que tenha aquele CPF ou CNPJ 
     // ( que está na variável $username ).
     // exemplo, supondo que as meta_keys sejam "cpf" e "cnpj":
     $user_row = $wpdb->get_results( 
        $wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}usermeta 
                         WHERE ( meta_key = 'cpf' AND meta_value = '%s') 
                         OR ( meta_key = 'cnpj' AND meta_value = '%s' )",
                        $username, $username ) );

    // Passo 2: Se encontrou, pega o objeto desse usuário,
    // confere a senha
     if ( ! empty( $user_row ) ) {
        $user = get_user_by( 'ID', $user_row[0]->ID );
        // Passo 3: Se a senha confere você retorna o objeto do usuário (WP_User)
        if ( wp_check_password( $password, $user->user_pass, $user_row[0]->ID ) ) {
            return $user;
        }       
     }

     /** 
     * Se não encontrou ou se a senha não confere, retorne um objeto WP_Error 
     * com a mensagem que deve aparecer 
     */
    return new WP_Error( '', 'mensagem de erro', $username );
}

That’s just one example, needs to be modified to work in your case.

1

Thanks for the help! I managed to do the authentication, but only for one type (CPF or CNPJ), I would like to check for both. I think it’s time to make the $wpdb-prepare, but according to my research, I can’t do two Select’s at once. Follows how is my code checking only by CPF:

add_filter('authenticate', 'login_cpf_cnpj', 10, 3);
function login_cpf_cnpj($user, $username, $password){
   if ($username == '' || $password == '') return;

   global $wpdb;
   if ($user) {
     return $user;
   }
    $user_row = $wpdb->get_results(
    $wpdb->prepare( "SELECT user_id FROM {$wpdb->prefix}usermeta 
                     WHERE ( meta_key = 'billing_cpf' AND meta_value = '%s') 
                     OR ( meta_key = 'billing_cnpj' AND meta_value = '%s' )",
        $username, $username ) );

   if (!empty($user_row)) {
     $user = get_user_by('ID', $user_row[0]->user_id);
     if ($user && wp_check_password($password, $user->user_pass, $user_row[0]->user_id)) {
        return $user;
     } else { ?>
          <script>
              alert('Senha Inválida!');
              window.location = "<?php get_permalink(); ?>";
          </script>
        <?php
     }
  }
  return $user;
}

UPDATE: as Ricardo answered, I changed my code to search 2 fields.

  • 1

    updated my answer with the searching code in 2 fields

  • Thank you Ricardo! Gave it right!

  • 1

    Perfect! This topic helped me a lot. Thank you all. I was also trying to create the same functionality with login and registration by Ajax on my site, and I ended up adapting my code with the query to the database using the function proposed here. Works well with the plugin Woocommerce Extra Checkout Fields for Brazil, which increases the checkout with the fields Cpf and cnpj https://br.wordpress.org/plugins/woocommerce-extra-checkout-fields-for-brazil/

1

Look at you make him choose between Cpf and cnpj you can put a condition to check the number of digits if it is greater than 12 do the cnpj test if you do not do the Cpf.

  • The tip is good, but you could have left an example with code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.