John Davidson

php - Add additional data to request object after initialisation

0 comments
Message:


The below public function returns oauth token against user name and password. However, I have a requirement where, the username has to queried first from email id. In the first part of the function, I need to somehow add the username to the request object. The request is created using laminas from what I can understand.


Full code from which function is taken is here.


  /**
* Processes POST requests to /oauth/token.
*/
public function token(ServerRequestInterface $request) {

////////////////
////////////////
// ADD LOGIC TO GET EMAIL FROM REQUEST & GET USERNAME
// ADD USERNAME TO $request
////////////////
////////////////

//Extract the grant type from the request body.
$body = $request->getParsedBody();
$grant_type_id = !empty($body['grant_type']) ? $body['grant_type'] : 'implicit';
$client_drupal_entity = NULL;
if (!empty($body['client_id'])) {
$consumer_storage = $this->entityTypeManager()->getStorage('consumer');
$client_drupal_entities = $consumer_storage
->loadByProperties([
'uuid' => $body['client_id'],
]);
if (empty($client_drupal_entities)) {
return OAuthServerException::invalidClient($request)
->generateHttpResponse(new Response());
}
$client_drupal_entity = reset($client_drupal_entities);
}
// Get the auth server object from that uses the League library.
try {
// Respond to the incoming request and fill in the response.
$auth_server = $this->grantManager->getAuthorizationServer($grant_type_id, $client_drupal_entity);
$response = $this->handleToken($request, $auth_server);
}
catch (OAuthServerException $exception) {
watchdog_exception('simple_oauth', $exception);
$response = $exception->generateHttpResponse(new Response());
}
return $response;
}

The request is send as form data:
See example js code below:
(username is accepted, email param is added to demonstrate whats needed)


var formdata = new FormData();
formdata.append("grant_type", "password");
formdata.append("client_id", "828472a8-xxxx-xxxx-xxx-ab041d3b313a");
formdata.append("client_secret", "secret-xxx-xxx-xxx");
//formdata.append("username", "username");
formdata.append("email", "[email protected]");
formdata.append("password", "password");

var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};

fetch("{{base_url}}oauth/token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));


My Answer:
To add the username to the request object before processing the token request, you can modify the code as follows:

php
/**
* Processes POST requests to /oauth/token.
*/
public function token(ServerRequestInterface $request) {

// Extract the email from the request body
$body = $request->getParsedBody();
$email = !empty($body['email']) ? $body['email'] : '';

// Query the username based on the email (Add your logic here)
$username = getUsernameFromEmail($email);

// Add the username to the request object
$request = $request->withAddedParsedBody('username', $username);

// Continue with the existing code
$grant_type_id = !empty($body['grant_type']) ? $body['grant_type'] : 'implicit';
$client_drupal_entity = NULL;
if (!empty($body['client_id'])) {
$consumer_storage = $this->entityTypeManager()->getStorage('consumer');
$client_drupal_entities = $consumer_storage
->loadByProperties([
'uuid' => $body['client_id'],
]);
if (empty($client_drupal_entities)) {
return OAuthServerException::invalidClient($request)
->generateHttpResponse(new Response());
}
$client_drupal_entity = reset($client_drupal_entities);
}

// Get the auth server object from that uses the League library.
try {
// Respond to the incoming request and fill in the response.
$auth_server = $this->grantManager->getAuthorizationServer($grant_type_id, $client_drupal_entity);
$response = $this->handleToken($request, $auth_server);
} catch (OAuthServerException $exception) {
watchdog_exception('simple_oauth', $exception);
$response = $exception->generateHttpResponse(new Response());
}

return $response;
}


In the above code snippet, I added a section to extract the email from the request body, query the username based on the email, and then add the username to the request object using the `withAddedParsedBody` method. You can replace the `getUsernameFromEmail($email)` function with your actual logic to retrieve the username based on the email.

By adding the username to the request object before processing the token request, you can now access the username in the subsequent code where needed.

Rate this post

5 of 5 based on 1171 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us