Last active
October 10, 2017 01:48
-
-
Save elialejandro/99efc6468fa13661e8625dc3f25344f1 to your computer and use it in GitHub Desktop.
JwtAuth para Symfony usando características de PHP 5.5 o superior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace AppBundle\Services; | |
use Doctrine\ORM\EntityManagerInterface; | |
use Firebase\JWT\JWT; | |
class JwtAuth | |
{ | |
protected $em; | |
protected $key; | |
public function __construct(EntityManagerInterface $entityManager) | |
{ | |
$this->em = $entityManager; | |
$this->key = 'secret'; | |
} | |
public function signup($email, $password, $getHash = null) | |
{ | |
$user = $this->em->getRepository('BackendBundle:User')->findOneBy([ | |
'email' => $email, | |
]); | |
$signup = false; | |
$data = [ | |
'status' => 'error', | |
'message' => 'User or password not valid!!', | |
]; | |
if (is_object($user) && password_verify($password, $user->getPassword())) { | |
$signup = true; | |
} | |
if ($signup) { | |
$token = [ | |
'sub' => $user->getId(), | |
'email' => $user->getEmail(), | |
'name' => $user->getName(), | |
'surname' => $user->getSurname(), | |
'iat' => time(), | |
'exp' => time() + (7 * 24 * 60 * 60), | |
]; | |
$token = JWT::encode($token, $this->key, 'HS256'); | |
if (!$getHash) { | |
$data = [ | |
'status' => 'success', | |
'token' => $token, | |
]; | |
} else { | |
$data = $token; | |
} | |
} | |
return $data; | |
} | |
public function checkToken($token, $getIdentity = false) | |
{ | |
$auth = false; | |
try { | |
$decoded = JWT::decode($token, $this->key, ['HS256']); | |
} catch (\UnexpectedValueException | \DomainException $e) { | |
$auth = false; | |
} | |
if (isset($decoded) && is_object($decoded) && isset($decoded->sub)) { | |
$auth = true; | |
} | |
if ($getIdentity) { | |
return $decoded; | |
} | |
return $auth; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment