Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an
Instance of Illuminate\Contracts\Auth\Authenticatable, instance of
Illuminate\Http\Request given
The question is not very descriptive. But from the title and the error, I am assuming you are trying to login to your application using another application login API.
For that, you need to build your own custom authentication system, middlewares for protecting authorized routes etc., as laravel default Auth will not work since it depends on Authenticatable contract which in return depends on user modal of the applicaiton.
If that another API, happened to be one of the Social media, in that case, you can use socialite driver.
public function userlogin(Request $request){
$validatedData = $request->validate([
'email' => 'required|max:255',
'pwd' => 'required|max:255|min:3',
]);
$data = [ "username"=>$request->email,
"password"=>$request->pwd,
];
$ch = curl_init("http://localhost/getuus/login");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$result = collect(json_decode($result));
if ($result['status'] == 1) {
$Auth = new Auth; $Auth::login($request, true);
return redirect('home');
}
else{
return view('userlogin');
}
}
Related
In laravel 9, breeze 1.11 app I want to make feature test for forgot-password functionality and in routes I found :
GET|HEAD
In laravel 9, breeze 1.11 app I want to make feature test for forgot-password functionality and in routes I found :
GET|HEAD forgot-password ... password.request › Auth\PasswordResetLinkController#create
POST forgot-password ........ password.email › Auth\PasswordResetLinkController#store
So I make :
test to check opened form :
public function testAdminForgetPasswordFormOpened()
{
$response = $this->get(route('password.request'));
$response->assertStatus(200);
$response->assertViewIs('auth.forgot-password');
$response->assertSessionHasNoErrors();
}
and it works ok. But I failed to check how token is sent when user submit form with email entered. I do :
public function testAdminGotPasswordResetLinkEmail()
{
Notification::fake();
$loggedAdmin = User::factory()->make();
$response = $this->post(route('password.email'), [
'email' => $loggedAdmin->email,
]);
$token = DB::table('password_resets')->first();
Notification::assertSentTo(
$loggedAdmin,
SubscriptionEmailingNotification::class,// that is my my Notification class
function ($notification) use ($token) { // https://laravel.com/docs/9.x/mocking#notification-fake
\Log::info(varDump($notification, ' -1 $notification::')); / I DO NOT SEE THESE LOG MESSAGES
\Log::info(varDump($token, ' -12 $token::'));
return Hash::check($notification->token, $token->token) === true;
}
);
}
But I got error :
1) Tests\Feature\AuthTest::testAdminGotPasswordResetLinkEmail
The expected [App\Notifications\SubscriptionEmailingNotification] notification was not sent.
Failed asserting that false is true.
/mnt/_work_sdb8/wwwroot/lar/MngProducts/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/NotificationFake.php:83
/mnt/_work_sdb8/wwwroot/lar/MngProducts/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:338
/mnt/_work_sdb8/wwwroot/lar/MngProducts/tests/Feature/AuthTest.php:226
Looking how it works in breeze I see method :
$status = Password::sendResetLink(
$request->only('email')
);
I did not find how method above is implemented and which notification it uses ?
I suppose that some notification is used here, but not sure...
I found declaration of assertSentTo method as :
public static function assertSentTo($notifiable, $notification, $callback = null)
{
How that tests must be done ?
Thanks!
You shouldn't check the token in the email if you continue to use the Password::sendResetLink(...) method. Breeze already has its own tests for this. Proving the Password::sendResetLink(...) method is successfully called will be enough to confirm faultless integration. You can verify it by checking the "ResetPassword" notification:
Notification::assertSentTo($user, ResetPassword::class);
However, if you still want to check the token, you can use the sample code below, which took from Breeze's tests
use App\Models\User;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Support\Facades\Notification;
// ...
public function test_password_can_be_reset_with_valid_token()
{
Notification::fake();
$user = User::factory()->create();
$this->post('/forgot-password', ['email' => $user->email]);
Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
$response = $this->post('/reset-password', [
'token' => $notification->token,
'email' => $user->email,
'password' => 'password',
'password_confirmation' => 'password',
]);
$response->assertSessionHasNoErrors();
return true;
});
}
Source: https://github.com/laravel/breeze/blob/v1.11.0/stubs/default/tests/Feature/PasswordResetTest.php#L50
I've been trying to return user data using access token but keep getting error:
Invalid payload
My method was to get the token then find the user id from oauth_access_tokens table. My code is as follows:
public function authenticateUser($token){
$user_id = DB::table('oauth_access_tokens')->where('id', trim($token))->value('user_id');
$user = \App\User::find($user_id);
Auth::login($user, true);
}
The token is something like this:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjkyZGU3ZGYyMDcxZjgzMzU5YWUxMmRlYzM4ZGJiM2EyMTk0NzEyYTQ5NmRiNzgwZWJkMDg2Yjc0NThkZjU0NmFlZmU2Yzg0N2Q0Mjc5MDAxIn0.eyJhdWQiOiIxIiwianRpIjoiOTJkZTdkZjIwNzFmODMzNTlhZTEyZGVjMzhkYmIzYTIxOTQ3MTJhNDk2ZGI3ODBlYmQwODZiNzQ1OGRmNTQ2YWVmZTZjODQ3ZDQyNzkwMDEiLCJpYXQiOjE1NzczNzE4MDYsIm5iZiI6MTU3NzM3MTgwNiwiZXhwIjoxNjA4OTk0MjA1LCJzdWIiOiIzMCIsInNjb3BlcyI6W119.Io4xkJYEczbI7rhFD_UKAoe7v_1-RLJXjA6XqGIe2nRAWEgMkg-mokQUiGz41xYVazmDmACDwwYSRr-iTTzwc591NABfxsmMk7OdYkUKb93UTA3JhKClEGSP82y1QrIfm9XTZ0KKDaCKlfKqye1Aobj9zFthQdApegTaK61ReLQa7MzO6EM5fcZ3udsLL3QpKXFuyO6JcPKRauKIbA8oNIKEdadprLWJSeQieIyA8lpYOr453QzgZGgzCwPY1U2RmIbCzqyNQD_L5264-ix1503KxgPt4F_Cl82WXm7tNsZKNwE-vGKhCc2CcgAgTV1lIj7ItDf2KpDh_Jt96Uiv2eJ3OtXYvuOTErz9mNnQ1T38hxQmKDh8XlG3f7JgIWWzN6m8ItBV1KyGZi0-vn2HXetkZTNIyfJV8E5-RaGUzIKX7RejWd5BVaqFw0OjDYPeliVOaZzfcZCRnPDSJBGwf7YqJrRXP61LMasn_ZJ-i8G5JIaQx2vdmfYgE41O5F9fE5uEF5-mIV979RbnswL6CJsSGmmUMzC7mPhqL6HtPu2hMTnfHbKY0-efqtzZ5I2TBQU6ODM37RFN5TEljoEgBFG6kAImkGDy4QFH5uqt6V7-ZFxvrKQzQozgezSgA6ITF1sRb7yWfI-9rF7sYE_aKu3r1_KRr4UJLoZqFyvGPP0
Isn't it the token that I should pass to the function above. When I pass it to base64_decode, I see the JSON object along with other gibberish. What am I doing wrong here?
I have never used Laravel Passport before, but I would imagine that the user is already authenticated when using the token. So maybe a route like:
Route::get('/user', function(Request $request) {
return Auth::user();
})->middleware('auth:api');
I've reached to way to do so eventually by sending a request to the api in the other machine while adding the token in the header:
public function authenticateUser($token) {
$client = new \GuzzleHttp\Client();
try {
$response = $client->request('GET', env('APP_API_URL') . '/api/v2/user_data', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
]);
$request = (string) $response->getBody();
$request = json_decode($request);
$user = User::where('email', $request->data->user->email)->first();
Auth::login($user, true);
} catch (RequestException $e) {
dd('Something went wrong while connection to the api');
}
}
when user register, i need to pass registration field value to other controller also. this other controller will send information to outside api as post to register other websites.
I try to redirect with data but i think i just totally lost. this is my second controller
public function registerUser()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api01.oriental-game.com:8085/register");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->xtoken);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
"username" => "test2",
"country" => "Korea",
"fullname" => "Hihi User",
"language" => "kr",
"email" => "myuser123#test.com",
"birthdate" => "1992-02-18"
)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
}
when user register to our site, it will automatically create account in our own site and other 2 websites through their register api.
thanks in advance for your help.
Instead of redirecting from function to function by means of HTTP redirects why not pass the form-data from your register form to a /register-user route and in the routes corresponding controller method catch the form data there.
Your form will post to something like this so make sure you have a route to first controller:
Route::get('/register-user', 'RegisterControllerNameHere#index');
Inside the first controllers function call the registerUser() in the second Controller like:
public function registerUser(Illuminate\Http\Request $request) {
(new \App\Http\Controllers\SecondControllerName)->registerUser($request>all());
}
Also allow for parameters to be passsed to the second controller:
public function registerUser($userData) // add parameter
Now $userData will have the same data as the first controller which you can pass to your API call.
Does this help answer your question?
I am trying to make a PUT request, in order to edit some user's data, but I am receiving empty data instead of what I'm sending through my request.
I have tried with postman (a chrome plugin) and with a custom php snippet:
?php
$process = curl_init('http://localhost/myapp/api/users/1.json');
$headers = [
'Content-Type:application/json',
'Authorization: Basic "...=="'
];
$data = [
'active' => 0,
'end_date' => '01/01/2018'
];
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_PUT, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);
print_r($return);
This is the code that I'm using cakephp-side:
class UsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
....
public function edit($id = null)
{
debug($_SERVER['REQUEST_METHOD']);
debug($this->request->data);
die;
}
....
And this is what it outputs:
/src/Controller/UsersController.php (line 318)
'PUT'
/src/Controller/UsersController.php (line 319)
[]
I am confused... similar code is working for a POST request and the add action... what is wrong with this code?
Two problems.
When using CURLOPT_PUT, you must use CURLOPT_INFILE to define the data to send, ie your code currently doesn't send any data at all.
CURLOPT_PUT
TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
http://php.net/manual/en/function.curl-setopt.php
You are defining the data as an array.
CURLOPT_POSTFIELDS
[...] If value is an array, the Content-Type header will be set to multipart/form-data.
http://php.net/manual/en/function.curl-setopt.php
So even if the data would be sent, it would be sent as form data, which the request handler component wouldn't be able to decode (it would expect a JSON string), even if it would try to, which it won't, since your custom Content-Type header would not be set unless you'd pass the data as a string.
Long story short, use CURLOPT_CUSTOMREQUEST instead of CURLOPT_PUT, and set your data as a JSON string.
curl_setopt($process, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($process, CURLOPT_POSTFIELDS, json_encode($data));
Your Postman request likely has a similar problem.
I'm trying to write a CodeIgniter controller to handle OAuth2 authentication for the 37signals' Basecamp API.
The problem is I keep encountering the 'internal checksum failed' error, when trying to connect (via cURL) to https://launchpad.37signals.com/authorization.json, providing the Auth Token in a HTTP header.
Here's the index and _authcode functions from my controller class:
<?php
// constants:
// BC_REQUEST_URL = 'https://launchpad.37signals.com/authorization/new'
// BC_TOKEN_URL = 'https://launchpad.37signals.com/authorization/token'
// ...
public function index() {
// if get data is set.
if ($this->input->get()) {
// if auth code is provided via GET, switch to _authcode method.
if ( $code = $this->input->get('code') ) {
return $this->_authcode($code);
}
// On error, kill yourself.
if ( $error = $this->input->get('error') ) {
die($error);
}
}
// redirect to 37 signals to get an authcode
header("Location: ".BC_REQUEST_URL."?type=web_server&client_id=".BC_CLIENT_ID."&redirect_uri=".BC_REDIRECT_URL."");
}
// handles the Authentication code that is returned by 37 Signals.
private function _authcode($code) {
// set vars to POST
$vars = array(
'type' => 'web_server',
'client_id' => BC_CLIENT_ID,
'redirect_uri' => BC_REDIRECT_URL,
'client_secret' => BC_CLIENT_SECRET,
'code' => $code
);
// make a request for the access_token
$url = BC_TOKEN_URL;
$c = curl_init($url);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($vars));
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($c));
curl_close($c);
unset($c,$url);
// get the access vars from this request
$expiry_seconds = $response->expires_in; // default: 1209600 (14 days)
$refresh_token = $response->refresh_token;
$access_token = $response->access_token;
unset($response);
// make a separate request to get user info for current user.
$url = "https://launchpad.37signals.com/authorization.json";
$c = curl_init($url);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer <$access_token>",
"Content-Type: application/json; charset=utf-8",
"User-Agent: MyApp (http://myapp.example.com)"
));
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($c)); // reply from 37 signal auth
curl_close($c);
unset($c,$url);
echo "response obj = " . print_r($response,1);
/* prints: response obj = stdClass Object ( [error] => OAuth token could not be verified. The internal checksum failed, so the token data was somehow mangled or tampered with. ) */
// get the user data from this request
// $expires_at = $response->expires_at; // the timestamp for when this request expires
// $identity = $response->identity; // the current user
// $accounts = $response->accounts; // list of accounts we can access
// unset($response);
// store the response data to the database for easy recall.
// $this->db->query("REPLACE INTO `sometable` SET `key1`='value', `key2`='value');
}
// ...
?>
I ran into this error when saving the auth token in the database with varchar(255). Basecamp's auth token has some checksum data which brings the token over 255 characters.
You don't appear to be pulling it from a database in your example, so this might not affect you, however checking for Basecamp's token being cut off is what I would first look at.
Optionally, remove the <> characters around your $access_token when setting the Bearer header.