Skip to content

Instantly share code, notes, and snippets.

@gaulatti
Created July 14, 2014 15:09
Show Gist options
  • Save gaulatti/8b5d6da78e908beebeae to your computer and use it in GitHub Desktop.
Save gaulatti/8b5d6da78e908beebeae to your computer and use it in GitHub Desktop.
Login con RUT en Symfony2
<?php
namespace rotVulpix\TestBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\SimpleFormAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use rotVulpix\TestBundle\Services\ValidacionRUT;
class RutAuthenticator implements SimpleFormAuthenticatorInterface
{
private $encoderFactory;
public function __construct(EncoderFactoryInterface $encoderFactory)
{
$this->encoderFactory = $encoderFactory;
}
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
try {
// Obtener y Limpiar Rut
$rut = $token->getUsername();
// Validar Forma e Integridad
$rutValido = new ValidacionRUT($rut);
if(!$rutValido) { throw new AuthenticationException('RUT Inválido'); }
// Validar Usuario
$user = $userProvider->loadUserByUsername($rutValido->getCuerpo());
} catch (UsernameNotFoundException $e) {
throw new AuthenticationException('RUT Inválido');
}
$encoder = $this->encoderFactory->getEncoder($user);
if(!is_null($token->getCredentials())) {
$passwordValid = $encoder->isPasswordValid(
$user->getPassword(),
$token->getCredentials(),
$user->getSalt()
);
} else {
$passwordValid = true;
}
if ($passwordValid) {
return new UsernamePasswordToken(
$user,
$user->getPassword(),
$providerKey,
$user->getRoles()
);
}
throw new AuthenticationException('RUT o Contraseña Inválidos');
}
public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof UsernamePasswordToken
&& $token->getProviderKey() === $providerKey;
}
public function createToken(Request $request, $username, $password, $providerKey)
{
return new UsernamePasswordToken($username, $password, $providerKey);
}
}
<?php
namespace rotVulpix\TestBundle\Services;
class ValidacionRUT {
private $cuerpo, $digito;
function __construct($rut) {
// Limpieza
$rut = str_replace('.', '', $rut);
// Aislación de DV
$rutSeparado = explode('-', $rut);
$cuerpo = $rutSeparado[0];
if(isset($rutSeparado[1])) {
// El RUT estaba separado con Guión
$digito = $rutSeparado[1];
} else {
/* No está separado con Guión, por lo que se asume que el
* último caracter es el Dígito Verificador
*/
$digito = substr($rut, -1);
$cuerpo = substr($rut, 0, -1);
}
$this->cuerpo = $cuerpo;
$this->digito = $digito;
return $this->Modulo11();
}
private function Modulo11() {
// Obtener desde Instancia
$cuerpo = $this->cuerpo;
$digito = $this->digito;
// Contadores
$x = 2;
$s = 0;
for ($i = strlen($cuerpo)-1; $i>=0; $i--)
{
if($x >7) {
$x=2;
}
$s += $cuerpo[$i]*$x;
$x++;
}
// Cálculo del DV
$dv=11-($s % 11);
if ($dv == 10) { $dv = 'K'; }
if ($dv == 11) { $dv = '0'; }
// Comparación
if ((string) $dv !== (string) $digito) {
return false;
} else {
return true;
}
}
public function getCuerpo() {
return $this->cuerpo;
}
}
@gaulatti
Copy link
Author

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