Laravel auth gurad check is not working in constructor - laravel

Having the below code in constructor,
public function __construct(){
if (Auth::guard('admin')->check()){
dd(Auth::guard('admin')->user()->name);
}
}
This is not working.
But this is working in other controller functions.

Since Laravel 5.3 you are no longer able to access session (and thus Auth stuff as well) in controller constructors, because session middleware has not run yet.
5.3 changes - scroll to "Session In The Constructor" to see how to get around it.

Related

Bitcoind walletnotify configure on Laravel does not work

I have successfully configured bitcoind and connected it from a Laravel application. My issue now is walletnotify does not get triggered when a new transaction comes on an internally generated address.
bitcoin.conf
maxconnections=12
rpcuser=user
rpcpassword=pass
test.rpcport=18332
rpcallowip=0.0.0.0/0 --testing purposes
keypool=10000
server=1
testnet=1
txindex=1
walletnotify=/usr/bin/curl http://127.0.0.1/notify/%s
I have also tried with:
walletnotify=curl http://127.0.0.1/notify/%s
The route:
Route::get('/notify', 'HomeController#notify');
The Controller:
public function notify($tx) {
$txinfo = Bitcoind::getRawTransaction($tx, true);
$txinfo = $txinfo->get();
.....
}
Notes:
Blockchain is synced.
I have checked the debug.log from bitcoin but no errors from walletnotify or at least the curl when it should run.
If I manually call the route and pass a txid, everything goes well.
Thanks in advance for any help!
Problem solved!
WalletNotify config below works just fine.
walletnotify=curl http://127.0.0.1/notify/%s
The problem was I build the function that verifies the transaction in the HomeController, which is guarded by the AUTH middleware. As I started this for testing purposes, I forget about the guard from the HomeController which is created by laravel authentication scaffolding.

Laravel 6.2 API, DELETE and PUT not working

Edit: Solved: the problem was the trailing slash on the urls
I cannot use the destroy() and update() methods of my API, it executes only the show() method.
routes:list shows all routes correctly and the controller has all required methods.
Authentication works correctly over Bearer Token.
api.php:
Route::apiResource('subscriptions', 'Api\SubscriptionController')->middleware('auth:api');
called urls:
DELETE http://127.0.0.1/api/subscriptions/2/
DELETE http://127.0.0.1/api/subscriptions/2/?_method=delete
Same with PUT and POST instead of DELETE, always executes the show() method.
store() and index() methods are working.
Used Versions:
Laravel 6.2
Php 7.2.23
Postman 7.13 (for requests)

No notifications are returned

I am trying to get user's unread notifications though my controller.
This works:
public function notifications(){
return \App\User::find(auth()->user()->id)->unreadNotifications()->limit(5)->get();
}
This doesn't, it returns an empty collection:
public function notifications(){
return auth()->user()->unreadNotifications()->limit(5)->get();
}
Could you tell me what I am missing? Thanks in advance.
Using Laravel 5.8 with Backpack 3.5.
The default auth guard of Laravel is overwitten to use Backpack auth in backpack routes, using the UseBackpackAuthGuardInsteadOfDefaultAuthGuard middleware of the permissions manager package. In the rest of the controller auth() and backpack_auth works normally.
Try this:
public function notifications()
return Auth::user()->unreadNotifications()->limit(5)->get();
}
As said in the docs:
You may access the authenticated user via the Auth facade:
Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods:
Auth and auth() likely don't work here because you're using the Backpack For Laravel authentication which uses a different guard than the default one Laravel uses.
This would probably work for you:
backpack_user()->unreadNotifications()->limit(5)->get();
If that works, here's why:
If you take a look at project/vendor/backpack/base/src/helpers.php you'll see that backpack_user() is an alias for backpack_auth()->user() and backpack_auth does a:
return \Auth::guard(backpack_guard_name());
That's the important bit because it grabs the guard defined config/backpack/base.php (which is backpack by default) and uses that instead of Laravel's default guard of web.

Where to check if an User is logged in in a Laravel Application?

I've been using your advice and View::sharing all of my important data to all views. However, there is one issue I have encountered.
This code:
if(!Auth::guest()){
$user=Auth::user()->id;
}
else $user=0;
$temp=DB::select('query');
View::share('cartnumber', count($temp));
View::share('cartitems', $temp);
doesn't work when put in AppServiceProvider. Or better, it always sets $user=0, even if I am logged in. I thought it is because AppServiceProvider's boot function executes before the site checks if someone is logged in.
I then tried to use a BaseController with a construct function but that doesn't work either. The only solution that seems to work correctly is putting the code in every single Controller for every view! That actually works, which kind of confirms my theory.
But is there anywhere I can put this code without having to copy/paste it in every single Controller? Thanks in advance!
You'd likely want to put this code later in the request life cycle to guarantee an auth user because as others have mentioned middleware/session code has not occured during this part of the framework booting up. You could use a service class to call in all your controllers to avoid the copy pasting. Or If you'd like to achieve this using code in your service provider you could use a View Composer instead of a share this allows you to define a callback/or class that will be called right before the view is returned
view()->composer(['/uri-that-needs-data'], function ($view) {
if (Auth::check()) {
$cart = DB::query(...)->get();
$view->with('cartitems', $cart);
}
});
Check out https://laravel.com/docs/5.7/views#view-composers for more details.
Auth::user() will be empty until the session middleware has run.
The reason you can't access the user inside your service provider is because that code is run during the "bootstrapping" phase of the application lifecycle, when it's doing things like loading filesystem or cache drivers, long before the request is sent through response handlers (including middleware).
Once the application has been bootstrapped and all service providers
have been registered, the Request will be handed off to the router
for dispatching. The router will dispatch the request to a route or
controller, as well as run any route specific middleware.
Source: https://laravel.com/docs/5.7/lifecycle
If you don't want to copy/paste that code everywhere, then one place to put it is in custom route middleware. You can list it after the auth middleware to guarantee a logged-in user.
Edit: View composers are another really good option, as suggested by #surgiie. The reason these can be set up inside a service provider (unlike your example) is because the view composer registers a callback, but doesn't execute it until a much later stage in the application lifecycle.

Laravel 5 - Is there a way to use built-in authentication but disable registration?

I am building an administrative back-end and thus need to hide public user registration. It appears that if you want to use the built-in Illuminate authentication you need to add
use AuthenticatesAndRegistersUsers to your controller definition. This trait is defined here.
It appears as if it is impossible to disable registration if you want to use the built-in auth handlers... can someone show me wrong?
I'm using Laravel 5.2+ and I found that if you remove the Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers and use just Illuminate\Foundation\Auth\AuthenticatesUsers does the trick too.
Though /register is still accessible and will throw a fatal error.
This page talks about overriding the auth controller. Its worth a read, at a basic level it seems you can add the following lines to app\Http\Controllers\Auth\AuthController.php :
public function getRegister() {
return redirect('/');
}
public function postRegister() {
return redirect('/');
}
So if a user accesses the registration url it will redirect them away to a place of your choosing.
You can have your own form of registration. The only thing Laravel does is make it easy to authenticate on a users table because they create the model, build the db schema for users and provide helper methods to authenticate on that model/table.
You don't have to have a view hitting the registration page... But if you want to use the built in auth you still need to use (or set) a Model and a driver for database connections.
You can just remove that view and/or controller method from the route that links to the registration view and create your own (or seed the database manually).
But, no, you cannot forgo using Eloquent, and the User model and expect to use built in auth. Built in authentication requires that you specify settings in /config/auth.php. You may specific a different model (other than User) and you may specify a different table, but you cannot forgo the configuration completely.
Laravel is very customizable though, so you can achieve what you are looking to do... plus why not use Eloquent, it's nice.
Based on #shoo's answer, working with Laravel 5.2
Add the following lines to app\Http\Controllers\Auth\AuthController.php :
public function showRegistrationForm() {
return redirect('/');
}
public function register() {
return redirect('/');
}

Resources