Skip to content

Instantly share code, notes, and snippets.

@carlosvarela
Forked from felipemarcos/wp-cpf-login.php
Created July 5, 2017 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosvarela/dfc063c4a829db754464424ee75cb2bc to your computer and use it in GitHub Desktop.
Save carlosvarela/dfc063c4a829db754464424ee75cb2bc to your computer and use it in GitHub Desktop.
Permitir login por CPF - WordPress
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Login
*/
class Custom_CPF_Login {
public function __construct() {
add_filter( 'authenticate', array($this, 'authenticate_user'), 20, 3 );
}
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;
}
public function attempt_login($password, $current_password, $id) {
return wp_check_password($password, $current_password, $cpf_user->data->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) {
/* Login by CPF */
// 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;
}
// Error Messages
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);
}
public function user_cpf_error() {
$text = '<strong>ERRO:</strong> CPF inválido.';
new WP_Error( 'broke', $text);
}
}
new Custom_CPF_Login();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment