Skip to content

Instantly share code, notes, and snippets.

@felipemarcos
Last active July 3, 2023 15:12
Show Gist options
  • Save felipemarcos/bad83e0d8999c973983cafae73a54ce6 to your computer and use it in GitHub Desktop.
Save felipemarcos/bad83e0d8999c973983cafae73a54ce6 to your computer and use it in GitHub Desktop.
Permitir login por CPF - WordPress
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Plugin Name: Login por CPF
* Description: Permite o usuário se logar utilizando o CPF.
* Author: Felipe Marcos
* Author URI: https://felipe.zip
* License: GNU General Public License v3 or later
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
class WPCPFLogin {
public function __construct() {
add_filter( 'authenticate', array($this, 'authenticate_user'), 20, 3 );
add_action( 'show_user_profile', array($this, 'custom_fields') );
add_action( 'edit_user_profile', array($this, 'custom_fields') );
add_action( 'user_new_form', array($this, 'custom_fields') );
add_action( 'personal_options_update', array($this, 'save_custom_fields') );
add_action( 'edit_user_profile_update', array($this, 'save_custom_fields') );
add_action( 'user_register', array($this, 'save_custom_fields') );
}
/**
* Checks if the current CPF is valid.
* @param string $cpf CPF number
* @return bool
*/
public function is_valid_cpf($cpf) {
$cpf = preg_replace("/[^0-9]/", "", $cpf);
$digitOne = 0;
$digitTwo = 0;
for ($i = 0, $x = 10; $i <= 8; $i++, $x--):
$digitOne += $cpf[$i] * $x;
endfor;
for ($i = 0, $x = 11; $i <= 9; $i++, $x--):
if (str_repeat($i, 11) == $cpf):
return false;
endif;
$digitTwo += $cpf[$i] * $x;
endfor;
$calcOne = (($digitOne%11) < 2) ? 0 : 11-($digitOne%11);
$calcTwo = (($digitTwo%11) < 2) ? 0 : 11-($digitTwo%11);
if ($calcOne <> $cpf[9] || $calcTwo <> $cpf[10]):
return false;
else:
return true;
endif;
}
/**
* Attempts to log the user in.
* @param string $password Stored password
* @param string $current_password Current password
* @param string $id user id
* @return bool
*/
public function attempt_login($password, $current_password, $id) {
return wp_check_password($password, $current_password, $id);
}
public function get_user_by_cpf($cpf) {
$cpf_user = get_users(
array(
'meta_key' => 'cpf',
'meta_value' => $cpf
)
);
if ( count($cpf_user) > 0 ):
return $cpf_user[0];
endif;
return false;
}
public function authenticate_user($user, $username, $password) {
// Remove everything but numbers from the username
$cpf = preg_replace('/[^0-9]/', '', $username);
// Is it a CPF?
if ( strlen($cpf) == 11 && is_int( (int)$cpf ) ):
// Validate CPF
if ( !$this->is_valid_cpf($cpf) ):
$user = $this->user_cpf_error();
endif;
// Find user by CPF
$cpf_user = $this->get_user_by_cpf($cpf);
// Found a user?
if ( $cpf_user ):
$current_password = $cpf_user->data->user_pass;
$id = $cpf_user->data->ID;
// Is the password valid?
if ( $this->attempt_login($password, $current_password, $id) ):
$user = $cpf_user;
else:
// Invalid Password
$user = $this->user_password_error();
endif;
endif;
endif;
// defaults to email or username
return $user;
}
/**
* Flashes invalid password error
* @return WP_Error
*/
private function user_password_error() {
$text = '<strong>ERRO</strong>: A senha está incorreta. <a href="' . esc_url( wp_lostpassword_url() ) . '">Esqueceu a senha?</a>';
return new WP_Error('broke', $text);
}
/**
* Flashes invalid CPF error
* @return WP_Error
*/
public function user_cpf_error() {
$text = '<strong>ERRO:</strong> CPF inválido.';
return new WP_Error('broke', $text);
}
public function custom_fields( $user ) {
$cpf = '';
if ($user !== 'add-new-user'):
$cpf = get_the_author_meta( 'cpf', $user->ID );
endif;
?>
<h3>Informações adicionais</h3>
<table class="form-table">
<tr>
<th><label for="cpf">CPF</label></th>
<td>
<input type="text" name="cpf" id="cpf" value="<?php echo esc_attr( $cpf ); ?>" class="regular-text" /><br />
</td>
</tr>
</table>
<?php }
public function save_custom_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
$cpf = sanitize_text_field( $_POST['cpf'] );
update_user_meta( $user_id, 'cpf', $cpf );
}
}
new WPCPFLogin();
@edersilva
Copy link

Perfeito @felipemarcos Parabéns pela contribuição.

@meninomiel
Copy link

Cara, esse seu código me ajudou muito a criar uma regra específica de login em um projeto. Valeu!

@marcilioqsj
Copy link

Fala Felipe! Consegui aqui e funcionou de boa! Mas deixa eu te perguntar uma coisa. No meu caso eu to fazendo um site que vai servir como treinamento interno para uma equipe. Os usuários precisam poder se registrar com CPF como chave ao invés do email. O seu plugin faz isso? Se não faz, você pegaria um freela pra desenvolver isso?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment