Last active
December 14, 2017 09:33
-
-
Save chalasr/58bb4ef37ebaf73bdafc to your computer and use it in GitHub Desktop.
Generate a token manually in controller - LexikJWTAuthenticationBundle
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 App\UserBundle\Controller; | |
use Doctrine\ORM\EntityManager; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Symfony\Component\HttpFoundation\JsonResponse; | |
use Symfony\Component\HttpFoundation\Request; | |
/** | |
* Mangages users authentication in API. | |
* | |
* @author Robin Chalas | |
*/ | |
class SecurityController extends Controller | |
{ | |
/** | |
* Register new user account and returns token. | |
* | |
* @param Request $request | |
*/ | |
public function registerUserAccountAction(Request $request) | |
{ | |
$data = $request->request->all(); | |
$userManager = $this->getUserManager(); | |
return $this->generateToken($this->createUser($data), 201); | |
} | |
/** | |
* Creates new User. | |
* | |
* @param array $data | |
* | |
* @return User $user | |
*/ | |
protected function createUser($data) | |
{ | |
$userManager = $this->getUserManager(); | |
$user = $userManager->createUser(); | |
$user->setUsername($data['name']); | |
$user->setEmail($data['email']); | |
$user->setPlainPassword($data['password']); | |
$user->setEnabled(true); | |
$userManager->updateUser($user); | |
return $user; | |
} | |
/** | |
* Generates a JsonWebToken from user. | |
*/ | |
protected function generateToken($user, $statusCode = 200) | |
{ | |
// Call the jwt_manager service & create the token | |
$token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user); | |
// If you want, add some user informations | |
$userInformations = array( | |
'id' => $user->getId(), | |
'username' => $user->getUsername(), | |
'email' => $user->getEmail(), | |
'roles' => $user->getRoles(), | |
); | |
// Build your response | |
$response = array( | |
'token' => $token, | |
'user' => $user, | |
); | |
// Return the response in JSON format | |
return new JsonResponse($response, $statusCode); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment