Laravel JWT return data from two tables - database

I am using JWT authentication via api.php
when a user login to the route
Route::post('login', 'AuthController#login');
he reached this method in auth controller
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 1000,
'user' => auth()->user()
]);
}
Here 'user' => auth()->user() is returning the data from user table,
I have another table user_Details in which all user information is saved, I want to fetch details from that table to when some one login,
Help me out please.

I have find another simple way to do that
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 1000,
'user' => auth()->user(),
'user_detail' => user_detail::where('user_id','=',auth()->user()->id)->get()
]);
}

Related

Laravel API and React js beginner here. I keep getting Error 422 in my application even though I am passing the required field

I have been trying to debug this error for a while now. I tried scouring the internet for solutions, yet I still can't find the fix for it. I am passing the required data for the API to work, but the error is still there.
Laravel Controller
protected function searchAdmin(Request $request)
{
$data = $request->validate([
'admin_ref' => 'string|required'
]);
$admin = adminInfos::where('adminID', $data['admin_ref'])->first();
if (!$admin) {
return response()->json([
'status' => '404',
'message' => $this->response['AccntNtFnd']
]);
} else {
return response()->json([
'status' => '200',
'account' => $admin
]);
}
}
React JS
const searchAdmin = (e) =>{
e.preventDefault();
axios.get(`http://127.0.0.1:8001/api/admin/adminSearch`, {
'headers':{
'Accept':'application/json',
'Content-Type':'application/json',
},
'data':{
'admin_ref': adminInput.searchInput
}
}).then(res=>{
if(res.data.status != 200){
console.log(res.data.message)
}else{
console.log(res.data.message)
}
}).catch(error => {
console.log(error.response.data)
});
}
UPDATE: I followed Nelson's advice, but the error still exists. Thank you for the advice tho, will make sure to take note of it.

Migrating from Stripe CardElement to PaymentElement

I currently have a Laraval/react app that is using Stripe and cashier to manage subscriptions. I am trying to migrate from the CardElement to the Payment Element.
My issue is I don't understand how to integrate the last part of the migration discussed in the docs. below is a screenshot of the part I need help with from the Stripe Docs
How my code currently works (but obviously does not once I implement the PaymentElement instead of the CardElement):
...
const result = await stripe.confirmCardSetup(intent.client_secret, {
payment_method: {
card: elements.getElement(CardElement),
},
});
if (result.error) {
console.log(result.error.message);
} else {
Inertia.visit(
route('subscriptions.start'),
{
method: 'post',
data: {
token: result.setupIntent.payment_method,
plan: 'small-office-plan',
}
}
);
}
...
which starts the subscription from the server :
public function start(Request $request)
{
$this->validate($request, [
'token' => 'required'
]);
$planId = 'price_1KJ2AfA7lb2vuawxuBX3Tl1N';
$request->user()->newSubscription('default', $planId)->create($request->token);
return redirect('/dashboard')->with(
'message',
[
'type' => 'success',
'text' => 'Subscription Started'
]
);
}
My issue here is that this 'migration' changes the functionality and will redirect, however, I need it to pass through my start function. Advice on how to do this correctly?

I am trying to get all Power BI reports while this process I sent CURL request in PHP to authenticate the user but it's throwing below error response

Please help me how to resolve this issue.
Error Response:
Array
(
[error] => invalid_grant
[error_description] => AADSTS65001: The user or administrator has not consented to use the application with ID '27ccc3c6-6560-461c-bf42-c0f3f756fa7a' named 'DrCloudEHR - East'. Send an interactive authorization request for this user and resource.
Trace ID: c137e449-e653-43d8-88f8-9abb8499b100
Correlation ID: 0b2f5c0d-ac09-49bc-81f3-b8b95a185186
Timestamp: 2020-11-20 06:10:03Z
[error_codes] => Array
(
[0] => 65001
)
[timestamp] => 2020-11-20 06:10:03Z
[trace_id] => c137e449-e653-43d8-88f8-9abb8499b100
[correlation_id] => 0b2f5c0d-ac09-49bc-81f3-b8b95a185186
[suberror] => consent_required
)
CURL REQUEST code:
$curlPostToken = curl_init();
curl_setopt_array($curlPostToken, array(
CURLOPT_URL => "https://login.windows.net/common/oauth2/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array(
grant_type => 'password',
scope => 'openid',
prompt => 'admin_consent',
client_secret => '~-8gGXjt~Ag7_o_N0~l9.K63Iza_FA49TR',
resource => 'https://analysis.windows.net/powerbi/api',
client_id => '27ccc3c6-6560-461c-bf42-c0f3f756fa7a', // Registered App ApplicationID
username => '*********g#*******.com', // for example john.doe#yourdomain.com
password => '**********' // Azure password for above user
)
));
$tokenResponse = curl_exec($curlPostToken);
$tokenError = curl_error($curlPostToken); print_r($tokenError);
curl_close($curlPostToken);
$tokenResult = json_decode($tokenResponse, true);
print_r($tokenResult); exit;

Create password hash from model

I need to hash a password from my "reset password" code. The obvious way to do it is deprecated:
class ResetPasswordsController {
public function reset () {
$this->ResetPassword->changePassword('correct horse battery staple');
}
}
class ResetPassword {
public function changePassword ($password) {
$hash = AuthComponent::password($password);
}
}
class AuthComponent extends Component {
public static function password($password) {
return Security::hash($password, null, true);
}
}
... and it doesn't work anyway because I'm using a custom password hasher, of which AuthComponent::password() is obviously not aware.
Comments says:
#deprecated 3.0.0 Since 2.4. Use Security::hash() directly or a password hasher object.
... but I can't figure out the syntax to call my hasher:
class CustomPasswordHasher extends AbstractPasswordHasher {
}
... esp. if I want to take app settings into account:
class AppController extends Controller {
public $components = array(
'Auth' => array(
'authenticate' => array(
'Custom' => array(
'passwordHasher' => array(
'className' => 'Foo',
'cost' => 10,
),
'userModel' => 'MyUserModel',
'fields' => array(
'username' => 'my_username_column',
'password' => 'my_auth_token_column'
),
)
),
),
);
}
Is there an instance of the hasher hooked somewhere in either controller or model?
Any idea?
In Cakephp 3.X you can do this in Model/Entity/User.php
protected function _setPassword($password)
{
if(strlen($password) > 0)
{
return (new DefaultPasswordHasher)->hash($password);
}
}
https://book.cakephp.org/3.0/en/controllers/components/authentication.html#hashing-passwords
I found a mechanism that seems to work:
class ResetPasswordsController {
public function reset () {
if (!$this->Auth->_authenticateObjects) {
$this->Auth->constructAuthenticate();
}
$passwordHasher = $this->Auth->_authenticateObjects[0]->passwordHasher();
$this->ResetPassword->changePassword('correct horse battery staple', $passwordHasher);
}
}
class ResetPassword {
public function changePassword ($password, AbstractPasswordHasher $passwordHasher) {
$hash = $passwordHasher->hash($password);
}
}
The tricky bit is that there doesn't seem to be an instance of the AuthComponent, probably because the reset password page is not password-protected. However, I can instantiate it myself with AuthComponent::constructAuthenticate().

Converting HttpFoundation\Response to an array

My symfony request is returning array with entity object and setstate method.
This is the dump of the array.
array (
0 =>
HealthyLiving\ApiBundle\Entity\User::__set_state(array(
'id' => 1,
'username' => 'admin',
'password' => '123',
'email' => 'batoosay#gmail.com',
'isActive' => false,
)),
)
And here is the code:
public function loginAction()
{
$restresult = $this->getDoctrine()->getRepository('ApiBundle:User')->findAll();
if ($restresult === null) {
return new View("there are no users exist", Response::HTTP_NOT_FOUND);
}
echo '<pre>' . var_export($restresult, true) . '</pre>';die;
return new JsonResponse(
$restresult
);
}
The JsonResponse is empty because of the strange array. How do i convert this array of object to json ?
try to serialize with JMS like this:
$serializer = $this->get('jms_serializer');
return new Response(
$serializer->serialize($restresult, 'json')
);

Resources