Error Laravel\Socialite\Two\InvalidStateException In the callback method from the Google side - laravel-5

I want use Socialite package but receive in Error !
controller codes :
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Laravel\Socialite\Facades\Socialite;
class GoogleAuthController extends Controller
{
public function redirect()
{
return Socialite::driver('google')->redirect();
}
public function callback()
{
// when i dd() here i see in the answer in the browser.
$googleUser = Socialite::driver('google')->user();
// but dd in here isn't working!
$user = User::where('email', $googleUser->email)->first;
if ($user) {
auth()->loginUsingId($user->id);
} else {
$newUser = User::create([
'name' => $googleUser->name,
'email' => $googleUser->email,
'password' => bcrypt(\Str::random(16)),
]);
auth()->loginUsingId($newUser->id);
}
return $this->redirect('/');
}
}
in web.php :
Route::get('auth/google', 'Auth\GoogleAuthController#redirect')->name('auth.google');
Route::get('auth/google/callback', 'Auth\GoogleAuthController#callback');
laravel version : 6.20.26
php version : 7.2.5
please help me. tnks
===============================================================
I try this (https://stackoverflow.com/a/37849202/20355717) :
Socialite::driver('google')->stateless()->user()
but in did't work for me and give error ! :
GuzzleHttp\Exception\RequestException
cURL error 77: error setting certificate verify locations: CAfile: /path/to
/downloaded/cacert.pem CApath: none (see https://curl.haxx.se/libcurl
/c/libcurl-errors.html) for https://www.googleapis.com/oauth2/v4/token
http://localhost:8000/auth/google/callback?authuser=0&code=4%2F0AfgeXvucuWTlboWqaMwf2bkBe0AHjbPEJd-
2e7cQdlSN345_3imguhVT_1PQ8fa3ISoHSA&prompt=consent&
scope=email%20profile%20openid%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&
state=axIlfjFkns6vWNJIX2uJMuMKNiYFfy7cKiE8Xr8W

1- change :
Socialite::driver('google')->user()
to in :
Socialite::driver('google')->stateless()->user()
2- download cacert.pem add this code in php.ini file.
curl.cainfo = "D:\wamp64\bin\php\php7.4.26\cacert.pem
like this https://stackoverflow.com/a/40861755/20355717
3- change
return $this->redirect('/');
in controller to
return view('welcome'); //or an any other view.
4- finish! hope helpful for you!

Related

cookie::make does not save the cookie in Laravel 8

Am I missing something? I am pulling my hair to solve this simple use of cookie. My intention is simply to save a variable for each user (I tried session and there were side effect issues). The below code should theorically save the cookie which should be there at the next call of the page, correct? It does not work. What am I missing?
class TestController extends Controller
{
public function show($page) {
echo #Cookie::get('testcookie');
if (Cookie::get('testcookie')) { echo 'cookie exists<br>'; }
else { echo 'cookie does not exist<br>'; }
$cookie = Cookie::make('testcookie','5', 120);
echo $cookie;
return view('tests.'.$page,['page' => $page]);
}
}
I have also modified config/session.php as recommended for use on http://localhost. Should I clean/cache... or similar after that. I am using laravel 8 & FF on OSX.
'secure' => env('SESSION_SECURE_COOKIE', false)
Can someone please tell me what I am doing wrong?
If I try the other way with response...
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
public function show($page, Request $request)
{
echo $request->cookie('name');
if ($request->cookie('name')) { echo 'cookie exists<br>'; } else { echo 'cookie does not exist<br>'; }
$response = new Response('Set Cookie');
$cookie = $response->withCookie(cookie('testcookie','5', 120));
echo $cookie;
return view('tests.'.$page,[
'page' => $page
]);
}
I get an error "Call to undefined method Illuminate\Support\Facades\Response::withCookie() ".
Why is it so complicated and so simple in php?
You must send maked cookie with response.
Cookie::make() just create cookie object on your backed - but, if you not send them to user - he cannot save them.
class TestController extends Controller
{
public function show($page) {
//for debug
if ($cookie = Cookie::get('testcookie')) { dump ($cookie); }
$cookie = Cookie::make('testcookie','5', 120);
return response()
->view('tests.'.$page,['page' => $page])
->withCookie($cookie);
}
}

How to work hash_hmac function in codeigniter or laravel?

How to work hash_hmac function in codeigniter or laravel with example
This is Work On Php So, you Can use in codeigniter or laravel.
Synatx :
string hash_hmac( $algo, $msg, $key, $raw_opt );
Code :
<?php
echo hash_hmac('md5','hash hmac example','DATA');
?>
Ans :
9c9c195ece5f36ea04df7cf5658baa25
Try this :
public function makeHash(Request $request)
{
$request->user()->fill([
'password' => Hash::make($request->newPassword)
])->save();
}
also add, use Illuminate\Support\Facades\Hash;
This way you can make the hash.

Laravel/Lumen file response

I need to stream file content (such as images and other mime types) from a Lumen resource server to a Laravel client server. I know in Laravel I can use:
$headers = ['Content-Type' => 'image/png'];
$path = storage_path('/mnt/somestorage/example.png')
return response()->file($path, $headers);
However, the file method is absent in Laravel\Lumen\Http\ResponseFactory.
Any suggestions are very welcome.
In Lumen you can use Symfony's BinaryFileResponse.
use Symfony\Component\HttpFoundation\BinaryFileResponse
$type = 'image/png';
$headers = ['Content-Type' => $type];
$path = '/path/to/you/your/file.png';
$response = new BinaryFileResponse($path, 200 , $headers);
return $response;
You can find the documentation here.
There is a function in Lumen:
https://lumen.laravel.com/docs/8.x/responses#file-downloads
<?php
namespace App\Http\Controllers;
use App\Models\Attachment;
use Illuminate\Http\Request;
class AttachmentController extends AbstractController
{
/**
* Downloads related document by id
*/
public function attachment(Request $request)
{
$path = "path/to/file.pdf";
return response()->download($path);
}
}

Adding # (at) sign to laravel route

I want to add # symbol to url. Just like this. I have tried this in web.php.
Route::get('/#{user}', 'ProfilesController#show');
It did not work. Then I tried Route::get('/#/{user}', 'ProfilesController#show');
It worked but how can I remove the (slash) '/' between # symbol and user id ?
User model:
public function getRouteKeyName()
{
return 'nick';
}
ProfilesController:
public function show(User $user)
{
return view('profiles.show', [
'profileUser' => $user
]);
}
web.php:
Route::get('/#{user}', 'ProfilesController#show');
The way you have it should work. Check your controller code to make sure you are accepting the variable. The code below is what we have working on our site.
web.php
Route::get('/#{username}', [
'as' => 'profile',
'uses' => 'ProfilesController#show'
]);
ProfilesController.php
public function show($username){
...
}
You are better off refactoring your code.. the # sign is a reserved character as is stated here

How to get a custom message on fail login credentials in Laravel?

I use this code to check user credentials, but I can't figure how to change the code to get an error message when credentials fail. Used redirect and so on, but show nothing....
public function loginWithCredentials(Request $request) {
$signinEmail = $request->input('email');
$signinPassword = $request->input('password');
$user = new Users();
$errors = new MessageBag;
$user = $user
->where('email', '=', $signinEmail)
->get()->first();
if(empty($user)) {
$errors->add('error', 'Invalid credentials!');
return json_encode([
'error'=>true,
'messages'=>$errors
]);
}
$userdata = $user->toArray();
if(md5($signinPassword) != $userdata['password']) {
$errors->add('error', 'Invalid credentials!');
return redirect()->guest('auth/login');
}
Session::put('user',$userdata);
$errors->add('message0', 'Welcome ' . strtoupper($userdata['username']) . '!');
}
Now it just simple redirects me to a white page with the "invalid credentials" message. I want the message to be on login page.
Your code you has some flaws, consider fixing it.
Why are you mixing json response with html response?
Consider using bcrypt() for hashing your users passwords instead md5().
Add some sort of validation, Laravel has the built in validation.
Laravel ships with easy use login auth, take a look at.
So in your code needs some changes here it is:
public function loginWithCredentials(Request $request) {
$signinEmail = $request->input('email');
$signinPassword = $request->input('password');
$user = new Users();
$user = $user
->where('email', '=', $signinEmail)
->get()->first();
if(empty($user) || md5($signinPassword) != $user->password) {
return redirect()->back()->with('message', 'Invalid credentials!');
}
$userdata = $user->toArray();
Session::put('user', $userdata);
return view('view.name')->with('message', 'Welcome ' . strtoupper($userdata['username']) . '!');
}
Then in your view you write the success message like so:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
this example is using blade, but should be similar to other views.
You just need to override AuthenticatesUsers Trait method named sendFailedLoginResponse like this:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
class LoginController extends Controller
{
use AuthenticatesUsers;
...
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
'your array key' => ['Place your custom message here'],
]);
}
...
}
That's It!
I hope this will help you. :)

Resources