The values ​are not sent via the request body. - Cakephp 4 - cakephp

I created a login form that uses email and password for authentication, but the credentials are not sent in the request body and I get a 500 error.
This is my login method:
if ($this->request->is('post')) {
$response = $http->post(
'http://localhost:8889/api/..',
[
'email' => $this->request->getData("email"),
'password' => $this->request->getData("password"),
]
);
debug($response);
In the image it is possible to verify a little more than I receive.
I put the information below in the debug, and I get the value coming from the form.
'email' => $this->request->getData("email"), 'password' => $this->request->getData("password")
When I test via mailman, the login is successful! Information coming from the form is not sent to the backend. Can you help me analyze?

Related

Axios post form data with user id of Logged in user

i want to post my form data using axios.post with the current user login id.
axios.post('http://localhost:8000/api/add-property/',
formData, {
headers:{
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': 'http://http://127.0.0.1:8000',
'Access-Control-Allow-Credentials': true,
}
}
).then(function(response){
console.log(response.data.message)
}).catch(function(error){
console.log(error)
});
kindly tell me about these things ?
what should be the api url to add some data with the id of logged in user ?
how to get the current logged in user id ?
my backend is in laravel and my store function controller is something like this :-
public function AddProperty(Request $request, $id) {
$validator = Validator::make($request->all(),
[
"agency_name" => "required",
"agency_location" => "required",
// my rest of validations
]
);
if($validator->fails()) {
return response()->json(["status" => "failed", "validation_errors" => $validator-
>errors()]);
}
//--------------------get user id---------------------------------------------------
$user = array();
$user = DB::table('users')->where('id', $id)->first();
$user_identification = $user->id;
//----------------------------------------------------------------------------------
$agency_name = $request->input('agency_name');
$agency_location = $request->input('agency_location');
$user_id = $user_identification;
$propertyArray = array(
'agency_name' => "$agency_name",
'agency_location' => "$agency_location",
'user_id' => $user_identification
);
$property = AddProperty::create($propertyArray);
return "property added succesfully with id:".$property->id;
my route for add property is :-
Route::post("add-property/{id}", "AddPropertyController#AddProperty");
when i pass id from postman it enters data into the database i am confused with how to get the id from the react and pass it in the post api and the enter the data in my db.
kindly someone help me and thanks in advance
If you are using laravel authentication you can simply call
$user = Auth::user();
to retrieve the authenticated user
If you are not using the laravel authentication, well it depends on how you implemented that
Save the logged in user object or the auth(bearer token) in the local storage of the browser.
Then when sending with the post api simply use that token or user id in the header of your api.
You can use the local storage solution like this:
var userObj= JSON.parse(localStorage.getItem('userObj'));
Or you can use react js props solution in componentWillReceiveProps get the logged in user.

How to create Token-Based Authentication(oauth2) for AngularJS and Laravel Apps via passport

I created an web app which it uses laravel default registration(auth), I've tested passport oauth2 client access token from taylor tutorial. My web app uses angular js for UI and laravel for backend , so I need to create user, when create user request is sent from angular and then create a global access token to give it in my response to angular which then in all later request I use it to authenticate requests.
actually I want to implement oauth2 authentication for my web app, but so far I've searched a lot but I couldn't find any useful step by step tutorial for it.
anyone can help me out?
FYI: I'm using laravel 5.3 with passport enabled and angular js 1.5 for frontend.
Use JWT token based authentication here you can learn about jwt https://jwt.io/
I've solved this.
I've Customized laravel auth for login and register and created a method which will send a request to the server to create an access token for registering user or log in.
I've set up passport and test it as taylor did in his toturial.
then in AuthenticatesUsers.php I've changed sendloginResponse method response like :
protected function sendLoginResponse(Request $request)
{
isset($request->token) ? $token = $request->token : $token = null;//Check if login request contain token
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
? $this->StatusCode($token,$this->credentials($request),$status=false) : $this->StatusCode($token,$this->credentials($request),$status=true);
}
And I have added this method to request access token and send it as json response :
public function StatusCode($token,$user,$status){
if( $token != null && $token != ''){
return ($status == true) ? response()->json(GetToken($user),200) : response()->json(['Message' => 'Failed to log in'],403);
}
function GetToken($userobject)
{
$http = new Client;
$response = $http->post('http://localhost/iranAd/public/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => '1',
'client_secret' => 'xKqNbzcXyjySg20nVuVLw5nk5PAMhFQOQwRTeTjd',
'username' => $userobject['email'],
'password' => $userobject['password'],
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
}
function RefreshToken($token,$userobject)
{
$http = new Client;
$response = $http->post('http://localhost/iranAd/public/oauth/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => 'refresh_token',
'client_id' => '1',
'client_secret' => 'xKqNbzcXyjySg20nVuVLw5nk5PAMhFQOQwRTeTjd',
'username' => $userobject['email'],
'password' => $userobject['password'],
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
}
return ($status == true) ? response()->json(GetToken($user),200) : response()->json(['Message' => 'Failed to log in'],403);
}
Same Procedure for register users.
The purpose of this post is not to answer(as already answered) but to give more info to other readers who eventually need more info on topic.
This is very helpfull tutorial just on this issue Implementing Vue.js 2.0 and Laravel 5.3 with CORS problem solution
Check this one and 2 next clips.
Some of this you can find in shorter form here here

Cakephp 3 HTTP Basic Authentication login issue

I am using basic authentication in my project to access Api. In ApiController, I added below code in beforeFilter:
$this->Auth->config('authenticate', [
'Basic' => [
'fields' => ['username' => 'username', 'password' => 'api_key'],
'userModel' => 'Users'
]
]);
So from chrome postman application, I am sending post request with basic auth credentials. for example like below:
So when I send a request, I get unauthorized error back.
you are sending a post request with a 'password' field
Your application is expecting a 'api_key' field that would contain the password.
I think you missed this one script in your model entity.
use Cake\Auth\DefaultPasswordHasher;
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
Put this one in Model/Entity/User.php

How to create cakephp database config settings (login, password) dynamically

Every cakephp user will have his database(Postgres) user replica. Therefore when he logs in, the database default config must take the "login" and "password" sent in the login.ctp form and with those values create the DATABASE_CONFIG. So far I have this, but I can't figure it out how to pass variables to the constructor. Is it possible? Is there an alternative?. Please help.
enter code here
class DATABASE_CONFIG{
var $default = array(
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => 'localhost',
'login' => 'XXX',
'password' => 'YYY',
'database' => 'db1',
'prefix' => '',
'schema'=>'public'
//'encoding' => 'utf8',
);
function __construct(){
$this->default['login'] = $userSentFromForm;
$this->default['password'] = $passwordSentFromForm;
}
}
I think that you should have some global database with users which stores login information (username and hashsed password) so you can validate & login user.
When user logs-in you save data from that form into the session.
Then you redirect the user to some action, like /dashboard or any else. Following request will have your desired data in session object, so you can read it in DATBASE_CONFIG::__construct().

CakePHP + Facebook

I am trying to implement facebook Connect to my cakephp Application. i am using Nick's Facebook Plugin.
I wanna implement it this way
When a user Visits the Site he should be able to login via Registration on the site or Facebook Connect
Existing users should be able to connect their account to their FB account
People who first time login to the site using FB Connect and dont have an account on the site. should be redirected to a page where they have to enter details to complete the profile.
What i have done -
I have followed the instruction of Nick to implement it and when i click Login - it connects to my app. but i dont understand how to create a username and password associated with the Fb Connect Id. and user it against the FB token.
Apparently I'm doing the same thing a little before you... ;-)
Here's a method for Facebook login I'm using (slightly redacted and annotated):
public function facebook($authorize = null) {
App::import('Lib', 'Facebook.FB');
$Fb = new FB();
$session = $Fb->getSession();
// not logged into Facebook and not a callback either,
// sending user over to Facebook to log in
if (!$session && !$authorize) {
$params = array(
'req_perms' => /* the permissions you require */,
'next' => Router::url(array('action' => 'facebook', 'authorize'), true),
'cancel_url' => Router::url(array('action' => 'login'), true)
);
$this->redirect($Fb->getLoginUrl($params));
}
// user is coming back from Facebook login,
// assume we have a valid Facebook session
$userInfo = $Fb->api('/me');
if (!$userInfo) {
// nope, login failed or something went wrong, aborting
$this->Session->setFlash('Facebook login failed');
$this->redirect(array('action' => 'login'));
}
$user = array(
'User' => array(
'firstname' => $userInfo['first_name'],
'lastname' => $userInfo['last_name'],
'username' => trim(parse_url($userInfo['link'], PHP_URL_PATH), '/'),
'email' => $userInfo['email'],
'email_validated' => $userInfo['verified']
),
'Oauth' => array(
'provider' => 'facebook',
'provider_uid' => $userInfo['id']
)
);
$this->oauthLogin($user);
}
This gives me an array with all the user details I could grab from Facebook and invokes ::oauthLogin, which either logs the user in with the given information or asks the user to fill in missing details and/or creates a new user record in the database. The most important part you get from the Facebook API is the $userInfo['id'] and/or email address, either of which you can use to identify the user in your database. If you're using the AuthComponent, you can "manually" log in the user using $this->Auth->login($user_id), where $user_id is the id of the user in your own database.
private function oauthLogin($data) {
$this->User->create();
// do we already know about these credentials?
$oauth = $this->User->Oauth->find('first', array('conditions' => $data['Oauth']));
if ($oauth) {
// yes we do, let's try to log this user in
if (empty($oauth['User']['id']) || !$this->Auth->login($oauth['User']['id'])) {
$this->Session->setFlash('Login failed');
}
$this->redirect('/');
}
// no we don't, let's see if we know this email address already
if (!empty($data['User']['email'])) {
$user = $this->User->find('first', array('conditions' => array('email' => $data['User']['email'])));
if ($user) {
// yes we do! let's store all data in the session
// and ask the user to associate his accounts
$data['User'] = array_merge($data['User'], $user['User']);
$data['Oauth']['user_id'] = $user['User']['id'];
$this->Session->write('Oauth.associate_accounts', $data);
$this->redirect(array('action' => 'oauth_associate_accounts'));
}
}
// no, this is a new user, let's ask him to register
$this->Session->write('Oauth.register', $data);
$this->redirect(array('action' => 'oauth_register'));
}
Look no further. Here is an excellent article that'll guide you all the way through (minus any readymade plugins):
Integrating Facebook Connect with CakePHP's Auth component
Simply follow the approach described in there.
Cheers,
m^e

Resources